@chenpu17/cc-gw 0.17.0 → 0.17.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +5 -5
- package/src/web/dist/assets/{About-D2m94wu2.js → About-DmIV-sHO.js} +1 -1
- package/src/web/dist/assets/{ApiKeys-Bt-otGF_.js → ApiKeys-BNr4zbD6.js} +1 -1
- package/src/web/dist/assets/{ConfirmDialog-CRSbmgE7.js → ConfirmDialog-_CIYYtzo.js} +1 -1
- package/src/web/dist/assets/{Dashboard-81qp43jm.js → Dashboard-Hg4OZNAc.js} +1 -1
- package/src/web/dist/assets/{DialogShell-DxWKa5oR.js → DialogShell-D1T4HXtd.js} +1 -1
- package/src/web/dist/assets/Events-CO2wWiEK.js +1 -0
- package/src/web/dist/assets/{Help-XaAZ__Kz.js → Help-CafNfXfx.js} +1 -1
- package/src/web/dist/assets/{Login-atwWPGzz.js → Login-C04-poiG.js} +1 -1
- package/src/web/dist/assets/Logs-CqaIXvR0.js +1 -0
- package/src/web/dist/assets/{PageSection-CC5EhfMe.js → PageSection-Dd2-9G6C.js} +1 -1
- package/src/web/dist/assets/{PageState-XybOeENt.js → PageState-Bbhr4fy6.js} +1 -1
- package/src/web/dist/assets/{PageToolbar-CnLp4aWt.js → PageToolbar-GyUQBhmq.js} +1 -1
- package/src/web/dist/assets/{ProvidersPage-CFCY2xSG.js → ProvidersPage-CHvyCANH.js} +1 -1
- package/src/web/dist/assets/{RoutingPage-35o5ZSMg.js → RoutingPage-fVr25VKF.js} +1 -1
- package/src/web/dist/assets/{Settings-DC1TPeS9.js → Settings-DfaIYHsa.js} +1 -1
- package/src/web/dist/assets/{Setup-CnQPVK9X.js → Setup-DUEpie5k.js} +1 -1
- package/src/web/dist/assets/{TargetCombobox-DkVdA04_.js → TargetCombobox-CSnHZqDY.js} +1 -1
- package/src/web/dist/assets/{apiKeys-CMk2nxB_.js → apiKeys-B5Os17Qm.js} +1 -1
- package/src/web/dist/assets/app-DZpd2fu9.js +61 -0
- package/src/web/dist/assets/{badge-eRkhnmCs.js → badge-CWbm9P64.js} +1 -1
- package/src/web/dist/assets/{chartTheme-Cx-0Jiew.js → chartTheme-ChTod603.js} +1 -1
- package/src/web/dist/assets/{charts-core-BOHudNiN.js → charts-core-BuoE1ECx.js} +1 -1
- package/src/web/dist/assets/{charts-engine-BhFpDbO0.js → charts-engine-DHIzBJl6.js} +1 -1
- package/src/web/dist/assets/{charts-react-CPWg-GRD.js → charts-react-BLOapElb.js} +1 -1
- package/src/web/dist/assets/{currency-Bx141-XL.js → currency-DffG4uWM.js} +2 -2
- package/src/web/dist/assets/{disclosure-CU-KJc8C.js → disclosure-W_XtxMJz.js} +1 -1
- package/src/web/dist/assets/{gateway-DyhqzHSh.js → gateway-DxaHzVOF.js} +1 -1
- package/src/web/dist/assets/{global-BLUcvOa8.js → global-BCYo_xAt.js} +1 -1
- package/src/web/dist/assets/global-CP6wBbWu.css +1 -0
- package/src/web/dist/assets/{i18n-v60Yn7Ls.js → i18n-ClvfZhYc.js} +1 -1
- package/src/web/dist/assets/{label-CdbE1ezd.js → label-09axTkPo.js} +1 -1
- package/src/web/dist/assets/{landing-BQdbaG8s.js → landing-BsX2AKvc.js} +3 -3
- package/src/web/dist/assets/{modelManagement-DwdbGu0o.js → modelManagement-Dc7L1tJw.js} +1 -1
- package/src/web/dist/assets/package-DgoCoO-z.js +1 -0
- package/src/web/dist/assets/{popover-CuM9b3U7.js → popover-CX5HRHKk.js} +1 -1
- package/src/web/dist/assets/{query-CvboQrUT.js → query-1Ng1fzmE.js} +1 -1
- package/src/web/dist/assets/{radix-d0BukFWM.js → radix-DONH6gHT.js} +1 -1
- package/src/web/dist/assets/{router-CqUBCAsx.js → router-Bkbjq53m.js} +1 -1
- package/src/web/dist/assets/{segmented-control-5mZhY1KZ.js → segmented-control-Cxe6ZLHe.js} +1 -1
- package/src/web/dist/assets/{shared-zfHsnBTk.js → shared-DG0AgdnU.js} +1 -1
- package/src/web/dist/assets/{switch-CZn1nypU.js → switch-C58zWdHT.js} +1 -1
- package/src/web/dist/assets/{tabs-CrNMQMmG.js → tabs-BIz291zK.js} +1 -1
- package/src/web/dist/assets/{useAppMutation-B29oVzxS.js → useAppMutation-CsoNTPQ7.js} +1 -1
- package/src/web/dist/assets/{useEventStream-DN2DYBVS.js → useEventStream-CvopQT4p.js} +1 -1
- package/src/web/dist/assets/{useProviderForm-DIuM3Z2u.js → useProviderForm-B_wmywxX.js} +1 -1
- package/src/web/dist/assets/{vendor-JUtelXU0.js → vendor-C-lQMZp3.js} +94 -84
- package/src/web/dist/index.html +14 -11
- package/src/web/dist/landing.html +5 -5
- package/src/web/dist/assets/Events-BQ4Dkqon.js +0 -1
- package/src/web/dist/assets/Logs-BYFIK_hM.js +0 -1
- package/src/web/dist/assets/app-CRxPj2SJ.js +0 -61
- package/src/web/dist/assets/global-BQq8O0Tv.css +0 -1
- package/src/web/dist/assets/package-Dmrvm3RO.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as i,j as e,
|
|
1
|
+
import{r as i,j as e,ba as E,bb as k}from"./vendor-C-lQMZp3.js";import{p as F,C as j,c as b,L,l as S,m as P,n as T,B as A,v as B}from"./app-DZpd2fu9.js";import{L as N,I as v}from"./label-09axTkPo.js";import{u as D}from"./i18n-ClvfZhYc.js";import{a as I,b as q}from"./router-Bkbjq53m.js";import"./global-BCYo_xAt.js";import"./query-1Ng1fzmE.js";import"./radix-DONH6gHT.js";function z(){const{t:s}=D(),r=I(),l=q(),{authEnabled:o,isAuthenticated:u,loading:c,login:y,error:x}=F(),[n,p]=i.useState({username:"",password:""}),[g,m]=i.useState(null),[h,f]=i.useState(!1),d=i.useMemo(()=>{var a;const t=l.state;return((a=t==null?void 0:t.from)==null?void 0:a.pathname)??"/"},[l.state]);i.useEffect(()=>{if(!o&&!c){r(d,{replace:!0});return}o&&u&&!c&&r(d,{replace:!0})},[o,d,u,c,r]),i.useEffect(()=>{document.title=`${s("login.title")} · cc-gw`},[s]);const C=async t=>{if(t.preventDefault(),m(null),!n.username.trim()||!n.password){m(s("login.validation.required"));return}f(!0);try{await y(n.username.trim(),n.password),r(d,{replace:!0})}catch(a){m(a instanceof Error?a.message:s("login.validation.failed"))}finally{f(!1)}};return c?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background px-4",children:e.jsx(j,{className:"w-full max-w-md",children:e.jsx(b,{className:"flex min-h-[320px] items-center justify-center",children:e.jsx(L,{})})})}):o?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background px-4 py-10",children:e.jsxs("div",{className:"mx-auto grid w-full max-w-5xl items-center gap-8 lg:grid-cols-[minmax(0,1fr)_minmax(400px,0.8fr)]",children:[e.jsx("div",{className:"hidden lg:block",children:e.jsxs("div",{className:"max-w-lg space-y-6",children:[e.jsx("div",{className:"inline-flex items-center gap-1.5 rounded-lg bg-secondary px-3 py-1 text-xs font-semibold text-foreground",children:s("login.badge")}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h1",{className:"text-4xl font-semibold tracking-tight text-foreground",children:s("login.title")}),e.jsx("p",{className:"max-w-md text-base leading-7 text-muted-foreground",children:s("login.description")})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(w,{icon:e.jsx(E,{className:"h-5 w-5","aria-hidden":"true"}),title:s("login.hint"),description:s("about.support.tip")}),e.jsx(w,{icon:e.jsx(k,{className:"h-5 w-5","aria-hidden":"true"}),title:s("login.sessionProtected"),description:s("help.note")})]})]})}),e.jsxs(j,{className:"w-full",children:[e.jsxs(S,{className:"pb-4 text-center",children:[e.jsx("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-xl bg-primary text-sm font-bold text-primary-foreground",children:"GW"}),e.jsx(P,{className:"text-xl",children:s("login.title")}),e.jsx(T,{children:s("login.description")})]}),e.jsx(b,{children:e.jsxs("form",{className:"space-y-4",onSubmit:C,children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(N,{htmlFor:"username",children:s("login.fields.username")}),e.jsx(v,{id:"username",value:n.username,autoComplete:"username",autoFocus:!0,onChange:t=>p(a=>({...a,username:t.target.value})),placeholder:s("login.fields.usernamePlaceholder")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(N,{htmlFor:"password",children:s("login.fields.password")}),e.jsx(v,{id:"password",type:"password",value:n.password,autoComplete:"current-password",onChange:t=>p(a=>({...a,password:t.target.value})),placeholder:s("login.fields.passwordPlaceholder")})]}),g||x?e.jsx("div",{role:"alert",className:"rounded-lg bg-destructive/10 px-4 py-3 text-sm text-destructive",children:g||x}):null,e.jsx(A,{type:"submit",className:"w-full",disabled:h,children:s(h?"common.actions.loading":"login.actions.submit")})]})}),e.jsx(B,{className:"justify-center pt-2",children:e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:s("login.hint")})})]})]})}):null}function w({description:s,icon:r,title:l}){return e.jsxs("div",{className:"rounded-lg bg-card/[var(--surface-alpha)] surface-blur px-4 py-4 shadow-[var(--surface-shadow)]",children:[e.jsx("div",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-secondary text-foreground",children:r}),e.jsx("p",{className:"mt-3 text-sm font-semibold text-foreground",children:l}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:s})]})}export{z as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as d,j as e,t as Qt,aF as Bt,ax as Wt,aG as Gt,ay as Xe,aH as Ze,aE as Jt,aI as Yt,a3 as et,Y as Xt,V as Zt,aJ as es}from"./vendor-C-lQMZp3.js";import{P as ts}from"./PageToolbar-GyUQBhmq.js";import{s as O,C as tt,c as st,B as T,d as ss,u as _e,b as ne,q as se,t as ls,a as $}from"./app-DZpd2fu9.js";import{B as te}from"./badge-CWbm9P64.js";import{L as Z,I as be}from"./label-09axTkPo.js";import{S as lt}from"./segmented-control-Cxe6ZLHe.js";import{S as pe,a as xe,b as ge,c as he,d as B,D as as}from"./disclosure-W_XtxMJz.js";import{c as C}from"./global-BCYo_xAt.js";import{u as H}from"./i18n-ClvfZhYc.js";import{D as ns,A as os,a as rs,b as is,c as cs,d as ds}from"./DialogShell-D1T4HXtd.js";import{P as us,a as re}from"./PageState-Bbhr4fy6.js";import{T as at,a as nt,b as ot,c as rt}from"./tabs-BIz291zK.js";import{c as ms}from"./clipboard-DqvcglYs.js";import{a as ps,g as Ee,b as it,c as W,d as Le,e as P,f as ee,h as Se,p as ct,i as dt,j as ut,k as xs,l as gs,T as hs}from"./currency-DffG4uWM.js";import{P as fs,a as bs,b as ys}from"./popover-CX5HRHKk.js";import{S as js}from"./switch-C58zWdHT.js";import{L as mt,u as vs}from"./router-Bkbjq53m.js";import{a as Ns}from"./query-1Ng1fzmE.js";import{g as We}from"./gateway-DxaHzVOF.js";import"./radix-DONH6gHT.js";function ws({apiKeys:t,selected:l,onChange:i,disabled:a,className:o}){const{t:s}=H(),r=d.useId(),[u,x]=d.useState(!1),[f,b]=d.useState(null),N=d.useRef(null),j=d.useRef(null),v=d.useRef(null),g=()=>{const y=j.current;if(!y)return;const p=y.getBoundingClientRect(),S=Math.max(p.width,256),m=window.innerWidth-12;b({left:Math.min(p.left,m-S),top:p.bottom+8,width:S})};d.useEffect(()=>{if(!u)return;const y=S=>{var D,R;const m=S.target;!((D=N.current)!=null&&D.contains(m))&&!((R=v.current)!=null&&R.contains(m))&&x(!1)},p=S=>{var m;S.key==="Escape"&&(x(!1),(m=j.current)==null||m.focus())};return window.addEventListener("mousedown",y),window.addEventListener("keydown",p),()=>{window.removeEventListener("mousedown",y),window.removeEventListener("keydown",p)}},[u]),d.useEffect(()=>{if(u)return g(),window.addEventListener("resize",g),window.addEventListener("scroll",g,!0),()=>{window.removeEventListener("resize",g),window.removeEventListener("scroll",g,!0)}},[u]);const n=d.useMemo(()=>{if(l.length===0)return[];const y=new Map;for(const p of t)y.set(p.id,p);return l.map(p=>{const S=y.get(p);return S?S.isWildcard?s("apiKeys.wildcard"):S.name:null}).filter(p=>!!p)},[t,l,s]),w=l.length===0?s("logs.filters.apiKeyAll"):s("logs.filters.apiKeySelected",{count:l.length}),h=y=>{l.includes(y)?i(l.filter(p=>p!==y)):i([...l,y])};return e.jsxs("div",{className:C("relative space-y-2",o),ref:N,children:[e.jsx(Z,{htmlFor:r,children:s("logs.filters.apiKey")}),e.jsxs("button",{ref:j,id:r,type:"button",onClick:()=>{g(),x(y=>!y)},disabled:a||t.length===0,title:s("logs.filters.apiKeyHint"),className:C("flex h-10 w-full items-center justify-between rounded-lg border border-input bg-background px-3 text-sm ring-offset-background transition-all focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",l.length>0&&"border-foreground",u&&"ring-2 ring-ring ring-offset-2"),children:[e.jsxs("span",{className:"truncate",children:[w,n.length>0&&e.jsx("span",{className:"ml-1 text-xs text-muted-foreground",children:n.join(", ")})]}),e.jsx("svg",{className:C("h-4 w-4 opacity-50 transition-transform",u&&"rotate-180"),viewBox:"0 0 20 20",fill:"currentColor",children:e.jsx("path",{fillRule:"evenodd",d:"M5.23 7.21a.75.75 0 011.06.02L10 10.94l3.71-3.71a.75.75 0 111.06 1.06l-4.24 4.25a.75.75 0 01-1.06 0L5.21 8.29a.75.75 0 01.02-1.08z",clipRule:"evenodd"})})]}),u&&f&&Qt.createPortal(e.jsxs("div",{ref:v,className:"fixed z-50 rounded-lg border bg-popover p-2 shadow-[var(--surface-shadow-lg)]",style:f,children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg bg-secondary px-3 py-2 text-xs",children:[e.jsx("span",{children:w}),e.jsx("button",{type:"button",onClick:()=>i([]),disabled:l.length===0,className:"text-foreground underline decoration-muted-foreground/40 underline-offset-2 hover:decoration-foreground disabled:opacity-40",children:s("common.actions.reset")})]}),e.jsxs("div",{className:"max-h-56 overflow-y-auto py-2",children:[t.map(y=>{const p=y.isWildcard?s("apiKeys.wildcard"):y.name,S=l.includes(y.id);return e.jsxs("label",{className:C("flex cursor-pointer items-center gap-3 rounded-xl px-3 py-2 text-sm transition hover:bg-accent",S&&"bg-secondary text-foreground"),children:[e.jsx("input",{type:"checkbox",className:"h-4 w-4 rounded border-border",checked:S,onChange:()=>h(y.id)}),e.jsx("span",{className:"truncate",children:p})]},y.id)}),t.length===0&&e.jsx("p",{className:"px-2 py-2 text-xs text-muted-foreground",children:s("logs.filters.apiKeyAll")})]})]}),document.body)]})}const oe=[20,50,100],ks=["all","errors","today","anthropic","openai"],Cs=["claude-code","codex","opencode","gemini-cli","cline","roo-code","cursor","crush","aider","kilo-code","droid","copilot","anthropic-compatible","openai-compatible"],J=["endpoint","provider","client","requestedModel","routedModel","apiKey","tokens","cost","duration","status","error"],le=["endpoint","provider","client","requestedModel","routedModel","apiKey","tokens","cost","duration","status","error"];function Ss(){return typeof window>"u"?"comfortable":window.localStorage.getItem(O.logs.density)==="compact"?"compact":"comfortable"}function _s(){if(typeof window>"u")return oe[0];const t=window.localStorage.getItem(O.logs.pageSize),l=Number(t);return oe.includes(l)?l:oe[0]}function Ge(t,l=!1){if(!t)return;const i=l?`${t}T23:59:59.999`:`${t}T00:00:00.000`,a=Date.parse(i);return Number.isFinite(a)?a:void 0}function Es(t,l,i){return t===i&&l===i}function Ls(t){const{t:l}=H(),{activeFilters:i,filtersExpanded:a,setFiltersExpanded:o,handleResetFilters:s,activeQuickView:r,applyQuickView:u,providerFilter:x,setProviderFilter:f,endpointFilter:b,setEndpointFilter:N,selectedApiKeys:j,setSelectedApiKeys:v,modelFilter:g,setModelFilter:n,clientKindFilter:w,setClientKindFilter:h,sessionFilter:y,setSessionFilter:p,statusFilter:S,setStatusFilter:m,fromDate:D,setFromDate:R,toDate:M,setToDate:_,providerOptions:F,apiKeys:U,apiKeysLoading:L,customEndpoints:A}=t;return e.jsx(tt,{"data-testid":"logs-filters-card",className:"overflow-hidden",children:e.jsxs(st,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:l("logs.filtersTitle")}),i.length>0&&e.jsx(te,{variant:"outline",className:"border-transparent bg-secondary px-2.5 py-0.5 text-[11px] font-semibold text-foreground",children:l("common.filters.activeCount",{count:i.length})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l("logs.filtersDescription")})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[i.length>0&&e.jsx(T,{variant:"ghost",size:"sm",onClick:s,className:"h-8 px-3 text-xs",children:l("common.actions.reset")}),e.jsx(T,{variant:"ghost",size:"sm",onClick:()=>o(k=>!k),className:"h-8 px-3 text-xs",children:a?e.jsxs(e.Fragment,{children:[l("common.filters.collapse"),e.jsx(Bt,{className:"ml-1 h-4 w-4"})]}):e.jsxs(e.Fragment,{children:[l("common.filters.expand"),e.jsx(Wt,{className:"ml-1 h-4 w-4"})]})})]})]}),i.length>0?e.jsx("div",{className:"flex min-h-10 flex-wrap items-center gap-2 rounded-lg bg-secondary px-3 py-2",children:i.map(k=>e.jsxs(te,{variant:"outline",role:"button",tabIndex:0,className:"flex cursor-pointer items-center gap-1 border border-border bg-card px-2.5 py-1 text-[11px] font-semibold text-foreground/90 transition hover:bg-secondary",onClick:k.onRemove,onKeyDown:ie=>{(ie.key==="Enter"||ie.key===" ")&&(ie.preventDefault(),k.onRemove())},children:[k.label,e.jsx(Gt,{className:"h-3 w-3","aria-hidden":"true"})]},k.key))}):null,e.jsx(lt,{value:r,onChange:u,className:"flex-wrap","aria-label":l("logs.filtersTitle"),options:ks.map(k=>({value:k,label:l(`logs.quickViews.${k}`)}))})]}),a&&e.jsxs("div",{className:"mt-3 grid gap-3 rounded-xl bg-secondary p-3 md:grid-cols-2 xl:grid-cols-4 animate-in fade-in slide-in-from-top-2 duration-200",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Z,{children:l("logs.filters.provider")}),e.jsxs(pe,{value:x,onValueChange:f,children:[e.jsx(xe,{children:e.jsx(ge,{})}),e.jsxs(he,{children:[e.jsx(B,{value:"all",children:l("logs.filters.providerAll")}),F.map(k=>e.jsx(B,{value:k.id,children:k.label??k.id},k.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Z,{children:l("logs.filters.endpoint")}),e.jsxs(pe,{value:b,onValueChange:N,children:[e.jsx(xe,{children:e.jsx(ge,{})}),e.jsxs(he,{children:[e.jsx(B,{value:"all",children:l("logs.filters.endpointAll")}),e.jsx(B,{value:"anthropic",children:l("logs.filters.endpointAnthropic")}),e.jsx(B,{value:"openai",children:l("logs.filters.endpointOpenAI")}),A==null?void 0:A.map(k=>e.jsx(B,{value:k.id,children:k.label||k.id},k.id))]})]})]}),e.jsx(ws,{className:"md:col-span-2",apiKeys:U,selected:j,disabled:L,onChange:v}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Z,{children:l("logs.filters.modelId")}),e.jsx(be,{value:g,onChange:k=>n(k.target.value),placeholder:l("logs.filters.modelPlaceholder")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Z,{children:l("logs.filters.clientKind")}),e.jsxs(pe,{value:w,onValueChange:h,children:[e.jsx(xe,{children:e.jsx(ge,{})}),e.jsxs(he,{children:[e.jsx(B,{value:"all",children:l("logs.filters.clientKindAll")}),Cs.map(k=>e.jsx(B,{value:k,children:l(`dashboard.usage.clientKinds.${k}`,{defaultValue:k})},k))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Z,{children:l("logs.filters.status")}),e.jsxs(pe,{value:S,onValueChange:k=>m(k),children:[e.jsx(xe,{children:e.jsx(ge,{})}),e.jsxs(he,{children:[e.jsx(B,{value:"all",children:l("logs.filters.statusAll")}),e.jsx(B,{value:"success",children:l("logs.filters.statusSuccess")}),e.jsx(B,{value:"error",children:l("logs.filters.statusError")})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Z,{children:l("logs.filters.startDate")}),e.jsx(be,{type:"date",value:D,onChange:k=>R(k.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Z,{children:l("logs.filters.endDate")}),e.jsx(be,{type:"date",value:M,onChange:k=>_(k.target.value)})]}),e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsx(Z,{htmlFor:"logs-session-filter",children:l("logs.filters.session")}),e.jsx(be,{id:"logs-session-filter",value:y,onChange:k=>p(k.target.value),placeholder:l("logs.filters.sessionPlaceholder"),className:"font-mono"})]})]})]})})}const Re={listRequest(t){return{url:"/api/logs",method:"GET",params:t}},detailRequest(t){return{url:t===null?"":`/api/logs/${t}`,method:"GET"}},async exportArchive(t,l){const i=await ss.post("/api/logs/export",t,{responseType:"blob",timeout:l});return new Blob([i.data],{type:"application/zip"})}};function pt({apiKeyMap:t,logId:l,open:i,providerLabelMap:a}){var g;const{t:o}=H(),{pushToast:s}=_e(),r=ne(se.logs.detail(l),Re.detailRequest(l),{enabled:i&&l!==null,staleTime:3e4,gcTime:15e3,placeholderData:void 0});d.useEffect(()=>{!r.isError||!r.error||s({title:o("logs.detail.loadError"),description:r.error.message,variant:"error"})},[r.error,r.isError,s,o]);const u=d.useCallback(async(n,w,h)=>{if(!w){s({title:o("logs.detail.copy.empty",{label:n}),variant:"info"});return}try{await ms(w),s({title:o(h),variant:"success"})}catch(y){s({title:o("logs.detail.copy.failure"),description:y instanceof Error?y.message:o("logs.detail.copy.failureFallback"),variant:"error"})}},[s,o]),x=d.useCallback((n,w)=>{if(!w){s({title:o("logs.detail.copy.empty",{label:n}),variant:"info"});return}const h=new Blob([w],{type:"application/json;charset=utf-8"}),y=URL.createObjectURL(h),p=document.createElement("a"),S=new Date().toISOString().replace(/[:.]/g,"-"),m=n.trim().toLowerCase().replace(/[^a-z0-9\u4e00-\u9fa5]+/gi,"-").replace(/^-+|-+$/g,"")||"payload";p.href=y,p.download=`cc-gw-log-${l??"payload"}-${m}-${S}.json`,document.body.appendChild(p),p.click(),document.body.removeChild(p),URL.revokeObjectURL(y)},[l,s,o]),f=r.data,b=f?a.get(f.provider)??f.provider:"",N=f&&f.api_key_id!=null?t.get(f.api_key_id):void 0,j=f?ps(f,o):null,v=f?Ee(f,o):null;return{apiKeyMeta:N,errorSourceMeta:j,errorMessage:r.isError?((g=r.error)==null?void 0:g.message)??null:null,handleCopy:u,handleDownloadPayload:x,isError:r.isError,isPending:r.isPending,providerLabel:b,refetch:r.refetch,record:f,statusMeta:v}}function xt({detail:t,compact:l=!1}){var r;const{t:i}=H(),a=u=>i(`logs.detail.errorDetail.stages.${u}`,{defaultValue:u}),o=e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.stage?e.jsx("span",{className:"border border-border bg-secondary px-1.5 py-0.5 text-[11px] font-medium text-foreground",children:a(t.stage)}):null,t.upstreamStatus!=null?e.jsxs("span",{className:"border border-destructive/40 bg-destructive/10 px-1.5 py-0.5 text-[11px] font-semibold tabular-nums text-destructive",children:["HTTP ",t.upstreamStatus]}):null,(r=t.failoverAttempts)!=null&&r.length?e.jsx("span",{className:"text-[11px] text-muted-foreground",children:i("logs.detail.errorDetail.attemptsCount",{count:t.failoverAttempts.length})}):null]}),s=t.failoverAttempts??[];return e.jsx(as,{defaultOpen:!0,summaryClassName:"px-1 py-1",contentClassName:C("mt-1 space-y-2",l&&"text-[11px]"),summary:e.jsx("span",{className:C("text-xs font-medium text-foreground",l&&"text-[11px]"),children:i("logs.detail.errorDetail.title")}),children:e.jsxs("div",{className:"space-y-2","data-testid":"log-error-detail",children:[o,t.message?e.jsx("p",{className:C("whitespace-pre-wrap break-all border-l-2 border-destructive/50 bg-destructive/5 px-2.5 py-1.5 font-mono",l?"text-[10.5px] leading-[1.55]":"text-[11px] leading-[1.6]"),children:t.message}):null,s.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-[11px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border text-left text-muted-foreground",children:[e.jsx("th",{className:"py-1 pr-3 font-medium",children:i("logs.detail.errorDetail.attemptBackend")}),e.jsx("th",{className:"py-1 pr-3 font-medium",children:i("logs.detail.errorDetail.attemptOutcome")}),e.jsx("th",{className:"py-1 pr-3 text-right font-medium",children:i("logs.detail.errorDetail.attemptStatus")}),e.jsx("th",{className:"py-1 text-right font-medium",children:i("logs.detail.errorDetail.attemptLatency")})]})}),e.jsx("tbody",{className:"tabular-nums",children:s.map((u,x)=>e.jsxs("tr",{className:"border-b border-border/50 last:border-b-0",children:[e.jsxs("td",{className:"py-1 pr-3",children:[e.jsx("span",{className:"font-medium",children:u.provider??"—"}),e.jsxs("span",{className:"text-muted-foreground",children:[" / ",u.model??"—"]})]}),e.jsx("td",{className:"py-1 pr-3 text-muted-foreground",children:u.outcome??"—"}),e.jsx("td",{className:"py-1 pr-3 text-right",children:u.status!=null?e.jsx("span",{className:u.status>=400?"text-destructive":"text-foreground",children:u.status}):"—"}),e.jsx("td",{className:"py-1 text-right text-muted-foreground",children:u.latencyMs!=null?`${u.latencyMs} ms`:"—"})]},x))})]})}):null,t.upstreamBody?e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("p",{className:C("text-muted-foreground",l?"text-[10.5px]":"text-[11px]"),children:i("logs.detail.errorDetail.upstreamBody")}),e.jsx("pre",{className:C("m-0 max-h-[180px] overflow-auto whitespace-pre-wrap border border-border bg-secondary/50 p-2 font-mono text-muted-foreground",l?"text-[10.5px] leading-[1.55]":"text-[11px] leading-[1.6]"),children:t.upstreamBody})]}):null]})})}function Rs({open:t,logId:l,onClose:i,providerLabelMap:a,apiKeyMap:o}){var y,p,S,m,D,R,M;const{t:s}=H(),{apiKeyMeta:r,errorSourceMeta:u,errorMessage:x,handleCopy:f,handleDownloadPayload:b,isError:N,isPending:j,providerLabel:v,refetch:g,record:n,statusMeta:w}=pt({apiKeyMap:o,logId:l,open:t,providerLabelMap:a}),h=d.useMemo(()=>{var F,U,L,A;return n?[{key:"client-request",title:s("logs.detail.payload.clientRequest"),value:((F=n.payload)==null?void 0:F.client_request)??null,emptyLabel:s("logs.detail.payload.emptyRequest"),copyToast:"logs.detail.copy.requestSuccess"},...(U=n.payload)!=null&&U.upstream_request?[{key:"upstream-request",title:s("logs.detail.payload.upstreamRequest"),value:n.payload.upstream_request,emptyLabel:s("logs.detail.payload.emptyRequest"),copyToast:"logs.detail.copy.requestSuccess"}]:[],...(L=n.payload)!=null&&L.upstream_response?[{key:"upstream-response",title:s("logs.detail.payload.upstreamResponse"),value:n.payload.upstream_response,emptyLabel:s("logs.detail.payload.emptyResponse"),copyToast:"logs.detail.copy.responseSuccess"}]:[],{key:"client-response",title:s("logs.detail.payload.clientResponse"),value:((A=n.payload)==null?void 0:A.client_response)??null,emptyLabel:s("logs.detail.payload.emptyResponse"),copyToast:"logs.detail.copy.responseSuccess"}].map(k=>({...k,display:it(k.value,k.emptyLabel)})):[]},[n,s]);return e.jsx(ns,{open:t,onOpenChange:_=>{_||i()},children:e.jsxs(os,{className:"w-[min(96vw,1200px)] max-w-[1200px]",children:[e.jsxs(rs,{className:"pr-14",children:[e.jsx(is,{children:s("logs.detail.title")}),e.jsx(cs,{children:n?s("logs.detail.id",{id:n.id}):s("logs.detail.loadError")})]}),e.jsx(ds,{className:"max-h-[78vh]",children:j?e.jsx(us,{compact:!0,className:"min-h-[240px]",label:s("common.loading")}):N?e.jsx(re,{compact:!0,className:"min-h-[240px]",tone:"danger",title:s("logs.detail.loadError"),description:x??s("common.unknownError"),action:e.jsx(T,{variant:"outline",onClick:()=>void g(),children:s("common.actions.refresh")})}):n?e.jsxs("div",{className:"space-y-6 text-sm",children:[e.jsxs("section",{className:"space-y-4 rounded-lg border bg-card p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s("logs.detail.infoSection")}),e.jsx("div",{className:"flex flex-wrap items-center gap-2 rounded-lg border bg-secondary p-3 text-xs",children:e.jsx("span",{className:"font-medium",children:s("logs.detail.summary.route",{from:n.client_model??s("logs.detail.info.noRequestedModel"),to:n.model})})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(te,{variant:w==null?void 0:w.variant,children:(w==null?void 0:w.label)??"—"}),e.jsx(te,{variant:"outline",children:n.stream?s("logs.stream.streaming"):s("logs.stream.single")})]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsx(I,{label:s("logs.detail.info.latency"),value:W(n.latency_ms,s("common.units.ms"))}),e.jsx(I,{label:s("logs.detail.info.ttft"),value:W(n.ttft_ms,s("common.units.ms"))}),e.jsx(I,{label:s("logs.detail.info.tpot"),value:W(n.tpot_ms,s("common.units.msPerToken"))}),e.jsx(I,{label:s("logs.detail.info.errorSource"),value:(u==null?void 0:u.label)??"—"})]}),e.jsxs("dl",{className:"grid gap-x-4 gap-y-3 md:grid-cols-2 xl:grid-cols-4",children:[e.jsx(Q,{label:s("logs.detail.info.time"),value:Le(n.timestamp)}),e.jsx(Q,{label:s("logs.detail.info.sessionId"),value:n.session_id??"—"}),e.jsx(Q,{label:s("logs.detail.info.endpoint"),value:n.endpoint||"—"}),e.jsx(Q,{label:s("logs.detail.info.provider"),value:v}),e.jsx(Q,{label:s("logs.detail.info.client"),value:n.client_kind??"—"}),e.jsx(Q,{label:s("logs.detail.info.userAgent"),value:n.user_agent??"—"}),e.jsx(Q,{label:s("logs.detail.info.requestedModel"),value:n.client_model??s("logs.detail.info.noRequestedModel")}),e.jsx(Q,{label:s("logs.detail.info.model"),value:n.model})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsx(I,{label:s("logs.detail.info.inputTokens"),value:P(n.input_tokens)}),e.jsx(I,{label:s("logs.detail.info.cacheReadTokens"),value:P(n.cache_read_tokens)}),e.jsx(I,{label:s("logs.detail.info.cacheCreationTokens"),value:P(n.cache_creation_tokens)}),e.jsx(I,{label:s("logs.detail.info.outputTokens"),value:P(n.output_tokens)})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-5","data-testid":"log-cost-breakdown",children:[e.jsx(I,{label:s("logs.detail.cost.title"),value:ee(n.cost,n.cost_currency)}),n.cost!=null?e.jsxs(e.Fragment,{children:[e.jsx(I,{label:s("logs.detail.cost.input"),value:ee(((y=n.cost_breakdown)==null?void 0:y.input)??null,n.cost_currency)}),e.jsx(I,{label:s("logs.detail.cost.output"),value:ee(((p=n.cost_breakdown)==null?void 0:p.output)??null,n.cost_currency)}),e.jsx(I,{label:s("logs.detail.cost.cacheRead"),value:ee(((S=n.cost_breakdown)==null?void 0:S.cacheRead)??null,n.cost_currency)}),e.jsx(I,{label:s("logs.detail.cost.cacheCreation"),value:ee(((m=n.cost_breakdown)==null?void 0:m.cacheCreation)??null,n.cost_currency)})]}):null]}),n.cost==null&&!Se(n)?e.jsx("p",{className:"text-xs text-muted-foreground/70",children:s("logs.detail.cost.unpricedHint")}):null,Se(n)?e.jsx("p",{className:"text-xs text-muted-foreground/70",children:s("logs.detail.tokensNoUsageHint")}):null,n.error?e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:s("logs.detail.info.error")}),e.jsx("p",{className:"rounded-xl border border-destructive/50 bg-destructive/10 p-3 text-xs text-destructive",children:n.error})]}):null,(()=>{const _=ct(n);return _?"raw"in _?e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:s("logs.detail.errorDetail.title")}),e.jsx("pre",{className:"m-0 max-h-[180px] overflow-auto whitespace-pre-wrap rounded-xl border border-border bg-secondary/50 p-3 font-mono text-[11px] leading-[1.6] text-muted-foreground",children:_.raw})]}):e.jsx(xt,{detail:_}):null})()]}),e.jsxs("div",{className:"grid gap-6 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]",children:[e.jsxs("section",{className:"space-y-3 rounded-lg border bg-card p-4",children:[e.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s("logs.detail.apiKey.title")}),e.jsxs("dl",{className:"grid gap-x-4 gap-y-3 sm:grid-cols-2",children:[e.jsx(Q,{label:s("logs.detail.apiKey.name"),value:n.api_key_id==null&&!n.api_key_name?s("logs.detail.apiKey.missing"):r!=null&&r.isWildcard?s("apiKeys.wildcard"):(r==null?void 0:r.name)??n.api_key_name??s("logs.detail.apiKey.missing")}),e.jsx(Q,{label:s("logs.detail.apiKey.identifier"),value:n.api_key_id??s("common.noData")}),e.jsx(Q,{label:s("logs.detail.apiKey.masked"),value:r!=null&&r.isWildcard?s("apiKeys.wildcard"):(r==null?void 0:r.maskedKey)??n.api_key_name??s("logs.detail.apiKey.maskedUnavailable")}),e.jsx(Q,{label:s("logs.detail.apiKey.lastUsed"),value:r!=null&&r.lastUsedAt?new Date(r.lastUsedAt).toLocaleString():s("common.noData")})]}),e.jsxs("div",{className:"rounded-lg border bg-secondary p-3 text-xs",children:[e.jsx("p",{className:"font-medium",children:s("logs.detail.apiKey.rawMasked")}),e.jsx("p",{className:"mt-1 break-all font-mono",children:n.api_key_value_available?n.api_key_value_masked??s("logs.detail.apiKey.rawUnavailable"):s("logs.detail.apiKey.rawUnavailable")}),e.jsx("p",{className:"mt-2 text-[11px] text-muted-foreground",children:s("logs.detail.apiKey.rawMaskedHint")})]})]}),e.jsxs("section",{className:"space-y-4 rounded-lg border bg-card p-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s("logs.detail.payload.title")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(D=n.payload)!=null&&D.upstream_request||(R=n.payload)!=null&&R.upstream_response?s("logs.detail.payload.helperWithUpstream"):s("logs.detail.payload.helperClientOnly")})]}),e.jsxs(at,{defaultValue:(M=h[0])==null?void 0:M.key,children:[e.jsx(nt,{className:"w-full justify-start overflow-x-auto",children:h.map(_=>e.jsx(ot,{value:_.key,children:_.title},_.key))}),h.map(_=>e.jsx(rt,{value:_.key,children:e.jsx(Fs,{title:_.title,display:_.display,onCopy:()=>f(_.title,_.value,_.copyToast),onDownload:()=>b(_.title,_.value),panelKey:_.key,t:s})},_.key))]})]})]})]}):e.jsx(re,{compact:!0,className:"min-h-[240px]",title:s("logs.detail.loadError"),description:s("common.noData")})})]})})}function I({label:t,value:l}){return e.jsxs("div",{className:"min-w-0 rounded-lg border bg-secondary px-3 py-3",children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-wider text-muted-foreground",children:t}),e.jsx("p",{className:"mt-2 break-all text-sm font-semibold leading-6",children:l})]})}function Q({label:t,value:l}){return e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsx("dt",{className:"text-xs text-muted-foreground",children:t}),e.jsx("dd",{className:"min-w-0 break-all whitespace-pre-wrap text-sm font-medium leading-6 text-foreground",children:l??"—"})]})}function Fs({display:t,onCopy:l,onDownload:i,panelKey:a,title:o,t:s}){return e.jsxs("div",{className:"space-y-3 rounded-lg border bg-secondary/40 p-4","data-testid":`log-payload-${a}`,children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:o}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(T,{variant:"outline",size:"sm",onClick:l,children:[e.jsx(Xe,{className:"mr-2 h-3.5 w-3.5"}),s("common.actions.copy")]}),e.jsxs(T,{variant:"outline",size:"sm",onClick:i,children:[e.jsx(Ze,{className:"mr-2 h-3.5 w-3.5"}),s("common.actions.download")]})]})]}),t.isTruncated?e.jsx("p",{className:"rounded-lg border border-warning/30 bg-warning-bg px-3 py-2 text-xs text-warning",children:s("logs.detail.payload.truncated",{shown:t.displayedLength.toLocaleString(),total:t.originalLength.toLocaleString()})}):null,e.jsx("pre",{className:"max-h-72 overflow-auto whitespace-pre rounded-lg border bg-secondary p-3 text-xs",children:t.text})]})}function Ds({autoRefresh:t,columnOptions:l,exporting:i,onExport:a,onRefresh:o,onResetColumns:s,onSetDensity:r,onToggleAutoRefresh:u,onToggleColumn:x,refreshing:f,rowDensity:b,visibleColumns:N,visibleColumnSet:j,autoHiddenColumns:v}){const{t:g}=H(),n=JSON.stringify(N)===JSON.stringify(J),w=new Set(v);return e.jsxs("div",{className:"flex w-full flex-col gap-3 xl:w-auto xl:flex-row xl:items-center",children:[e.jsxs("div",{className:"grid w-full grid-cols-2 gap-2 sm:flex sm:flex-row sm:flex-wrap sm:items-center xl:w-auto xl:flex-nowrap",children:[e.jsx(lt,{block:!0,className:"col-span-2 w-full overflow-x-auto sm:w-auto",value:b,onChange:r,options:[{value:"comfortable",label:g("logs.table.density.comfortable")},{value:"compact",label:g("logs.table.density.compact")}]}),e.jsxs(fs,{children:[e.jsx(bs,{asChild:!0,children:e.jsx(T,{variant:"outline",size:"sm",className:"w-full sm:w-auto",children:g("logs.actions.columns")})}),e.jsxs(ys,{align:"end",className:"w-64 p-3",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsx("p",{className:"text-sm font-semibold",children:g("logs.actions.columns")}),e.jsx(T,{variant:"ghost",size:"sm",onClick:s,disabled:n,children:g("common.actions.reset")})]}),e.jsx("div",{className:"grid gap-1.5",children:l.map(h=>{const y=j.has(h.id);return e.jsxs("label",{className:C("flex cursor-pointer items-center gap-3 rounded-xl px-3 py-2 text-sm transition hover:bg-accent",y&&"bg-secondary text-foreground"),children:[e.jsx("input",{type:"checkbox",checked:y,onChange:()=>x(h.id),className:"h-4 w-4 rounded border-border"}),e.jsx("span",{children:h.label}),w.has(h.id)?e.jsx("span",{className:"ml-auto rounded-sm bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground",children:g("logs.table.narrowHiddenPill")}):null]},h.id)})}),e.jsx("p",{className:"mt-3 text-[11px] leading-snug text-muted-foreground",children:g("logs.table.autoHiddenNote")})]})]}),e.jsxs(T,{variant:"outline",onClick:a,disabled:i,className:"w-full sm:w-auto",children:[e.jsx(Ze,{className:"mr-2 h-4 w-4"}),g(i?"logs.actions.exporting":"logs.actions.export")]})]}),e.jsxs("div",{className:"flex w-full items-center gap-3 xl:w-auto",children:[e.jsxs("label",{className:"flex shrink-0 cursor-pointer items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(js,{checked:t,onCheckedChange:u,"aria-label":g("logs.actions.autoRefresh")}),g("logs.actions.autoRefresh")]}),e.jsxs(T,{variant:"outline",size:"sm",onClick:o,disabled:f,className:"shrink-0",children:[e.jsx(Jt,{className:C("mr-2 h-4 w-4",f&&"animate-spin")}),g(f?"common.actions.refreshing":"logs.actions.manualRefresh")]})]})]})}function Ts({record:t,providerLabelMap:l,onSelect:i,costCurrency:a}){const{t:o}=H(),s=Ee(t,o),r=l.get(t.provider)??t.provider,u=dt(t.session_id),x=u==null?void 0:u.accentStyle;return e.jsxs("button",{type:"button","data-session-id":u==null?void 0:u.sessionId,"data-session-color":u==null?void 0:u.colorKey,style:x,onClick:()=>i(t.id),className:"w-full space-y-2 border-b border-border/50 px-4 py-3 text-left transition-colors hover:bg-muted/50",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:Le(t.timestamp)}),e.jsx(te,{variant:s.variant,className:"text-xs",children:s.label})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[e.jsx("span",{className:"min-w-0 truncate font-medium",title:r,children:r}),e.jsx("span",{className:"min-w-0 truncate text-muted-foreground",title:t.model,children:t.model})]}),t.client_kind?e.jsx("div",{className:"text-[11px] text-muted-foreground/80",title:t.user_agent??void 0,children:t.client_kind}):null,e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-xs tabular-nums text-muted-foreground",children:[e.jsx("span",{children:W(t.latency_ms,o("common.units.ms"))}),t.ttft_ms!=null?e.jsxs("span",{children:[o("logs.table.columns.latencyTtft")," ",W(t.ttft_ms,o("common.units.ms"))]}):null,t.tpot_ms!=null?e.jsxs("span",{children:[o("logs.table.columns.latencyTpot")," ",W(t.tpot_ms,o("common.units.msPerToken"))]}):null,t.cost!=null?e.jsx("span",{children:ee(t.cost,a)}):null]}),t.cache_read_tokens!=null||t.cache_creation_tokens!=null?e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] tabular-nums text-muted-foreground/80",children:[e.jsxs("span",{children:[o("logs.table.columns.tokenCacheRead")," ",P(t.cache_read_tokens??t.cached_tokens)]}),e.jsxs("span",{children:[o("logs.table.columns.tokenCacheWrite")," ",P(t.cache_creation_tokens)]})]}):null]})}const Je={accent:"bg-foreground",ok:"bg-success",warn:"bg-warning",error:"bg-destructive"};function Ks({logId:t,providerLabelMap:l,apiKeyMap:i}){const{t:a}=H(),{record:o,isPending:s,isError:r,errorMessage:u,statusMeta:x,providerLabel:f,handleCopy:b,refetch:N}=pt({apiKeyMap:i,logId:t,open:!0,providerLabelMap:l}),j=d.useMemo(()=>{var D,R,M,_;if(!o)return[];const m=[{key:"client-request",title:a("logs.detail.payload.clientRequest"),value:((D=o.payload)==null?void 0:D.client_request)??null,emptyLabel:a("logs.detail.payload.emptyRequest"),copyToast:"logs.detail.copy.requestSuccess"}];return(R=o.payload)!=null&&R.upstream_request&&m.push({key:"upstream-request",title:a("logs.detail.payload.upstreamRequest"),value:o.payload.upstream_request,emptyLabel:a("logs.detail.payload.emptyRequest"),copyToast:"logs.detail.copy.requestSuccess"}),(M=o.payload)!=null&&M.upstream_response&&m.push({key:"upstream-response",title:a("logs.detail.payload.upstreamResponse"),value:o.payload.upstream_response,emptyLabel:a("logs.detail.payload.emptyResponse"),copyToast:"logs.detail.copy.responseSuccess"}),m.push({key:"client-response",title:a("logs.detail.payload.clientResponse"),value:((_=o.payload)==null?void 0:_.client_response)??null,emptyLabel:a("logs.detail.payload.emptyResponse"),copyToast:"logs.detail.copy.responseSuccess"}),m.map(F=>({...F,display:it(F.value,F.emptyLabel)}))},[o,a]),[v,g]=d.useState("client-request"),n=j.find(m=>m.key===v)??j[0];if(s)return e.jsx("div",{className:"py-3",children:e.jsx(ut,{className:"h-28 w-full"})});if(r)return e.jsx(re,{compact:!0,tone:"danger",title:a("logs.detail.loadError"),description:u??a("common.unknownError"),action:e.jsx(T,{variant:"outline",size:"sm",onClick:()=>void N(),children:a("common.actions.refresh")})});if(!o)return e.jsx(re,{compact:!0,title:a("logs.detail.loadError"),description:a("common.noData")});const w=xs(o,f,a),h=a("common.units.ms"),y=[{label:a("logs.detail.info.status"),value:(x==null?void 0:x.label)??"—"},{label:a("logs.detail.info.latency"),value:W(o.latency_ms,h)},{label:a("logs.detail.info.ttft"),value:W(o.ttft_ms,h)},{label:a("logs.detail.info.tpot"),value:W(o.tpot_ms,a("common.units.msPerToken"))},{label:a("logs.detail.info.inputTokens"),value:P(o.input_tokens)},{label:a("logs.detail.info.outputTokens"),value:P(o.output_tokens)},{label:a("logs.detail.info.cacheReadTokens"),value:P(o.cache_read_tokens??o.cached_tokens)},{label:a("logs.detail.info.cacheCreationTokens"),value:P(o.cache_creation_tokens)},{label:a("logs.detail.info.cost"),value:ee(o.cost,o.cost_currency)}],p=o.ttft_ms!=null,S=o.session_id;return e.jsxs("div",{"data-testid":"log-row-expanded",className:"grid gap-5 py-1 xl:grid-cols-[minmax(0,1.15fr)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"mb-3 text-[10.5px] font-semibold uppercase tracking-[0.06em] text-muted-foreground",children:a("logs.detail.trace.title")}),e.jsx("ol",{"data-testid":"log-trace-timeline",className:"flex flex-col",children:w.map((m,D)=>e.jsxs("li",{className:"grid grid-cols-[14px_1fr] gap-3",children:[e.jsxs("div",{className:"flex flex-col items-center","aria-hidden":"true",children:[e.jsx("span",{className:C("mt-1 h-[9px] w-[9px] rounded-full",Je[m.tone])}),D<w.length-1?e.jsx("span",{className:"mt-[3px] w-px flex-1 bg-border"}):null]}),e.jsxs("div",{className:"pb-3.5",children:[e.jsxs("div",{className:"flex items-baseline gap-2.5",children:[e.jsx("span",{className:"text-xs font-semibold",children:m.title}),m.atLabel?e.jsx("span",{className:"text-[10.5px] tabular-nums text-muted-foreground",children:m.atLabel}):null,m.durLabel?e.jsx("span",{className:"ml-auto text-[10.5px] tabular-nums text-muted-foreground",children:m.durLabel}):null]}),m.detail?e.jsx("div",{className:"mt-1 text-[11px] leading-[1.55] text-muted-foreground",children:m.detail}):null,e.jsx("div",{className:"mt-1.5 h-1 w-full max-w-[220px] bg-secondary",children:e.jsx("div",{className:C("h-full",Je[m.tone]),style:{width:`${m.barPct}%`}})})]})]},m.id))}),p?null:e.jsx("p",{className:"mt-1 text-[10.5px] text-muted-foreground/70",children:a("logs.detail.trace.degraded")}),(()=>{const m=ct(o);return!m||"raw"in m?null:e.jsx("div",{className:"mt-2 border-t border-border pt-2",children:e.jsx(xt,{detail:m,compact:!0})})})()]}),e.jsxs("div",{className:"flex min-w-0 flex-col gap-3",children:[e.jsx("div",{className:"grid grid-cols-3 gap-2",children:y.map(m=>e.jsxs("div",{className:"border border-border bg-card px-2.5 py-2",children:[e.jsx("div",{className:"text-[10.5px] text-muted-foreground",children:m.label}),e.jsx("div",{className:"mt-0.5 text-[13px] font-semibold tabular-nums",children:m.value})]},m.label))}),Se(o)?e.jsx("p",{className:"text-[11px] text-muted-foreground/70",children:a("logs.detail.tokensNoUsageHint")}):null,e.jsx("div",{className:"border border-border bg-card",children:e.jsxs(at,{value:n==null?void 0:n.key,onValueChange:g,children:[e.jsx(nt,{className:"w-full justify-start overflow-x-auto",children:j.map(m=>e.jsx(ot,{value:m.key,className:"px-2.5 text-[10.5px]",children:m.title},m.key))}),j.map(m=>e.jsx(rt,{value:m.key,className:"mt-0",children:e.jsx("pre",{"data-testid":`log-payload-${m.key}`,className:"m-0 max-h-[172px] overflow-auto whitespace-pre-wrap p-3 font-mono text-[10.5px] leading-[1.65] text-muted-foreground",children:m.display.text||a("logs.detail.payload.emptyRequest")})},m.key))]})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(T,{variant:"outline",size:"sm",className:"h-[30px] flex-1",onClick:()=>{n&&b(n.title,n.value,n.copyToast)},children:[e.jsx(Xe,{className:"mr-1.5 h-3.5 w-3.5","aria-hidden":"true"}),a("logs.detail.inline.copyRequest")]}),S?e.jsx(T,{variant:"outline",size:"sm",className:"h-[30px] flex-1",onClick:()=>b(a("logs.detail.inline.copySession"),S,"logs.detail.inline.sessionCopied"),children:a("logs.detail.inline.copySession")}):null,e.jsx(T,{asChild:!0,variant:"outline",size:"sm",className:"h-[30px] flex-1",children:e.jsxs(mt,{to:"/providers?tab=routing",children:[a("logs.detail.inline.viewRule"),e.jsx(Yt,{className:"ml-1.5 h-3.5 w-3.5","aria-hidden":"true"})]})})]})]})]})}function Ms({record:t,providerLabelMap:l,apiKeyMap:i,onSelect:a,isExpanded:o,onToggleExpand:s,isEven:r,density:u,visibleColumnSet:x,costCurrency:f}){const{t:b}=H(),N=l.get(t.provider)??t.provider,j=t.endpoint||"—",v=Ee(t,b),g=t.client_model??b("logs.table.requestedModelFallback"),n=t.api_key_id!=null?i.get(t.api_key_id):void 0,w=t.api_key_id==null?b("logs.table.apiKeyUnknown"):n!=null&&n.isWildcard?b("apiKeys.wildcard"):n!=null&&n.name?n.name:t.api_key_name?t.api_key_name:b("logs.table.apiKeyUnknown"),h=u==="compact"?"px-1.5 py-1.5":"px-1.5 py-2",y=r?"bg-muted/30":"bg-background",p=dt(t.session_id),S=p==null?void 0:p.accentStyle,m=x.size+2,D=b(o?"logs.detail.inline.collapse":"logs.detail.inline.expand");return e.jsxs(e.Fragment,{children:[e.jsxs("tr",{"data-log-id":t.id,"data-session-id":p==null?void 0:p.sessionId,"data-session-color":p==null?void 0:p.colorKey,className:C("transition-colors duration-160 ease-surface",r?"bg-muted/30":"",o?"bg-muted/50":"hover:bg-muted/50"),children:[e.jsx("td",{className:C("sticky left-0 z-10 text-xs",h,y),style:S,children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{type:"button","aria-expanded":o,"aria-label":D,onClick:()=>s(t.id),className:"-ml-0.5 inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:e.jsx(et,{className:C("h-3.5 w-3.5 transition-transform duration-160 ease-surface",o&&"rotate-90"),"aria-hidden":"true"})}),e.jsx("span",{"data-visual-volatile":"true",className:"metric-number whitespace-nowrap",title:Le(t.timestamp),children:gs(t.timestamp)})]})}),x.has("endpoint")&&e.jsx("td",{className:C(h,"text-xs"),children:e.jsx("div",{className:"max-w-[120px] truncate",title:j,children:j})}),x.has("provider")&&e.jsx("td",{className:C(h,"text-xs"),children:e.jsx("div",{className:"max-w-[100px] truncate",title:N,children:N})}),x.has("client")&&e.jsx("td",{className:C(h,"text-xs text-muted-foreground"),children:e.jsx("div",{className:"max-w-[110px] truncate",title:t.user_agent??t.client_kind??"",children:t.client_kind??"—"})}),x.has("requestedModel")&&e.jsx("td",{className:C(h,"text-xs text-muted-foreground"),children:e.jsx("div",{className:"max-w-[100px] truncate",title:g,children:g})}),x.has("routedModel")&&e.jsx("td",{className:C(h,"text-xs"),children:e.jsx("div",{className:"max-w-[100px] truncate",title:t.model,children:t.model})}),x.has("apiKey")&&e.jsx("td",{className:C(h,"text-xs text-muted-foreground"),children:e.jsx("div",{className:"max-w-[90px] truncate",title:w,children:w})}),x.has("tokens")&&e.jsx("td",{className:C(h,"text-right text-xs tabular-nums"),children:t.input_tokens==null&&t.output_tokens==null?e.jsx("span",{className:"whitespace-nowrap text-muted-foreground/70",children:b("logs.table.tokensNoUsage")}):e.jsxs("div",{className:"flex flex-col items-end gap-0.5",children:[e.jsxs("span",{"data-visual-volatile":"true",className:"whitespace-nowrap",children:[b("logs.table.columns.tokenInShort")," ",P(t.input_tokens),e.jsx("span",{className:"mx-1 text-muted-foreground/50",children:"·"}),b("logs.table.columns.tokenOutShort")," ",P(t.output_tokens)]}),e.jsxs("span",{"data-visual-volatile":"true",className:"whitespace-nowrap text-[10.5px] leading-tight text-muted-foreground",title:`${b("logs.table.columns.tokenCacheRead")} ${P(t.cache_read_tokens??t.cached_tokens)} · ${b("logs.table.columns.tokenCacheWrite")} ${P(t.cache_creation_tokens)}`,children:[b("logs.table.columns.tokenCacheReadShort")," ",P(t.cache_read_tokens??t.cached_tokens),e.jsx("span",{className:"mx-1 text-muted-foreground/40",children:"·"}),b("logs.table.columns.tokenCacheWriteShort")," ",P(t.cache_creation_tokens)]})]})}),x.has("cost")&&e.jsx("td",{className:C(h,"text-right text-xs tabular-nums align-top"),children:e.jsx("span",{className:"whitespace-nowrap",title:t.cost==null?b("logs.table.costUnpricedHint"):void 0,"data-testid":`log-cost-${t.id}`,children:ee(t.cost,f)})}),x.has("duration")&&e.jsx("td",{className:C(h,"text-right text-xs tabular-nums"),children:e.jsxs("div",{className:"flex flex-col items-end gap-0.5",children:[e.jsx("span",{"data-visual-volatile":"true",className:"whitespace-nowrap",children:W(t.latency_ms,"ms")}),e.jsxs("span",{"data-visual-volatile":"true",className:"whitespace-nowrap text-[10.5px] leading-tight text-muted-foreground",title:`${b("logs.table.columns.latencyTtft")} ${W(t.ttft_ms,"ms")} · ${b("logs.table.columns.latencyTpot")} ${W(t.tpot_ms,b("common.units.msPerToken"))}`,children:[b("logs.table.columns.latencyTtft")," ",P(t.ttft_ms),e.jsx("span",{className:"mx-1 text-muted-foreground/40",children:"·"}),b("logs.table.columns.latencyTpot")," ",P(t.tpot_ms)]})]})}),x.has("status")&&e.jsx("td",{className:C(h,"text-center"),children:e.jsx(te,{variant:v.variant,className:"text-xs",children:v.label})}),x.has("error")&&e.jsx("td",{className:C(h,"text-xs text-muted-foreground"),children:e.jsx("div",{className:"max-w-[60px] truncate",title:t.error??"",children:t.error?t.error:"—"})}),e.jsx("td",{className:C("sticky right-0 z-10 text-center",h,y),children:e.jsx(T,{variant:"outline",size:"sm",onClick:()=>a(t.id),children:b("logs.actions.detail")})})]}),o?e.jsx("tr",{"data-testid":`log-row-expanded-wrapper-${t.id}`,children:e.jsx("td",{colSpan:m,className:"border-t border-border bg-secondary/30 p-0",children:e.jsx("div",{className:"px-5 pb-5 pt-3",children:e.jsx(Ks,{logId:t.id,providerLabelMap:l,apiKeyMap:i})})})}):null]})}const V="whitespace-nowrap px-1.5 py-2.5 text-xs font-semibold text-muted-foreground";function Ps(t){const{t:l}=H(),{tableScrollRef:i,visibleColumnSet:a,visibleColumnCount:o,autoHiddenColumns:s,logsError:r,logsPending:u,items:x,costCurrency:f,activeFiltersCount:b,total:N,handleResetFilters:j,handleRetry:v,providerLabelMap:g,apiKeyMap:n,handleOpenDetail:w,expandedLogId:h,onToggleExpand:y,rowDensity:p,showScrollHint:S,pageSize:m,setPageSize:D,page:R,totalPages:M,setPage:_}=t,F=e.jsx(re,{compact:!0,tone:"danger",icon:e.jsx(Xt,{className:"h-5 w-5","aria-hidden":"true"}),title:l("logs.toast.listError.title"),description:r,action:e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-2",children:[e.jsx(T,{variant:"outline",size:"sm",onClick:v,children:l("common.actions.refresh")}),b>0?e.jsx(T,{variant:"ghost",size:"sm",onClick:j,children:l("common.actions.reset")}):null]})}),U=e.jsx(re,{compact:!0,tone:"primary",icon:e.jsx(Zt,{className:"h-5 w-5","aria-hidden":"true"}),title:b>0?l("logs.empty.filteredTitle"):l("logs.empty.title"),description:b>0?l("logs.empty.filteredSubtitle"):l("logs.empty.subtitle"),action:e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-2",children:[b>0?e.jsx(T,{variant:"outline",size:"sm",onClick:j,children:l("logs.empty.actions.reset")}):null,e.jsx(T,{asChild:!0,variant:"ghost",size:"sm",children:e.jsx(mt,{to:"/api-keys",children:l("logs.empty.actions.apiKeys")})})]})});return e.jsx(tt,{variant:"solid",className:"overflow-hidden bg-card shadow-[var(--surface-shadow)]",children:e.jsxs(st,{className:"p-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 bg-secondary/50 px-4 py-3 border-b border-border",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-semibold",children:l("logs.title")}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.jsx("span",{className:"metric-number",children:l("logs.summary.total",{value:N.toLocaleString()})}),e.jsx("span",{className:"mx-1.5 text-muted-foreground/50",children:"·"}),l("logs.table.visibleColumns",{count:o})]})]}),s.length>0||S?e.jsxs("div",{className:"hidden items-center gap-2 md:flex",children:[s.length>0?e.jsx(te,{variant:"outline",className:"bg-background text-muted-foreground",title:l("logs.table.autoHiddenHint",{columns:s.map(L=>l(`logs.table.columns.${L}`)).join(" · ")}),children:l("logs.table.autoHiddenColumns",{count:s.length})}):null,e.jsx(te,{variant:"outline",className:"bg-background text-muted-foreground",children:l(p==="compact"?"logs.table.density.compact":"logs.table.density.comfortable")})]}):null]}),e.jsxs("div",{className:"relative hidden md:block",children:[e.jsx("div",{ref:i,className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"border-b border-border/50 bg-secondary/50",children:e.jsxs("tr",{children:[e.jsx("th",{className:C(V,"sticky left-0 z-20 bg-secondary text-left"),children:l("logs.table.columns.time")}),a.has("endpoint")&&e.jsx("th",{className:C(V,"text-left"),children:l("logs.table.columns.endpoint")}),a.has("provider")&&e.jsx("th",{className:C(V,"text-left"),children:l("logs.table.columns.provider")}),a.has("client")&&e.jsx("th",{className:C(V,"text-left"),children:l("logs.table.columns.client")}),a.has("requestedModel")&&e.jsx("th",{className:C(V,"text-left"),children:l("logs.table.columns.requestedModel")}),a.has("routedModel")&&e.jsx("th",{className:C(V,"text-left"),children:l("logs.table.columns.routedModel")}),a.has("apiKey")&&e.jsx("th",{className:C(V,"text-left"),children:l("logs.table.columns.apiKey")}),a.has("tokens")&&e.jsx("th",{className:C(V,"text-right"),title:l("logs.table.tokensHeaderHint"),children:l("logs.table.columns.tokens")}),a.has("cost")&&e.jsx("th",{className:C(V,"text-right"),children:l("logs.table.columns.cost")}),a.has("duration")&&e.jsx("th",{className:C(V,"text-right"),title:l("logs.table.durationHeaderHint"),children:l("logs.table.columns.duration")}),a.has("status")&&e.jsx("th",{className:C(V,"text-center"),children:l("logs.table.columns.status")}),a.has("error")&&e.jsx("th",{className:C(V,"text-left"),children:l("logs.table.columns.error")}),e.jsx("th",{className:C(V,"sticky right-0 z-20 bg-secondary text-center"),children:l("logs.table.columns.actions")})]})}),e.jsx("tbody",{className:"divide-y divide-border/50",children:u?Array.from({length:8}).map((L,A)=>e.jsx(hs,{columns:o},A)):r&&x.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:o,className:"px-3 py-6",children:F})}):x.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:o,className:"px-3 py-8 text-center text-sm text-muted-foreground",children:U})}):x.map((L,A)=>e.jsx(Ms,{record:L,providerLabelMap:g,apiKeyMap:n,onSelect:w,isExpanded:L.id===h,onToggleExpand:y,isEven:A%2===0,density:p,visibleColumnSet:a,costCurrency:f},L.id))})]})}),S&&e.jsx("div",{className:"table-scroll-hint"})]}),e.jsx("div",{className:"md:hidden",children:u?e.jsx("div",{className:"space-y-3 p-4",children:Array.from({length:5}).map((L,A)=>e.jsx(ut,{className:"h-20 w-full"},A))}):r&&x.length===0?e.jsx("div",{className:"px-3 py-6",children:F}):x.length===0?e.jsx("div",{className:"px-3 py-8",children:U}):x.map(L=>e.jsx(Ts,{record:L,providerLabelMap:g,onSelect:w,costCurrency:f},L.id))}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4 bg-secondary/50 p-4 border-t border-border",children:[e.jsxs("div",{className:"flex items-center gap-2 border border-border bg-secondary px-3 py-1.5",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:l("logs.table.pagination.perPage")}),e.jsxs(pe,{value:m.toString(),onValueChange:L=>D(Number(L)),children:[e.jsx(xe,{className:"h-8 w-[80px] bg-background",children:e.jsx(ge,{})}),e.jsx(he,{children:oe.map(L=>e.jsx(B,{value:L.toString(),children:L},L))})]})]}),e.jsxs("div",{className:"flex items-center gap-2 border border-border bg-secondary px-2 py-1.5",children:[e.jsxs(T,{variant:"outline",size:"sm",onClick:()=>_(L=>Math.max(L-1,1)),disabled:R<=1,children:[e.jsx(es,{className:"mr-1 h-4 w-4","aria-hidden":"true"}),l("logs.table.pagination.previous")]}),e.jsx("span",{className:"metric-number px-1 text-sm text-muted-foreground",children:l("logs.table.pagination.pageLabel",{page:M===0?0:R,total:M})}),e.jsxs(T,{variant:"outline",size:"sm",onClick:()=>_(L=>M===0?L:Math.min(L+1,M)),disabled:M===0||R>=M,children:[l("logs.table.pagination.next"),e.jsx(et,{className:"ml-1 h-4 w-4","aria-hidden":"true"})]})]})]})]})})}function As({exportTimeoutMs:t,queryParams:l,total:i}){const{t:a}=H(),{pushToast:o}=_e(),[s,r]=d.useState(!1),u=d.useCallback(async()=>{if(!s){r(!0);try{const x=i>0?Math.min(i,5e3):1e3,f={...l,limit:x,offset:0},b=await Re.exportArchive(f,t),N=new Date().toISOString().replace(/[:.]/g,"-"),j=URL.createObjectURL(b),v=document.createElement("a");v.href=j,v.download=`cc-gw-logs-${N}.zip`,document.body.appendChild(v),v.click(),v.remove(),URL.revokeObjectURL(j),o({title:a("logs.toast.exportSuccess.title"),description:a("logs.toast.exportSuccess.desc"),variant:"success"})}catch(x){const f=ls(x);o({title:a("logs.toast.exportError.title"),description:a("logs.toast.exportError.desc",{message:f.message}),variant:"error"})}finally{r(!1)}}},[t,s,o,l,a,i]);return{exporting:s,handleExport:u}}function Os(){const t=d.useRef(null),[l,i]=d.useState(!1),a=d.useCallback(()=>{const o=t.current;if(!o)return;const s=o.scrollWidth-o.scrollLeft-o.clientWidth>1;i(s)},[]);return d.useEffect(()=>{const o=t.current;if(!o)return;a(),o.addEventListener("scroll",a,{passive:!0});const s=new ResizeObserver(a);return s.observe(o),()=>{o.removeEventListener("scroll",a),s.disconnect()}},[a]),{scrollRef:t,showScrollHint:l,updateScrollHint:a}}const Ye=["error","client","apiKey","requestedModel","routedModel"],qs=[{below:1140,hidden:1},{below:1080,hidden:2},{below:1020,hidden:3},{below:960,hidden:4},{below:920,hidden:5}],zs=[];function Is(t){if(!Number.isFinite(t)||t<=0)return 0;let l=0;for(const i of qs)t<i.below&&(l=i.hidden);return l}function Vs(t,l){const{i18n:i}=H(),a=i.resolvedLanguage??i.language,[o,s]=d.useState(0),r=d.useRef(o);r.current=o;const u=d.useRef(0);d.useEffect(()=>{const N=t.current;if(!N)return;let j=0,v=0,g=r.current;u.current=-1;const n=()=>{if(j=0,v>0&&(v-=1,v>0)){w();return}const p=N.clientWidth;if(!Number.isFinite(p)||p<=0){g=0,r.current=0,u.current=p,s(0);return}const S=N.firstElementChild,m=!!(S!=null&&S.querySelector("tbody tr[data-log-id]")),D=Ye.filter(F=>l.includes(F)).length,R=Is(p),M=!!(S&&m&&S.scrollWidth>p+1),_=F=>F===g?!1:(g=F,r.current=F,s(F),v=2,w(),!0);Math.abs(p-u.current)>1&&(u.current=p,_(R))||M&&g<D&&_(g+1)},w=()=>{j===0&&(j=window.requestAnimationFrame(n))};n();const h=new ResizeObserver(w);h.observe(N);const y=N.firstElementChild;return y&&h.observe(y),window.addEventListener("resize",w),()=>{j!==0&&window.cancelAnimationFrame(j),h.disconnect(),window.removeEventListener("resize",w)}},[t,a,l]);const x=d.useMemo(()=>o===0?zs:Ye.filter(N=>l.includes(N)).slice(0,o),[o,l]),f=d.useMemo(()=>{if(x.length===0)return l;const N=new Set(x);return l.filter(j=>!N.has(j))},[x,l]),b=d.useMemo(()=>new Set(f),[f]);return{autoHiddenColumns:x,effectiveVisibleColumns:f,effectiveVisibleColumnSet:b,effectiveVisibleColumnCount:f.length+2}}const $s="cc-gw.logs.visible-columns-v2";function Hs(){if(typeof window>"u")return J;const t=window.localStorage.getItem($s);if(!t)return J;try{const l=JSON.parse(t);if(!Array.isArray(l))return J;const i=l.filter(a=>le.includes(a));return i.length===0?J:(i.includes("cost")||i.push("cost"),i.sort((a,o)=>le.indexOf(a)-le.indexOf(o)))}catch{return J}}function Us(){const[t,l]=$(O.logs.density,Ss,{serialize:N=>N,deserialize:N=>N==="compact"?"compact":"comfortable"}),[i,a]=$(O.logs.visibleColumns,Hs,{serialize:JSON.stringify,deserialize:N=>{try{const j=JSON.parse(N);if(!Array.isArray(j))return J;const v=j.filter(g=>le.includes(g));return v.length>0?v:J}catch{return J}}}),{scrollRef:o,showScrollHint:s}=Os(),r=Vs(o,i),u=d.useMemo(()=>new Set(i),[i]),x=i.length+2,f=d.useCallback(N=>{a(j=>{if(j.includes(N))return j.length===1?j:j.filter(g=>g!==N);const v=[...j,N];return v.sort((g,n)=>le.indexOf(g)-le.indexOf(n)),v})},[]),b=d.useCallback(()=>{a(J)},[]);return{autoHiddenColumns:r.autoHiddenColumns,effectiveVisibleColumns:r.effectiveVisibleColumns,effectiveVisibleColumnCount:r.effectiveVisibleColumnCount,effectiveVisibleColumnSet:r.effectiveVisibleColumnSet,resetVisibleColumns:b,rowDensity:t,setRowDensity:l,showScrollHint:s,tableScrollRef:o,toggleColumn:f,visibleColumnCount:x,visibleColumns:i,visibleColumnSet:u}}const Qs=3e3,Bs=200;function Ws(){var Pe,Ae,Oe,qe,ze,Ie;const{t}=H(),{pushToast:l}=_e(),i=Ns(),[a,o]=$(O.logs.providerFilter,"all"),[s,r]=$(O.logs.endpointFilter,"all"),[u,x]=$(O.logs.modelFilter,""),[f,b]=$(O.logs.clientKindFilter,"all"),[N,j]=$(O.logs.sessionFilter,""),[v,g]=$(O.logs.statusFilter,"all"),[n,w]=$(O.logs.fromDate,""),[h,y]=$(O.logs.toDate,""),[p,S]=d.useState(1),[m,D]=$(O.logs.autoRefresh,!0),[R,M]=$(O.logs.pageSize,_s,{serialize:c=>String(c),deserialize:c=>{const E=Number(c);return oe.includes(E)?E:oe[0]}}),[_,F]=d.useState(null),[U,L]=d.useState(!1),[A,k]=d.useState(null),[ie,gt]=d.useState(!1);d.useEffect(()=>{const c=document.querySelector('[data-testid="app-scroll"]'),E=()=>c?c.scrollTop:window.scrollY,K=()=>{gt(E()>=Bs)};K();const me=c??window;return me.addEventListener("scroll",K,{passive:!0}),()=>me.removeEventListener("scroll",K)},[]);const[q,ce]=$(O.logs.selectedApiKeys,[],{serialize:JSON.stringify,deserialize:c=>{try{const E=JSON.parse(c);return Array.isArray(E)?E.map(K=>Number(K)).filter(K=>Number.isInteger(K)&&K>0):[]}catch{return[]}}}),[ht,ft]=d.useState(()=>typeof window>"u"||window.matchMedia("(min-width: 768px)").matches),{resetVisibleColumns:bt,rowDensity:yt,setRowDensity:jt,showScrollHint:vt,tableScrollRef:Nt,toggleColumn:wt,visibleColumnCount:kt,visibleColumns:Ct,visibleColumnSet:St,autoHiddenColumns:_t,effectiveVisibleColumns:Et,effectiveVisibleColumnCount:Lt,effectiveVisibleColumnSet:Rt}=Us(),[G,Fe]=vs(),De=d.useRef(!1);d.useEffect(()=>{if(De.current)return;const c=["status","endpoint","provider","model","clientKind","session","from","to"];if(!c.some(Ce=>G.has(Ce)))return;De.current=!0,o("all"),r("all"),x(""),b("all"),j(""),g("all"),w(""),y(""),ce([]);const E=G.get("status");(E==="success"||E==="error")&&g(E);const K=G.get("endpoint");K&&r(K);const me=G.get("provider");me&&o(me);const Ve=G.get("model");Ve&&x(Ve);const $e=G.get("clientKind");$e&&b($e);const He=G.get("session");He&&j(He);const Ue=G.get("from");Ue&&w(Ue);const Qe=G.get("to");Qe&&y(Qe);const Be=new URLSearchParams(G);for(const Ce of c)Be.delete(Ce);Fe(Be,{replace:!0})},[G,b,r,w,x,o,Fe,ce,j,g,y]);const Ft=d.useDeferredValue(u),z=u===""?"":Ft,Dt=d.useDeferredValue(N),Y=N===""?"":Dt;d.useEffect(()=>{S(1),k(null)},[a,s,z,f,Y,v,n,h,R,q]);const ye=d.useMemo(()=>{const c={limit:R,offset:(p-1)*R};a!=="all"&&(c.provider=a),s!=="all"&&(c.endpoint=s),z.trim().length>0&&(c.model=z.trim()),f!=="all"&&(c.clientKind=f),Y.trim().length>0&&(c.session=Y.trim()),v!=="all"&&(c.status=v);const E=Ge(n),K=Ge(h,!0);return E!==void 0&&(c.from=E),K!==void 0&&(c.to=K),q.length>0&&(c.apiKeys=q.join(",")),c},[z,Y,f,s,n,p,R,a,q,v,h]),X=ne(se.logs.list(ye),Re.listRequest(ye),{gcTime:6e4,refetchInterval:m&&p===1&&A===null&&!U&&!ie?Qs:!1}),ae=ne(se.providers.all(),We.providersRequest()),Te=ne(se.apiKeys.all(),{url:"/api/keys",method:"GET"}),je=ne(se.customEndpoints.all(),{url:"/api/custom-endpoints",method:"GET"}),Ke=ne(se.config.exportTimeout(),We.configRequest());d.useEffect(()=>{!X.isError||!X.error||l({title:t("logs.toast.listError.title"),description:t("logs.toast.listError.desc",{message:X.error.message}),variant:"error"})},[X.error,X.isError,l,t]),d.useEffect(()=>{!ae.isError||!ae.error||l({title:t("logs.toast.providerError.title"),description:t("logs.toast.providerError.desc",{message:ae.error.message}),variant:"error"})},[ae.error,ae.isError,l,t]);const fe=((Pe=X.data)==null?void 0:Pe.total)??0,de=fe>0?Math.ceil(fe/R):0,Tt=((Ae=X.data)==null?void 0:Ae.items)??[],Kt=(Oe=X.data)==null?void 0:Oe.cost_currency,Mt=d.useMemo(()=>{var E;const c=(E=Ke.data)==null?void 0:E.logExportTimeoutSeconds;return typeof c=="number"&&Number.isFinite(c)?Math.min(Math.max(Math.round(c),5),600)*1e3:6e4},[(qe=Ke.data)==null?void 0:qe.logExportTimeoutSeconds]);d.useEffect(()=>{de>0&&p>de&&S(de)},[p,de]);const ve=ae.data??[],Ne=d.useMemo(()=>{const c=new Map;for(const E of ve)E.id&&c.set(E.id,E.label??E.id);return c},[ve]),Me=d.useMemo(()=>{var E;const c=new Map;c.set("anthropic",t("logs.filters.endpointAnthropic")),c.set("openai",t("logs.filters.endpointOpenAI"));for(const K of((E=je.data)==null?void 0:E.endpoints)??[])c.set(K.id,K.label||K.id);return c},[(ze=je.data)==null?void 0:ze.endpoints,t]),Pt=d.useMemo(()=>{const c=[];if(a!=="all"){const E=Ne.get(a)??a;c.push({key:"provider",label:`${t("logs.filters.provider")}: ${E}`,onRemove:()=>o("all")})}if(s!=="all"){const E=Me.get(s)??s;c.push({key:"endpoint",label:`${t("logs.filters.endpoint")}: ${E}`,onRemove:()=>r("all")})}if(z.trim()&&c.push({key:"model",label:`${t("logs.filters.modelId")}: ${z.trim()}`,onRemove:()=>x("")}),f!=="all"&&c.push({key:"clientKind",label:`${t("logs.filters.clientKind")}: ${t(`dashboard.usage.clientKinds.${f}`,{defaultValue:f})}`,onRemove:()=>b("all")}),Y.trim()&&c.push({key:"session",label:`${t("logs.filters.session")}: ${Y.trim()}`,onRemove:()=>j("")}),v!=="all"){const E=t(v==="success"?"logs.filters.statusSuccess":"logs.filters.statusError");c.push({key:"status",label:`${t("logs.filters.status")}: ${E}`,onRemove:()=>g("all")})}return n&&c.push({key:"from",label:`${t("logs.filters.startDate")}: ${n}`,onRemove:()=>w("")}),h&&c.push({key:"to",label:`${t("logs.filters.endDate")}: ${h}`,onRemove:()=>y("")}),q.length>0&&c.push({key:"apiKeys",label:t("logs.filters.apiKeySelected",{count:q.length}),onRemove:()=>ce([])}),c},[z,Y,f,s,Me,n,a,Ne,q.length,v,t,h]),we=Te.data??[],At=d.useMemo(()=>{const c=new Map;for(const E of we)c.set(E.id,E);return c},[we]),Ot=d.useMemo(()=>le.map(c=>({id:c,label:t(`logs.table.columns.${c}`)})),[t]),ue=d.useMemo(()=>{const c=new Date;return`${c.getFullYear()}-${String(c.getMonth()+1).padStart(2,"0")}-${String(c.getDate()).padStart(2,"0")}`},[]),qt=d.useMemo(()=>f!=="all"||Y.trim()!==""?null:a==="all"&&s==="all"&&z.trim()===""&&v==="all"&&n===""&&h===""&&q.length===0?"all":v==="error"&&s==="all"&&a==="all"&&z.trim()===""&&n===""&&h===""&&q.length===0?"errors":Es(n,h,ue)&&s==="all"&&a==="all"&&z.trim()===""&&v==="all"&&q.length===0?"today":s==="anthropic"&&a==="all"&&z.trim()===""&&v==="all"&&n===""&&h===""&&q.length===0?"anthropic":s==="openai"&&a==="all"&&z.trim()===""&&v==="all"&&n===""&&h===""&&q.length===0?"openai":null,[z,Y,f,s,n,a,q.length,v,h,ue]),ke=d.useCallback(()=>{o("all"),x(""),b("all"),j(""),r("all"),g("all"),w(""),y(""),ce([])},[]),zt=d.useCallback(c=>{if(S(1),ke(),c!=="all"){if(c==="errors"){g("error");return}if(c==="today"){w(ue),y(ue);return}if(c==="anthropic"){r("anthropic");return}c==="openai"&&r("openai")}},[ke,ue]),{exporting:It,handleExport:Vt}=As({exportTimeoutMs:Mt,queryParams:ye,total:fe}),$t=d.useCallback(c=>{i.removeQueries({queryKey:["logs","detail"],type:"inactive"}),F(c),L(!0)},[i]),Ht=d.useCallback(()=>{L(!1)},[]),Ut=d.useCallback(c=>{k(E=>E===c?null:c)},[]);return d.useEffect(()=>{U||_===null||(i.removeQueries({queryKey:se.logs.detail(_),exact:!0}),F(null))},[U,i,_]),{activeFilters:Pt,activeQuickView:qt,apiKeyMap:At,apiKeys:we,apiKeysQuery:Te,applyQuickView:zt,autoRefresh:m,clientKindFilter:f,columnOptions:Ot,customEndpoints:(Ie=je.data)==null?void 0:Ie.endpoints,endpointFilter:s,exporting:It,expandedLogId:A,filtersExpanded:ht,fromDate:n,handleCloseDetail:Ht,handleExport:Vt,handleOpenDetail:$t,handleResetFilters:ke,handleToggleExpand:Ut,isDetailOpen:U,items:Tt,costCurrency:Kt,logsQuery:X,modelFilter:u,page:p,pageSize:R,providerFilter:a,providerLabelMap:Ne,providerOptions:ve,rowDensity:yt,resetVisibleColumns:bt,selectedApiKeys:q,selectedLogId:_,sessionFilter:N,setAutoRefresh:D,setClientKindFilter:b,setEndpointFilter:r,setFiltersExpanded:ft,setFromDate:w,setModelFilter:x,setPage:S,setPageSize:M,setProviderFilter:o,setRowDensity:jt,setSelectedApiKeys:ce,setSessionFilter:j,setStatusFilter:g,setToDate:y,showScrollHint:vt,statusFilter:v,tableScrollRef:Nt,toDate:h,toggleColumn:wt,total:fe,totalPages:de,autoHiddenColumns:_t,effectiveVisibleColumns:Et,effectiveVisibleColumnCount:Lt,effectiveVisibleColumnSet:Rt,visibleColumnCount:kt,visibleColumns:Ct,visibleColumnSet:St}}function gl(){var l;const t=Ws();return e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx(ts,{actions:e.jsx(Ds,{autoRefresh:t.autoRefresh,columnOptions:t.columnOptions,exporting:t.exporting,onExport:()=>void t.handleExport(),onRefresh:()=>void t.logsQuery.refetch(),onResetColumns:t.resetVisibleColumns,onSetDensity:t.setRowDensity,onToggleAutoRefresh:t.setAutoRefresh,onToggleColumn:t.toggleColumn,refreshing:t.logsQuery.isFetching,rowDensity:t.rowDensity,visibleColumns:t.visibleColumns,visibleColumnSet:t.visibleColumnSet,autoHiddenColumns:t.autoHiddenColumns})}),e.jsx(Ls,{activeFilters:t.activeFilters,filtersExpanded:t.filtersExpanded,setFiltersExpanded:t.setFiltersExpanded,handleResetFilters:t.handleResetFilters,activeQuickView:t.activeQuickView,applyQuickView:t.applyQuickView,providerFilter:t.providerFilter,setProviderFilter:t.setProviderFilter,endpointFilter:t.endpointFilter,setEndpointFilter:t.setEndpointFilter,selectedApiKeys:t.selectedApiKeys,setSelectedApiKeys:t.setSelectedApiKeys,modelFilter:t.modelFilter,setModelFilter:t.setModelFilter,clientKindFilter:t.clientKindFilter,setClientKindFilter:t.setClientKindFilter,sessionFilter:t.sessionFilter,setSessionFilter:t.setSessionFilter,statusFilter:t.statusFilter,setStatusFilter:t.setStatusFilter,fromDate:t.fromDate,setFromDate:t.setFromDate,toDate:t.toDate,setToDate:t.setToDate,providerOptions:t.providerOptions,apiKeys:t.apiKeys,apiKeysLoading:t.apiKeysQuery.isLoading,customEndpoints:t.customEndpoints}),e.jsx(Ps,{tableScrollRef:t.tableScrollRef,visibleColumnSet:t.effectiveVisibleColumnSet,visibleColumnCount:t.effectiveVisibleColumnCount,autoHiddenColumns:t.autoHiddenColumns,logsError:t.logsQuery.isError?((l=t.logsQuery.error)==null?void 0:l.message)??null:null,logsPending:t.logsQuery.isPending,items:t.items,costCurrency:t.costCurrency,activeFiltersCount:t.activeFilters.length,total:t.total,handleResetFilters:t.handleResetFilters,handleRetry:()=>void t.logsQuery.refetch(),providerLabelMap:t.providerLabelMap,apiKeyMap:t.apiKeyMap,handleOpenDetail:t.handleOpenDetail,expandedLogId:t.expandedLogId,onToggleExpand:t.handleToggleExpand,rowDensity:t.rowDensity,showScrollHint:t.showScrollHint,pageSize:t.pageSize,setPageSize:t.setPageSize,page:t.page,totalPages:t.totalPages,setPage:t.setPage}),e.jsx(Rs,{open:t.isDetailOpen,logId:t.selectedLogId,onClose:t.handleCloseDetail,providerLabelMap:t.providerLabelMap,apiKeyMap:t.apiKeyMap})]})}export{gl as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{j as s}from"./vendor-
|
|
1
|
+
import{j as s}from"./vendor-C-lQMZp3.js";import{j as d}from"./app-DZpd2fu9.js";import{c as l}from"./global-BCYo_xAt.js";function p({title:a,description:e,eyebrow:t,actions:r,className:x,contentClassName:n,children:c}){const m=a||e||t||r;return s.jsxs("div",{className:l(d({variant:"default"}),x),children:[m&&s.jsxs("div",{className:"flex flex-col gap-4 p-6 pb-0 sm:flex-row sm:items-start sm:justify-between",children:[s.jsxs("div",{className:"min-w-0 space-y-1.5",children:[t?s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-primary/80",children:t}):null,typeof a=="string"?s.jsx("h2",{className:"text-base font-semibold text-foreground",children:a}):a,e&&(typeof e=="string"?s.jsx("p",{className:"text-sm text-muted-foreground/70",children:e}):s.jsx("div",{className:"text-sm text-muted-foreground/70",children:e}))]}),r&&s.jsx("div",{className:"w-full shrink-0 sm:w-auto",children:r})]}),s.jsx("div",{className:l("p-6",!m&&"pt-6",n),children:c})]})}export{p as P};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{j as e,T as u}from"./vendor-
|
|
1
|
+
import{j as e,T as u}from"./vendor-C-lQMZp3.js";import{c as n}from"./global-BCYo_xAt.js";const x={default:"border-border/30 bg-card",primary:"border-foreground/10 bg-card",danger:"border-destructive/15 bg-card"},c={default:"bg-secondary text-muted-foreground",primary:"bg-secondary text-foreground",danger:"bg-destructive/10 text-destructive"};function o({icon:r,title:t,description:s,action:a,className:l,compact:i=!1,inline:m=!1,tone:d="default"}){return m?e.jsxs("div",{className:n("flex flex-wrap items-center justify-center gap-x-2.5 gap-y-1.5 rounded-lg border border-dashed px-4 py-3 text-center",x[d],l),children:[r?e.jsx("span",{className:n("flex h-6 w-6 shrink-0 items-center justify-center rounded-md",c[d]),children:r}):null,e.jsx("span",{className:"text-sm font-medium text-foreground",children:t}),s?e.jsx("span",{className:"text-sm text-muted-foreground",children:s}):null,a?e.jsx("span",{className:"flex flex-wrap items-center gap-2",children:a}):null]}):e.jsxs("div",{className:n("flex flex-col items-center justify-center rounded-xl border-2 border-dashed px-6 text-center",i?"min-h-[180px] py-8":"min-h-[260px] py-12",x[d],l),children:[r?e.jsx("div",{className:n("mb-4 flex h-12 w-12 items-center justify-center rounded-2xl",c[d]),children:r}):null,e.jsxs("div",{className:"max-w-xl space-y-1.5",children:[e.jsx("div",{className:"text-base font-semibold tracking-[-0.01em]",children:t}),s?e.jsx("div",{className:"text-sm text-muted-foreground",children:s}):null]}),a?e.jsx("div",{className:"mt-5 flex flex-wrap items-center justify-center gap-2",children:a}):null]})}function g({label:r,className:t,compact:s=!1}){return e.jsx(o,{className:t,compact:s,tone:"primary",icon:e.jsx(u,{className:"h-5 w-5 animate-spin","aria-hidden":"true"}),title:r})}export{g as P,o as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as x,j as r}from"./vendor-
|
|
1
|
+
import{r as x,j as r}from"./vendor-C-lQMZp3.js";import{c as d}from"./global-BCYo_xAt.js";import{o as u}from"./app-DZpd2fu9.js";import{u as f}from"./i18n-ClvfZhYc.js";import{b as p}from"./router-Bkbjq53m.js";function g(){var s;const{t:l}=f(),i=p(),e=(s=u(i.pathname))==null?void 0:s.nav,t=e?l(e.titleKey??e.labelKey):"";return x.useEffect(()=>{document.title=t?`${t} · cc-gw`:"cc-gw"},[t]),{title:t,description:e!=null&&e.descriptionKey?l(e.descriptionKey):""}}function y({title:l,description:i,info:e,status:t,actions:s,className:m}){const c=g(),n=l??c.title,o=i??c.description,a=t||e;return!n&&!a&&!s?null:r.jsxs("div",{className:d("flex flex-col gap-3",m),children:[(n||s)&&r.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between",children:[r.jsxs("div",{className:"min-w-0 space-y-1",children:[n?r.jsx("h1",{className:"truncate text-xl text-foreground",children:n}):null,o?r.jsx("p",{className:"text-sm leading-6 text-muted-foreground",children:o}):null]}),s?r.jsx("div",{className:"flex shrink-0 flex-wrap items-center gap-2",children:s}):null]}),a?r.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[t,e]}):null]})}export{y as P};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as m,j as e,aI as Ge,aJ as Ue,aK as Je,aL as Xe,aM as Ye,aN as Ze,aO as es,aP as ss,aQ as ts,aR as rs,aS as as,aD as ns,aT as is,aU as ls,aV as os,a4 as ds,av as cs,aW as us}from"./vendor-JUtelXU0.js";import{C as de}from"./ConfirmDialog-CRSbmgE7.js";import{P as ms}from"./PageToolbar-CnLp4aWt.js";import{B as Y}from"./badge-eRkhnmCs.js";import{t as ce,b as Te,q as ue,B as k,u as Ke,e as _e,d as ze,C as be,c as je,s as De}from"./app-CRxPj2SJ.js";import{r as ps,m as Ve,a as xs,u as gs,s as hs}from"./modelManagement-DwdbGu0o.js";import{g as Pe}from"./gateway-DyhqzHSh.js";import{L as ee,I as G}from"./label-CdbE1ezd.js";import{D as ye,A as Ne,a as we,b as Ce,c as Se,d as ke,e as Me}from"./DialogShell-DxWKa5oR.js";import{S as Re,a as Ee,b as Oe,c as Ae,e as He,f as $e,d as ne,D as Qe}from"./disclosure-CU-KJc8C.js";import{P as fs,a as vs,d as bs,b as js,p as Ie,u as ys,B as Ns,M as ws,c as Cs}from"./useProviderForm-DIuM3Z2u.js";import{u as q}from"./i18n-v60Yn7Ls.js";import{a as fe}from"./PageState-XybOeENt.js";import{c as te}from"./global-BLUcvOa8.js";import{T as Ss}from"./TargetCombobox-DkVdA04_.js";import{u as We}from"./useAppMutation-B29oVzxS.js";import{c as ks}from"./clipboard-DqvcglYs.js";import{S as Ms}from"./switch-CZn1nypU.js";import{g as Ds}from"./router-CqUBCAsx.js";import"./query-CvboQrUT.js";import"./radix-d0BukFWM.js";import"./popover-CuM9b3U7.js";function Ps(s){const{t,pushToast:i,config:r,setConfig:p,configQuery:n,customEndpoints:j,ensureConfig:x}=s,[h,a]=m.useState(""),[d,b]=m.useState("all"),[c,o]=m.useState(null),[E,O]=m.useState({}),[g,v]=m.useState(!1),[M,A]=m.useState(null),[$,L]=m.useState(!0),[T,l]=m.useState({}),[w,F]=m.useState(null),P=(r==null?void 0:r.providers)??[],D=P.length,y=m.useMemo(()=>P.filter(f=>{var z;if(!(d==="all"||(f.type??"custom")===d))return!1;const S=h.trim().toLowerCase();return S?[f.id,f.label??"",f.baseUrl??"",f.defaultModel??"",...((z=f.models)==null?void 0:z.map(re=>re.id))??[]].join(" ").toLowerCase().includes(S):!0}),[h,d,P]),U=m.useMemo(()=>{const f=new Map;for(const C of P){if(!C.defaultModel||!C.models)continue;const S=C.models.find(N=>N.id===C.defaultModel);S&&f.set(C.id,ps(S))}return f},[P]),B=m.useMemo(()=>[{key:"anthropic-beta",value:"claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14",label:t("providers.testDialog.options.beta.label"),description:t("providers.testDialog.options.beta.description")}],[t]),J=async f=>{if(!r)throw new Error(t("settings.toast.missingConfig"));const C={...r,providers:[...P,f]};await Pe.saveConfig(C),p(C),n.refetch(),i({title:t("providers.toast.createSuccess",{name:f.label||f.id}),variant:"success"})},u=async f=>{if(!r)throw new Error(t("settings.toast.missingConfig"));const C={...r,providers:P.map(S=>S.id===f.id?f:S)};await Pe.saveConfig(C),p(C),n.refetch(),i({title:t("providers.toast.updateSuccess",{name:f.label||f.id}),variant:"success"})},I=(f,C)=>{O(S=>({...S,[f]:C}))},_=async(f,C)=>{o(f.id);try{const S={provider:f};C!=null&&C.headers&&Object.keys(C.headers).length>0&&(S.headers=C.headers),C!=null&&C.query&&C.query.trim().length>0&&(S.query=C.query.trim());const N=await Ve.testProvider(f.id,S);if(N.ok){I(f.id,{ok:!0,status:N.status,statusText:N.statusText,durationMs:N.durationMs,testedAt:Date.now()}),i({title:t("providers.toast.testSuccess"),description:t("providers.toast.testSuccessDesc",{status:N.status,duration:N.durationMs?`${N.durationMs} ms`:"—"}),variant:"success"});return}I(f.id,{ok:!1,status:N.status,statusText:N.statusText,durationMs:N.durationMs,message:`${N.status} ${N.statusText}`,testedAt:Date.now()}),i({title:t("providers.toast.testFailure",{message:`${N.status} ${N.statusText}`}),variant:"error"})}catch(S){const N=ce(S),z=N.status?`${N.status} ${N.message}`:N.message;I(f.id,{ok:!1,status:N.status,message:z,testedAt:Date.now()}),i({title:t("providers.toast.testFailure",{message:z}),variant:"error"})}finally{o(null)}},W=f=>{var me,pe;if(!(!!((me=f.defaultModel)!=null&&me.trim())||!!((pe=f.models)!=null&&pe.some(X=>X.id.trim().length>0)))){F(f);return}if(f.type!=="anthropic"){_(f);return}const S=f.extraHeaders??{},N=new Map(B.map(X=>[X.key.toLowerCase(),X])),z={};let re=!0;for(const X of B){const ae=Object.entries(S).find(([ge])=>ge.toLowerCase()===X.key.toLowerCase());if(!ae)continue;const[xe,ie]=ae;String(ie??"")!==X.value&&(re=!1,z[xe]=String(ie??""))}for(const[X,ae]of Object.entries(S))N.has(X.toLowerCase())||(z[X]=String(ae??""));l(z),L(re),A(f),v(!0)},K=()=>{v(!1),A(null),L(!0),l({})};return{providers:P,providerCount:D,filteredProviders:y,providerSearch:h,setProviderSearch:a,providerTypeFilter:d,setProviderTypeFilter:b,defaultLabels:U,testingProviderId:c,testResults:E,testDialogOpen:g,testDialogProvider:M,testDialogUsePreset:$,setTestDialogUsePreset:L,testDialogPreservedExtras:T,noModelDialogProvider:w,setNoModelDialogProvider:F,anthropicTestHeaderOptions:B,handleCreateProvider:J,handleUpdateProvider:u,handleDeleteProvider:async f=>{var ae,xe,ie,ge,Le,Fe;if(!x())return;const C=P.filter(R=>R.id!==f.id).map(R=>{if(R.type!=="aggregate"||!R.models)return R;const H=R.models.map(Z=>({...Z,members:(Z.members??[]).filter(he=>he.target.split(":")[0]!==f.id)})).filter(Z=>(Z.members??[]).length>0),se=H.some(Z=>Z.id===R.defaultModel)?R.defaultModel:void 0;return{...R,models:H,defaultModel:se}}),S=R=>{const H={};if(!R)return H;for(const[se,Z]of Object.entries(R)){if(!Z)continue;const[he]=Z.split(":");he&&he===f.id||Z===f.id||(H[se]=Z)}return H},N=R=>{if(!R)return R;const H=se=>se&&xs(se,f.id)?null:se;return{...R,completion:H(R.completion),reasoning:H(R.reasoning),background:H(R.background)}},z=(r==null?void 0:r.endpointRouting)??{},re=S(((ae=z.anthropic)==null?void 0:ae.modelRoutes)??(r==null?void 0:r.modelRoutes)??{}),me=S(((xe=z.openai)==null?void 0:xe.modelRoutes)??{}),pe=((r==null?void 0:r.customEndpoints)??j).map(R=>{const H=R.routing;if(!H)return R;const se=H.defaults?N(H.defaults):H.modelRoutes?N(r.defaults):void 0;return{...R,routing:{...H,...se?{defaults:se}:{},...H.modelRoutes?{modelRoutes:S(H.modelRoutes)}:{}}}}),X={...r,providers:C,defaults:N(r.defaults)??r.defaults,modelRoutes:re,customEndpoints:pe,endpointRouting:{anthropic:{defaults:N(((ie=z.anthropic)==null?void 0:ie.defaults)??r.defaults)??r.defaults,modelRoutes:re,compatibility:(ge=z.anthropic)==null?void 0:ge.compatibility},openai:{defaults:N(((Le=z.openai)==null?void 0:Le.defaults)??r.defaults)??r.defaults,modelRoutes:me,compatibility:(Fe=z.openai)==null?void 0:Fe.compatibility}}};try{await Pe.saveConfig(X),p(X),i({title:t("providers.toast.deleteSuccess",{name:f.label||f.id}),variant:"success"}),n.refetch()}catch(R){i({title:t("providers.toast.deleteFailure",{message:ce(R).message}),variant:"error"})}},handleTestConnection:_,initiateTestConnection:W,closeTestDialog:K,confirmTestDialog:async()=>{if(!M)return;const f={};if($)for(const N of B)f[N.key]=N.value;const C=new Map(B.map(N=>[N.key.toLowerCase(),N]));for(const[N,z]of Object.entries(T))C.get(N.toLowerCase())&&$||(f[N]=z);const S=M;K(),await _(S,{headers:Object.keys(f).length>0?f:void 0})}}}const le="preset:",oe="manual:",Ts=[{value:"openai",labelKey:"providers.presets.manualOpenAiCompatible"},{value:"anthropic",labelKey:"providers.presets.manualAnthropicCompatible"},{value:"aggregate",labelKey:"providers.aggregate.typeLabel"}];function Rs({open:s,onOpenChange:t,existingProviderIds:i,onSubmit:r,onCreated:p}){const{t:n,i18n:j}=q(),[x,h]=m.useState(""),[a,d]=m.useState(""),[b,c]=m.useState(""),[o,E]=m.useState(""),[O,g]=m.useState({}),[v,M]=m.useState(null),[A,$]=m.useState(!1),L=Te(ue.providers.presets(),{url:"/api/provider-presets",method:"GET"},{retry:!1,staleTime:1/0,enabled:s}),T=m.useMemo(()=>{var u;return((u=L.data)==null?void 0:u.presets)??[]},[L.data]),l=()=>{h(""),d(""),c(""),E(""),g({}),M(null),$(!1)},w=u=>{u||(t(!1),l())},F=u=>{var I;if(h(u),M(null),u.startsWith(le)){const _=T.find(W=>W.id===u.slice(le.length));if(_){E(_.baseUrl),g(Object.fromEntries(_.endpoints.map(W=>[W.id,W.baseUrl])));return}}if(u.startsWith(oe)){const _=u.slice(oe.length);E(((I=vs[_??"custom"])==null?void 0:I.baseUrl)??"")}g({})},P=u=>{d(u),(!b.trim()||b===a)&&c(u)},D=x.startsWith(le)?T.find(u=>u.id===x.slice(le.length)):void 0,y=x.startsWith(oe)?x.slice(oe.length):void 0,U=y==="aggregate",B=u=>{var I;return(I=j.resolvedLanguage)!=null&&I.startsWith("en")?n(`providers.presets.catalog.${u.id}`,{defaultValue:u.description}):u.description},J=async()=>{const u=a.trim(),I=o.trim();if(!u){M({field:"id",message:n("providers.drawer.errors.idRequired")});return}if(i.includes(u)){M({field:"id",message:n("providers.drawer.errors.idDuplicate")});return}if(!U){if(!I){M({field:"baseUrl",message:n("providers.drawer.errors.baseUrlInvalid")});return}try{new URL(I)}catch{M({field:"baseUrl",message:n("providers.drawer.errors.baseUrlInvalid")});return}for(const V of(D==null?void 0:D.endpoints)??[]){const Q=(O[V.id]??V.baseUrl).trim();try{new URL(Q)}catch{M({field:"endpointUrl",endpointId:V.id,message:n("providers.endpoints.errors.baseUrlInvalid")});return}}}const _=D?D.type:y??"custom",W=bs(_),K={id:u,label:b.trim()||u,type:_,baseUrl:U?void 0:I,authMode:W==="apiKey"&&_!=="anthropic"?void 0:W,...D!=null&&D.balanceAdapter?{balanceAdapter:D.balanceAdapter}:null,...D&&D.endpoints.length>0?{endpoints:D.endpoints.map(V=>({id:V.id,protocol:V.protocol,baseUrl:(O[V.id]??V.baseUrl).trim()}))}:null};D&&D.defaultModels.length>0&&(K.models=D.defaultModels.map(V=>({id:V})),K.defaultModel=D.defaultModels[0]),$(!0);try{await r(K)}catch(V){$(!1),M({field:null,message:n("providers.drawer.toast.saveFailure",{message:ce(V).message})});return}p(u),w(!1)};return e.jsx(ye,{open:s,onOpenChange:w,children:e.jsxs(Ne,{className:"max-w-lg",children:[e.jsxs(we,{children:[e.jsx(Ce,{children:n("providers.presets.title")}),e.jsx(Se,{children:n("providers.presets.description")})]}),e.jsxs(ke,{className:"space-y-4",children:[e.jsxs(ee,{className:"flex flex-col gap-2 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:n("providers.presets.template")}),e.jsxs(Re,{value:x,onValueChange:F,children:[e.jsx(Ee,{"aria-label":n("providers.presets.template"),children:e.jsx(Oe,{placeholder:n("providers.presets.templatePlaceholder")})}),e.jsxs(Ae,{children:[T.length>0?e.jsxs(He,{children:[e.jsx($e,{children:n("providers.presets.groupPresets")}),T.map(u=>e.jsx(ne,{value:`${le}${u.id}`,children:e.jsxs("span",{className:"flex flex-col",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:B(u)})]})},u.id))]}):null,e.jsxs(He,{children:[e.jsx($e,{children:n("providers.presets.groupManual")}),Ts.map(u=>e.jsx(ne,{value:`${oe}${u.value}`,children:n(u.labelKey)},u.value))]})]})]})]}),D?e.jsxs("p",{className:"border border-border bg-secondary/50 px-3 py-2 text-xs leading-relaxed text-muted-foreground",children:[B(D),D.noModelProbe?` ${n("providers.presets.noModelProbeNote")}`:""]}):null,e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs(ee,{className:"flex flex-col gap-2 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:n("providers.drawer.fields.id")}),e.jsx(G,{value:a,onChange:u=>P(u.target.value),placeholder:n("providers.drawer.fields.idPlaceholder"),"aria-invalid":(v==null?void 0:v.field)==="id","aria-describedby":v?"create-provider-error":void 0})]}),e.jsxs(ee,{className:"flex flex-col gap-2 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:n("providers.drawer.fields.label")}),e.jsx(G,{value:b,onChange:u=>c(u.target.value),placeholder:n("providers.drawer.fields.labelPlaceholder")})]})]}),U?e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:n("providers.aggregate.drawer.explainerBody")}):e.jsxs(ee,{className:"flex flex-col gap-2 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:n("providers.drawer.fields.baseUrl")}),e.jsx(G,{value:o,onChange:u=>E(u.target.value),placeholder:n("providers.drawer.fields.baseUrlPlaceholder"),"aria-invalid":(v==null?void 0:v.field)==="baseUrl","aria-describedby":v?"create-provider-error":void 0})]}),D&&D.endpoints.length>0&&!U?e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:n("providers.presets.endpointsHint")}),D.endpoints.map(u=>{var _;const I=((_=fs.find(W=>W.value===u.protocol))==null?void 0:_.label)??u.protocol;return e.jsxs(ee,{className:"flex flex-col gap-2 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:n("providers.presets.endpointBaseUrl",{protocol:I})}),e.jsx(G,{value:O[u.id]??u.baseUrl,onChange:W=>g(K=>({...K,[u.id]:W.target.value})),"aria-invalid":(v==null?void 0:v.field)==="endpointUrl"&&v.endpointId===u.id,"aria-describedby":v?"create-provider-error":void 0})]},u.id)})]}):null,v?e.jsx("p",{id:"create-provider-error",className:"text-xs text-destructive","aria-live":"polite",children:v.message}):null]}),e.jsxs(Me,{children:[e.jsx(k,{variant:"outline",onClick:()=>w(!1),disabled:A,children:n("common.actions.cancel")}),e.jsx(k,{onClick:()=>void J(),disabled:A||!x,children:n(A?"common.actions.saving":"providers.presets.createAction")})]})]})})}function Es({open:s,provider:t,onClose:i,onEdit:r}){const{t:p}=q();return t?e.jsx(ye,{open:s,onOpenChange:n=>!n&&i(),children:e.jsxs(Ne,{className:"max-w-md",children:[e.jsxs(we,{children:[e.jsx(Ce,{children:p("providers.noModelDialog.title")}),e.jsx(Se,{children:p("providers.noModelDialog.subtitle",{name:t.label||t.id})})]}),e.jsxs(ke,{className:"space-y-4",children:[e.jsx("div",{className:"rounded-xl bg-secondary p-4 text-sm text-muted-foreground",children:p("providers.noModelDialog.description")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:p("providers.noModelDialog.hint")})]}),e.jsxs(Me,{children:[e.jsx(k,{variant:"outline",onClick:i,children:p("common.actions.close")}),e.jsx(k,{onClick:()=>r(t),children:p("providers.noModelDialog.primary")})]})]})}):null}function Os(s){const{t}=q(),{form:i,errors:r,onModelIdChange:p,onAddModel:n,onRemoveModel:j,onAddMember:x,onRemoveMember:h,onMemberTargetChange:a,onReorderMembers:d,onModelFailoverChange:b,memberOptions:c}=s;return e.jsx("div",{className:"space-y-8",children:e.jsxs("section",{className:"space-y-4","aria-labelledby":"aggregate-model-fields",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{id:"aggregate-model-fields",className:"text-sm font-semibold",children:t("providers.aggregate.drawer.stepTitle")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t("providers.aggregate.drawer.modelsDescription")})]}),e.jsx(k,{type:"button",variant:"outline",size:"sm",onClick:n,className:"bg-card text-xs",children:t("providers.drawer.fields.addModel")})]}),r.models?e.jsx("p",{className:"text-xs text-destructive",children:r.models}):null,e.jsxs("div",{className:"space-y-4",children:[i.models.map((o,E)=>{var O,g;return e.jsxs("div",{"data-testid":"aggregate-model-card",className:"border border-border bg-card p-3",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(ee,{className:"flex flex-col gap-2 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:t("providers.aggregate.drawer.modelIdLabel")}),e.jsx(G,{value:o.id,onChange:v=>p(E,v.target.value),placeholder:t("providers.aggregate.drawer.modelIdPlaceholder"),className:"font-mono"})]}),e.jsx("p",{className:"self-end text-xs leading-relaxed text-muted-foreground",children:t("providers.aggregate.drawer.modelIdHint")})]}),e.jsx(As,{modelKey:o._key,members:o.members,options:c,error:(O=r.members)==null?void 0:O[o._key],onAddMember:x,onRemoveMember:h,onMemberTargetChange:a,onReorderMembers:d}),e.jsxs(Qe,{summary:t("providers.aggregate.drawer.failoverTitle"),className:"mt-3 bg-secondary/50",summaryClassName:"px-3 py-2 text-xs font-medium",contentClassName:"space-y-4 px-3 py-3",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs(ee,{className:"flex flex-col gap-1.5 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:t("providers.aggregate.drawer.consecutiveFailures")}),e.jsx(G,{type:"number",min:1,value:o.failover.consecutiveFailures,onChange:v=>b(o._key,{consecutiveFailures:v.target.value}),placeholder:t("providers.aggregate.drawer.consecutiveFailuresHint")})]}),e.jsxs(ee,{className:"flex flex-col gap-1.5 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:t("providers.aggregate.drawer.cooldownSeconds")}),e.jsx(G,{type:"number",min:1,max:86400,value:o.failover.cooldownSeconds,onChange:v=>b(o._key,{cooldownSeconds:v.target.value}),placeholder:t("providers.aggregate.drawer.cooldownSecondsHint")})]}),e.jsxs(ee,{className:"flex flex-col gap-1.5 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:t("providers.aggregate.drawer.failureWindowSeconds")}),e.jsx(G,{type:"number",min:1,value:o.failover.failureWindowSeconds,onChange:v=>b(o._key,{failureWindowSeconds:v.target.value}),placeholder:t("providers.aggregate.drawer.failureWindowSecondsHint")})]})]}),e.jsxs(ee,{className:"flex flex-col gap-1.5 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:t("providers.aggregate.drawer.triggerStatusCodes")}),e.jsx(G,{value:o.failover.triggerStatusCodes,onChange:v=>b(o._key,{triggerStatusCodes:v.target.value}),placeholder:t("providers.aggregate.drawer.triggerStatusCodesHint"),className:"font-mono text-xs",spellCheck:!1})]}),(g=r.failover)!=null&&g[o._key]?e.jsx("p",{className:"text-xs text-destructive",children:r.failover[o._key]}):null,e.jsx("p",{className:"text-[11px] text-muted-foreground",children:t("providers.aggregate.drawer.defaultsHint")})]}),e.jsx("div",{className:"mt-3 flex justify-end",children:e.jsx(k,{type:"button",variant:"ghost",size:"sm",className:"h-auto px-2 text-destructive",onClick:()=>j(E),children:t("providers.drawer.fields.removeModel")})})]},o._key)}),i.models.length===0?e.jsxs("div",{className:"rounded-xl border border-warning/30 bg-warning-bg p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-warning",children:t("providers.aggregate.drawer.noModelsTitle")}),e.jsx("p",{className:"mt-1 text-xs leading-relaxed text-warning",children:t("providers.aggregate.drawer.noModelsHint")})]}):null]})]})})}function As({modelKey:s,members:t,options:i,error:r,onAddMember:p,onRemoveMember:n,onMemberTargetChange:j,onReorderMembers:x}){const{t:h}=q(),a=Ge(Ue(Ye,{activationConstraint:{distance:6}}),Ue(Xe,{coordinateGetter:Je})),d=b=>{const{active:c,over:o}=b;!o||c.id===o.id||x(s,String(c.id),String(o.id))};return e.jsxs("div",{className:"mt-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:"text-xs font-medium text-foreground",children:h("providers.aggregate.drawer.membersTitle")}),e.jsx(k,{type:"button",variant:"outline",size:"sm","data-testid":"aggregate-add-member",onClick:()=>p(s),className:"h-7 bg-card px-2.5 text-[11px]",children:h("providers.aggregate.drawer.addMember")})]}),r?e.jsx("p",{className:"text-xs text-destructive",children:r}):null,t.length===0?e.jsx("p",{className:"border border-dashed border-border bg-secondary/40 px-3 py-3 text-xs text-muted-foreground",children:h("providers.aggregate.drawer.memberEmptyHint")}):e.jsx(Ze,{sensors:a,collisionDetection:es,onDragEnd:d,children:e.jsx(ss,{items:t.map(b=>b._key),strategy:ts,children:e.jsx("div",{className:"flex flex-col gap-1.5",children:t.map((b,c)=>e.jsx(Is,{modelKey:s,member:b,index:c,options:i,onRemoveMember:n,onMemberTargetChange:j},b._key))})})}),e.jsx("p",{className:"text-[11px] leading-relaxed text-muted-foreground",children:h("providers.aggregate.drawer.memberHint")})]})}function Is({modelKey:s,member:t,index:i,options:r,onRemoveMember:p,onMemberTargetChange:n}){const{t:j}=q(),{attributes:x,listeners:h,setNodeRef:a,setActivatorNodeRef:d,transform:b,transition:c,isDragging:o}=rs({id:t._key});return e.jsxs("div",{ref:a,"data-testid":"aggregate-member-row",style:{transform:is.Transform.toString(b),transition:c},className:te("flex items-center gap-2 border border-border bg-card p-2",o&&"z-10 opacity-60 shadow-[var(--surface-shadow-lg)]"),children:[e.jsx("button",{ref:d,type:"button","data-testid":"aggregate-member-grip","aria-label":j("workbench.routing.dragHandle"),className:"flex h-7 w-4 shrink-0 cursor-grab touch-none items-center justify-center text-muted-foreground hover:text-foreground active:cursor-grabbing",...x,...h,children:e.jsx(as,{className:"h-4 w-4","aria-hidden":!0})}),e.jsx("span",{className:"w-4 shrink-0 text-center text-[10.5px] tabular-nums text-muted-foreground",children:i+1}),i===0?e.jsx(Y,{variant:"outline",className:"shrink-0 px-1.5 text-[10px] font-normal text-muted-foreground",children:j("providers.aggregate.drawer.primaryBadge")}):null,e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(Ss,{value:t.target,onChange:E=>n(s,t._key,E),options:r,placeholder:j("providers.aggregate.drawer.memberPlaceholder"),ariaLabel:j("providers.aggregate.drawer.memberTarget")})}),e.jsx(k,{variant:"ghost",size:"icon","data-testid":"aggregate-member-delete",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>p(s,t._key),"aria-label":j("common.delete"),children:e.jsx(ns,{className:"h-3.5 w-3.5","aria-hidden":!0})})]})}function Ls({open:s,providerId:t,providerName:i,existingModelIds:r,draft:p,onImport:n,onClose:j}){const{t:x}=q(),{pushToast:h}=Ke(),[a,d]=m.useState({phase:"loading"}),[b,c]=m.useState(""),[o,E]=m.useState(new Set),O=m.useRef(p);O.current=p,m.useEffect(()=>{if(!s)return;d({phase:"loading"}),c(""),E(new Set);let l=!1;return Ve.probeModels(t,O.current).then(w=>{var F;l||(w.ok&&w.models?d({phase:"ready",models:w.models}):d({phase:"error",message:((F=w.statusText)==null?void 0:F.trim())||x("providers.drawer.probe.failedFallback"),status:w.status>0?w.status:void 0}))}).catch(w=>{l||d({phase:"error",message:ce(w).message})}),()=>{l=!0}},[s,t,x]);const g=m.useMemo(()=>new Set(r),[r]),v=m.useMemo(()=>{if(a.phase!=="ready")return[];const l=b.trim().toLowerCase();return l?a.models.filter(w=>w.id.toLowerCase().includes(l)||(w.label??"").toLowerCase().includes(l)):a.models},[a,b]),M=m.useMemo(()=>v.map(l=>l.id).filter(l=>!g.has(l)),[v,g]),A=l=>{E(w=>{const F=new Set(w);return F.has(l)?F.delete(l):F.add(l),F})},$=()=>{E(l=>new Set([...l,...M]))},L=()=>{E(new Set)},T=()=>{if(a.phase!=="ready"||o.size===0)return;const l=a.models.filter(w=>o.has(w.id));n(l),h({title:x("providers.drawer.probe.importSuccess",{count:l.length}),variant:"success"}),j()};return e.jsx(ye,{open:s,onOpenChange:l=>!l&&j(),children:e.jsxs(Ne,{className:"max-w-2xl",children:[e.jsxs(we,{children:[e.jsx(Ce,{children:x("providers.drawer.probe.title")}),e.jsx(Se,{children:x("providers.drawer.probe.subtitle",{name:i})})]}),e.jsxs(ke,{className:"space-y-4",children:[a.phase==="loading"?e.jsx("p",{className:"rounded-xl bg-secondary/50 px-4 py-6 text-center text-sm text-muted-foreground",children:x("providers.drawer.probe.loading")}):null,a.phase==="error"?e.jsxs("div",{className:"space-y-2 rounded-xl border border-warning/30 bg-warning-bg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-semibold text-warning",children:x("providers.drawer.probe.failedTitle")}),a.status?e.jsxs(Y,{variant:"warning",className:"shrink-0",children:["HTTP ",a.status]}):null]}),e.jsx("p",{className:"break-words text-xs leading-relaxed text-warning",children:a.message}),e.jsx("p",{className:"text-xs text-muted-foreground",children:x("providers.drawer.probe.failedHint")})]}):null,a.phase==="ready"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(G,{value:b,onChange:l=>c(l.target.value),placeholder:x("providers.drawer.probe.searchPlaceholder"),className:"h-9"}),e.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:x("providers.drawer.probe.totalCount",{count:a.models.length})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"h-auto bg-card px-2 py-1 text-xs",onClick:$,disabled:M.length===0,children:x("providers.drawer.probe.selectAll")}),e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"h-auto bg-card px-2 py-1 text-xs",onClick:L,disabled:o.size===0,children:x("providers.drawer.probe.clearSelection")})]}),e.jsx("span",{className:"text-muted-foreground",children:x("providers.drawer.probe.selectedCount",{count:o.size})})]}),v.length===0?e.jsx("p",{className:"rounded-xl bg-secondary/50 px-4 py-6 text-center text-sm text-muted-foreground",children:x("providers.drawer.probe.emptyResult")}):e.jsx("div",{className:"grid max-h-80 gap-1 overflow-y-auto",children:v.map(l=>{const w=g.has(l.id),F=o.has(l.id);return e.jsxs("label",{className:te("flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2.5 transition-colors",w?"cursor-not-allowed opacity-60":"cursor-pointer hover:border-foreground/30 hover:bg-accent/50",F&&"border-foreground bg-secondary"),children:[e.jsx("input",{type:"checkbox",className:"h-4 w-4 shrink-0 rounded border-input accent-primary",checked:F,disabled:w,onChange:()=>A(l.id)}),e.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-xs",children:l.id}),l.label?e.jsx("span",{className:"shrink-0 truncate text-xs text-muted-foreground",children:l.label}):null,w?e.jsx(Y,{variant:"secondary",className:"shrink-0",children:x("providers.drawer.probe.imported")}):null]},l.id)})})]}):null]}),e.jsxs(Me,{children:[e.jsx(k,{variant:"outline",onClick:j,children:x("common.actions.cancel")}),e.jsx(k,{onClick:T,disabled:a.phase!=="ready"||o.size===0,children:x("providers.drawer.probe.importAction",{count:o.size})})]})]})})}const qe={refresh(s){return _e(ze.post(`/api/providers/${s}/balance/refresh`))},all(){return _e(ze.get("/api/providers/balances"))}},Fs=[{value:"deepseek",label:"DeepSeek"},{value:"moonshot",label:"Moonshot / Kimi"},{value:"siliconflow",label:"SiliconFlow"},{value:"openrouter",label:"OpenRouter"}];function Us({form:s,errors:t,onKeyChange:i,onAddKey:r,onRemoveKey:p}){const{t:n}=q(),[j,x]=m.useState(new Set),h=a=>{x(d=>{const b=new Set(d);return b.has(a)?b.delete(a):b.add(a),b})};return e.jsxs("section",{className:"space-y-3","aria-labelledby":"provider-keys-fields",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{id:"provider-keys-fields",className:"text-sm font-semibold",children:s.keys.length>0?`${n("providers.keys.title")} (${s.keys.length})`:n("providers.keys.title")}),e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:n("providers.keys.hint")})]}),e.jsx(k,{type:"button",variant:"outline",size:"sm",onClick:r,className:"bg-card text-xs",children:n("providers.keys.add")})]}),s.keys.length>0?e.jsx("div",{className:"divide-y divide-border border border-border",children:s.keys.map((a,d)=>{var c;const b=(c=t.keys)==null?void 0:c[a._key];return e.jsxs("div",{className:"space-y-2 p-3","data-testid":"provider-key-row",children:[e.jsxs("div",{className:"grid gap-2 md:grid-cols-[auto_minmax(0,0.8fr)_minmax(0,0.8fr)_minmax(0,2fr)_auto_auto] md:items-center",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx("input",{type:"radio",name:`provider-active-key-${s.id}`,checked:a.active,onChange:()=>i(d,{active:!0}),"aria-label":n("providers.keys.active"),className:"h-4 w-4 accent-primary"}),n("providers.keys.active")]}),e.jsx(G,{value:a.id,onChange:o=>i(d,{id:o.target.value}),placeholder:n("providers.keys.idPlaceholder"),"aria-label":n("providers.keys.id"),className:"h-8 text-xs","aria-invalid":!!b}),e.jsx(G,{value:a.label,onChange:o=>i(d,{label:o.target.value}),placeholder:n("providers.keys.labelPlaceholder"),"aria-label":n("providers.keys.label"),className:"h-8 text-xs"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx(G,{type:j.has(a._key)?"text":"password",value:a.value,onChange:o=>i(d,{value:o.target.value}),placeholder:n("providers.keys.valuePlaceholder"),"aria-label":n("providers.keys.value"),autoComplete:"off",className:"h-8 font-mono text-xs"}),e.jsx(k,{type:"button",variant:"ghost",size:"sm",className:"h-8 w-8 shrink-0 px-0",onClick:()=>h(a._key),"aria-label":j.has(a._key)?n("providers.keys.hide"):n("providers.keys.reveal"),children:j.has(a._key)?e.jsx(ls,{className:"h-4 w-4","aria-hidden":"true"}):e.jsx(os,{className:"h-4 w-4","aria-hidden":"true"})})]}),e.jsx("span",{className:"text-right",children:e.jsx(k,{type:"button",variant:"ghost",size:"sm",className:"h-auto px-2 text-xs text-destructive",onClick:()=>p(d),children:n("common.delete")})})]}),b?e.jsx("p",{className:"text-xs text-destructive",children:b}):null]},a._key)})}):e.jsx("p",{className:"border border-dashed border-border px-3 py-3 text-xs text-muted-foreground",children:n("providers.keys.empty")})]})}function _s({value:s,onChange:t}){const{t:i}=q();return e.jsxs(Re,{value:s||"none",onValueChange:r=>t(r==="none"?"":r),children:[e.jsx(Ee,{className:"h-8 w-[220px] text-xs","aria-label":i("providers.balance.adapter"),children:e.jsx(Oe,{placeholder:i("providers.balance.adapterNone")})}),e.jsxs(Ae,{children:[e.jsx(ne,{value:"none",children:i("providers.balance.adapterNone")}),Fs.map(r=>e.jsx(ne,{value:r.value,children:r.label},r.value))]})]})}function zs({providerId:s,adapter:t,savedAdapter:i,onAdapterChange:r}){const{t:p}=q(),n=Te(ue.providers.balances(),{url:"/api/providers/balances",method:"GET"},{retry:!1}),j=m.useMemo(()=>{var a;return((a=n.data)==null?void 0:a.balances.find(d=>d.providerId===s))??null},[n.data,s]),x=We({mutationFn:()=>qe.refresh(s),successToast:a=>({title:p("providers.balance.refreshSuccess"),description:a.display??p("providers.balance.displayEmpty")}),errorToast:a=>({title:p("providers.balance.refreshFailure",{message:a.message})}),invalidateKeys:[ue.providers.balances()]}),h=(t||void 0)!==i;return e.jsxs("section",{className:"space-y-3","aria-labelledby":"provider-balance-fields",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{id:"provider-balance-fields",className:"text-sm font-semibold",children:p("providers.balance.title")}),e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:p("providers.balance.hint")})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(_s,{value:t,onChange:r}),e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"bg-card text-xs",onClick:()=>x.mutate(),disabled:!i||h||x.isPending,title:i?h?p("providers.balance.unsavedAdapter"):void 0:p("providers.balance.noAdapter"),children:x.isPending?p("providers.balance.refreshing"):p("providers.balance.refresh")}),h&&i?e.jsx("span",{className:"text-xs text-muted-foreground",children:p("providers.balance.unsavedAdapter")}):null]}),j?e.jsxs("div",{className:"border border-border p-4",children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground",children:p("providers.balance.snapshotLabel")}),e.jsx("p",{className:"mt-2 font-mono text-sm font-semibold tabular-nums",children:j.display??p("providers.balance.displayEmpty")}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:p("providers.balance.fetchedAt",{time:new Date(j.fetchedAt).toLocaleString()})}),e.jsx(Qe,{summary:p("providers.balance.rawTitle"),className:"mt-3 bg-secondary/50",summaryClassName:"px-3 py-2 text-xs font-medium",contentClassName:"px-3 py-3",children:e.jsx("pre",{className:"max-h-64 overflow-auto font-mono text-xs leading-relaxed text-foreground",children:JSON.stringify(j.raw,null,2)})})]}):i?e.jsx("p",{className:"border border-dashed border-border px-3 py-3 text-xs text-muted-foreground",children:p("providers.balance.neverRefreshed")}):null]})}const Hs={anthropic:"Anthropic",openai:"OpenAI Chat","openai-responses":"Responses"};function ve({label:s,children:t}){return e.jsxs("div",{className:"grid gap-1 py-2 sm:grid-cols-[110px_minmax(0,1fr)] sm:gap-3 sm:py-1.5",children:[e.jsx("dt",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:s}),e.jsx("dd",{className:"min-w-0 text-xs text-foreground",children:t})]})}function Be({value:s}){const{t}=q(),{pushToast:i}=Ke(),[r,p]=m.useState(!1),n=async()=>{try{await ks(s),p(!0),window.setTimeout(()=>p(!1),1500)}catch{i({title:t("common.actions.copyFailed"),variant:"error"})}};return e.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[e.jsx("span",{className:"truncate font-mono",children:s}),e.jsx(k,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 shrink-0 px-0 text-muted-foreground hover:text-foreground",onClick:()=>void n(),"aria-label":t("providers.profile.copy"),children:r?e.jsx(ds,{className:"h-3.5 w-3.5 text-foreground","aria-hidden":"true"}):e.jsx(cs,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]})}function $s({provider:s}){var b;const{t}=q(),i=s.type==="aggregate",r=m.useMemo(()=>!s.keys||s.keys.length===0?null:s.keys.find(c=>c.active)??s.keys[0],[s.keys]),p=r?t("providers.profile.namedKeys",{count:((b=s.keys)==null?void 0:b.length)??0,id:r.label||r.id}):s.apiKey?t("providers.profile.singleKey"):t("providers.profile.noKey"),n=m.useMemo(()=>{const c=[];s.nonStreamViaStream&&c.push(t("providers.drawer.fields.nonStreamViaStream")),s.useAbsoluteUrl&&c.push(t("providers.drawer.fields.useAbsoluteUrl")),s.streamUsage&&c.push(t("providers.drawer.fields.streamUsage")),s.rpmLimit&&c.push(`RPM ${s.rpmLimit}`),s.rpmMaxWaitSeconds&&c.push(t("providers.profile.rpmWait",{seconds:s.rpmMaxWaitSeconds}));const o=Object.keys(s.extraHeaders??{}).length;return o>0&&c.push(t("providers.profile.headers",{count:o})),c},[s,t]),j=Te(ue.providers.balances(),{url:"/api/providers/balances",method:"GET"},{retry:!1,enabled:!!s.balanceAdapter}),x=m.useMemo(()=>{var c;return((c=j.data)==null?void 0:c.balances.find(o=>o.providerId===s.id))??null},[j.data,s.id]),h=We({mutationFn:()=>qe.refresh(s.id),successToast:c=>({title:t("providers.balance.refreshSuccess"),description:c.display??t("providers.balance.displayEmpty")}),errorToast:c=>({title:t("providers.balance.refreshFailure",{message:c.message})}),invalidateKeys:[ue.providers.balances()]}),a=s.models??[],d=s.defaultModel;return e.jsxs("div",{className:"space-y-5","data-testid":"provider-profile-view",children:[e.jsxs("section",{"aria-labelledby":"provider-profile-connection",className:"space-y-2",children:[e.jsx("h3",{id:"provider-profile-connection",className:"text-sm font-semibold",children:t("providers.profile.connection")}),i?e.jsx("p",{className:"border border-border bg-secondary/40 px-3 py-2.5 text-xs leading-relaxed text-muted-foreground",children:t("providers.aggregate.drawer.explainerBody")}):e.jsxs("dl",{className:"divide-y divide-border border border-border px-3 py-1.5",children:[e.jsx(ve,{label:t("providers.profile.primaryEndpoint"),children:s.baseUrl?e.jsx(Be,{value:s.baseUrl}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),(s.endpoints??[]).map(c=>e.jsx(ve,{label:t("providers.profile.protocolEndpoint"),children:e.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[e.jsx(Y,{variant:"outline",className:"shrink-0 text-[10px]",children:Hs[c.protocol]}),e.jsx(Be,{value:c.baseUrl})]})},c.id)),e.jsx(ve,{label:t("providers.drawer.sections.auth"),children:e.jsxs("span",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{children:js(s.type,s.authMode??"apiKey",t)}),e.jsx("span",{className:"text-muted-foreground",children:"·"}),e.jsx("span",{className:te(r||s.apiKey?"text-foreground":"text-warning"),children:p})]})}),s.balanceAdapter?e.jsx(ve,{label:t("providers.balance.title"),children:e.jsxs("span",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{children:s.balanceAdapter}),x!=null&&x.display?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"·"}),e.jsx("span",{className:"font-medium",children:x.display})]}):null,e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"h-6 bg-card px-2 text-[11px]",onClick:()=>h.mutate(),disabled:h.isPending,children:h.isPending?t("common.loading"):t("providers.balance.refresh")})]})}):null]}),n.length>0?e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:t("providers.profile.advanced")}),n.map(c=>e.jsx(Y,{variant:"secondary",className:"text-[10px] font-normal",children:c},c))]}):null]}),e.jsxs("section",{"aria-labelledby":"provider-profile-models",className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("h3",{id:"provider-profile-models",className:"text-sm font-semibold",children:a.length>0?`${t("providers.drawer.fields.models")} (${a.length})`:t("providers.drawer.fields.models")}),i?null:e.jsx("span",{className:"text-[11px] text-muted-foreground",children:t("providers.profile.defaultIs",{model:d??t("providers.card.noDefault")})})]}),a.length===0?e.jsx("p",{className:"border border-dashed border-border px-3 py-4 text-xs text-muted-foreground",children:t("providers.profile.noModelsHint")}):i?e.jsx("ul",{className:"divide-y divide-border border border-border",children:a.map(c=>e.jsxs("li",{className:"px-3 py-2",children:[e.jsx("p",{className:"font-mono text-xs",children:c.id}),c.members&&c.members.length>0?e.jsx("p",{className:"mt-0.5 truncate font-mono text-[11px] text-muted-foreground",title:c.members.map(o=>o.target).join(" → "),children:c.members.map(o=>o.target).join(" → ")}):null]},c.id))}):e.jsx("div",{className:"grid gap-1.5 sm:grid-cols-2 lg:grid-cols-3",children:a.map(c=>{const o=c.id===d;return e.jsxs("div",{className:te("flex min-w-0 items-center gap-2 border px-2.5 py-1.5",o?"border-foreground/60 bg-secondary/60":"border-border bg-secondary/30"),title:c.label?`${c.label} (${c.id})`:c.id,children:[e.jsx("span",{className:te("h-1.5 w-1.5 shrink-0 rounded-full",o?"bg-foreground":"bg-border"),"aria-hidden":"true"}),e.jsx("span",{className:"truncate font-mono text-xs",children:c.id}),o?e.jsx("span",{className:"ml-auto shrink-0 text-[10px] font-medium text-foreground",children:t("providers.profile.defaultTag")}):null]},c.id)})})]}),!i&&s.type&&s.type!=="openai"&&s.type!=="anthropic"?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:t("providers.profile.typeFootnote",{type:Ie(s.type,t)})}):null]})}function Bs({provider:s,providers:t,onSubmit:i}){const r=ys({mode:"edit",provider:s,existingProviderIds:[],providers:t}),[p,n]=m.useState(!1),[j,x]=m.useState(null),h=m.useRef(null);h.current===null&&(h.current=JSON.stringify(r.form));const a=JSON.stringify(r.form)!==h.current,d=m.useRef(s);return d.current!==s&&(d.current=s,a||(r.resetForm(),h.current=null)),{providerForm:r,dirty:a,saving:p,saveError:j,save:async()=>{if(!r.validate())return!1;n(!0),x(null);try{const o=r.serialize();return await i(o),h.current=JSON.stringify(r.form),!0}catch(o){return x(ce(o).message),!1}finally{n(!1)}},discard:()=>{r.resetForm(),h.current=null,x(null)}}}const Ks={anthropic:"Anthropic",openai:"OpenAI Chat","openai-responses":"Responses"};function Vs({provider:s,allProviders:t,testResult:i,testing:r,onTest:p,onRequestDelete:n,onSubmit:j,onDirtyChange:x,startInEdit:h=!1}){const{t:a}=q(),[d,b]=m.useState(!1),[c,o]=m.useState(h?"edit":"view"),[E,O]=m.useState(!1),{providerForm:g,dirty:v,saving:M,saveError:A,save:$,discard:L}=Bs({provider:s,providers:t,onSubmit:j}),{form:T,errors:l,advancedOpen:w,providerIdRef:F}=g,P=T.type==="aggregate";m.useEffect(()=>{h&&o("edit")},[h]);const D=async()=>{await $()&&o("view")},y=()=>{L(),o("view")},U=()=>{if(v){O(!0);return}o("view")};m.useEffect(()=>(x==null||x(v),()=>x==null?void 0:x(!1)),[v,x]);const B=m.useMemo(()=>{var V;const K=[];for(const Q of t){if(Q.type==="aggregate")continue;const f=Q.label&&Q.label!==Q.id?`${Q.label} (${Q.id})`:Q.id,C=(V=Q.models)!=null&&V.length?Q.models:Q.defaultModel?[{id:Q.defaultModel}]:[];for(const S of C)K.push({value:`${Q.id}:${S.id}`,label:`${f} · ${S.label??S.id}`,providerId:Q.id,providerLabel:f,modelId:S.id,modelLabel:S.label??S.id,kind:"model"})}return K},[t]),J={form:T,errors:l,isCreate:!1,advancedOpen:w,onAdvancedOpenChange:g.setAdvancedOpen,idInputRef:F,onProviderIdChange:g.handleProviderIdChange,onFieldChange:g.handleFieldChange,onTypeChange:g.handleTypeChange,onAuthModeChange:g.handleAuthModeChange,onNonStreamViaStreamChange:g.handleProviderNonStreamViaStreamChange,onUseAbsoluteUrlChange:g.handleUseAbsoluteUrlChange,onStreamUsageChange:g.handleStreamUsageChange,onAddHeader:g.handleAddHeader,onRemoveHeader:g.handleRemoveHeader,onHeaderChange:g.handleHeaderChange,onModelIdChange:g.handleModelIdChange,onModelChange:g.handleModelChange,onAddModel:g.handleAddModel,onRemoveModel:g.handleRemoveModel,onModelNonStreamViaStreamChange:g.handleModelNonStreamViaStreamChange,onSetDefaultModel:g.handleSetDefaultModel,onEndpointChange:g.handleEndpointChange,onAddEndpoint:g.handleAddEndpoint,onRemoveEndpoint:g.handleRemoveEndpoint,memberOptions:B,onAddMember:g.handleAddMember,onRemoveMember:g.handleRemoveMember,onMemberTargetChange:g.handleMemberTargetChange,onReorderMembers:g.handleReorderMembers,onModelFailoverChange:g.handleModelFailoverChange,testVerification:P?void 0:{available:!0,testing:r,result:i,onTest:()=>p(g.serialize())},probeModels:P?void 0:{available:T.baseUrl.trim().length>0,onProbe:()=>b(!0)}},u=c==="edit",I=u?T.type:s.type,_=u?T.endpoints:s.endpoints??[],W=u?T.models.length:(s.models??[]).length;return e.jsxs(be,{className:"overflow-hidden","data-testid":"provider-detail-panel",children:[e.jsxs("header",{className:"flex flex-wrap items-start justify-between gap-3 border-b border-border bg-secondary/50 px-5 py-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h2",{className:"truncate text-base font-semibold tracking-[-0.02em]",children:s.label||s.id}),i?i.ok?e.jsx(Y,{variant:"success",className:"shrink-0 text-[10px]",children:i.durationMs!==void 0?`${a("providers.masterDetail.testOkShort")} · ${i.durationMs}ms`:a("providers.masterDetail.testOkShort")}):e.jsx(Y,{variant:"destructive",className:"shrink-0 text-[10px]",title:i.message??void 0,children:a("providers.masterDetail.testFailedShort")}):null,u?e.jsx(Y,{variant:"outline",className:"shrink-0 text-[10px] text-muted-foreground",children:a("providers.profile.editingTag")}):null]}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5",children:[e.jsx(Y,{variant:"secondary",className:"text-[10px]",children:Ie(I,a)}),I==="aggregate"?null:_.map(K=>e.jsxs(Y,{variant:"outline",className:"text-[10px]",children:["+ ",Ks[K.protocol]]},K.id)),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:a("providers.masterDetail.modelsMeta",{count:W})})]}),e.jsx("p",{className:"mt-0.5 font-mono text-xs text-muted-foreground",children:s.id})]}),e.jsxs("div",{className:"flex shrink-0 gap-2",children:[P?null:e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"bg-card text-xs",onClick:()=>p(g.serialize()),disabled:r,children:a(r?"common.actions.testingConnection":"providers.actions.test")}),u?e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"bg-card text-xs",onClick:U,disabled:M,children:a("providers.profile.cancelEdit")}):e.jsx(k,{type:"button",variant:"outline",size:"sm","data-testid":"provider-edit",onClick:()=>o("edit"),children:a("providers.profile.edit")}),e.jsx(k,{type:"button",variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive",onClick:()=>n(s),disabled:M,children:a("providers.actions.delete")})]})]}),e.jsx(je,{className:"p-5",children:u?e.jsxs("div",{className:"space-y-5",children:[e.jsx(Ns,{...J}),P?null:e.jsxs(e.Fragment,{children:[e.jsx(Us,{form:T,errors:l,onKeyChange:g.handleKeyChange,onAddKey:g.handleAddKey,onRemoveKey:g.handleRemoveKey}),e.jsx(zs,{providerId:s.id,adapter:T.balanceAdapter,savedAdapter:s.balanceAdapter,onAdapterChange:g.handleBalanceAdapterChange})]}),P?e.jsx(Os,{...J}):e.jsx(ws,{...J})]}):e.jsx($s,{provider:s})}),u&&(v||A)?e.jsxs("footer",{className:"sticky bottom-0 flex flex-wrap items-center justify-between gap-3 border-t border-border bg-card px-5 py-3",children:[e.jsx("div",{className:"min-w-0 text-xs",children:e.jsx("span",{className:te("font-medium",A?"text-destructive":"text-foreground"),"aria-live":"polite",children:A?a("providers.drawer.toast.saveFailure",{message:A}):a("providers.masterDetail.dirtyHint")})}),e.jsxs("div",{className:"flex shrink-0 gap-2",children:[e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"bg-card text-xs",onClick:y,disabled:M,children:a("providers.masterDetail.discard")}),e.jsx(k,{type:"button",variant:"outline",size:"sm","data-testid":"provider-save",onClick:()=>void D(),disabled:M,children:a(M?"common.actions.saving":"providers.masterDetail.save")})]})]}):null,e.jsx(de,{open:E,onOpenChange:O,title:a("providers.masterDetail.unsavedTitle"),description:a("providers.masterDetail.unsavedBody"),confirmLabel:a("providers.masterDetail.unsavedConfirm"),cancelLabel:a("common.actions.cancel"),onConfirm:()=>{L(),o("view"),O(!1)}}),e.jsx(Ls,{open:d,providerId:s.id,providerName:s.label||s.id,existingModelIds:T.models.map(K=>K.id.trim()).filter(Boolean),draft:g.serialize(),onImport:g.handleImportModels,onClose:()=>b(!1)})]})}function Qs({providers:s,configPending:t,configError:i,onRetryConfig:r,selectedProviderId:p,onSelectProvider:n,onTest:j,onRequestDelete:x,onDirtyChange:h,autoEditProviderId:a}){const{t:d}=q(),{filteredProviders:b,providerSearch:c,setProviderSearch:o,providerTypeFilter:E,setProviderTypeFilter:O}=s,g=s.providers.length,[v,M]=m.useState(!1),[A,$]=m.useState(null),L=m.useCallback(y=>{M(y),h==null||h(y)},[h]),[T,l]=m.useState(!1),w=m.useRef(!0);m.useEffect(()=>{if(w.current){w.current=!1;return}l(!!p)},[p]),m.useEffect(()=>{if(!v)return;const y=U=>{U.preventDefault(),U.returnValue=""};return window.addEventListener("beforeunload",y),()=>window.removeEventListener("beforeunload",y)},[v]);const F=y=>{if(v&&y!==p){$(y);return}n(y),l(!0)},P=s.providers.find(y=>y.id===p)??null,D=y=>{var J,u;const U=[],B=((J=y.models)==null?void 0:J.length)??0;if(U.push(d("providers.masterDetail.modelsMeta",{count:B})),y.type!=="aggregate"){const I=((u=y.keys)==null?void 0:u.length)??0;U.push(I>0?d("providers.masterDetail.keysMeta",{count:I}):d("providers.masterDetail.noKeysMeta"))}return U.join(" · ")};return e.jsx("div",{className:"grid gap-4 lg:grid-cols-[300px_minmax(0,1fr)]",children:i?e.jsx(fe,{className:"lg:col-span-2",tone:"danger",title:d("common.status.error"),description:i,action:r?e.jsx(k,{variant:"outline",onClick:r,children:d("common.actions.refresh")}):void 0}):e.jsxs(e.Fragment,{children:[e.jsx(be,{className:te("h-fit overflow-hidden lg:sticky lg:top-4",T&&P?"hidden lg:block":""),children:e.jsxs(je,{className:"p-0",children:[e.jsxs("div",{className:"space-y-2 border-b border-border bg-secondary/50 px-3 py-3",children:[e.jsx(G,{value:c,onChange:y=>o(y.target.value),placeholder:d("providers.filters.searchPlaceholder"),className:"h-9"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Re,{value:E,onValueChange:O,children:[e.jsx(Ee,{className:"h-9 flex-1 text-xs","aria-label":d("providers.table.type"),children:e.jsx(Oe,{})}),e.jsxs(Ae,{children:[e.jsx(ne,{value:"all",children:d("providers.filters.typeAll")}),Cs.map(y=>e.jsx(ne,{value:y.value??"custom",children:y.label},y.value??"custom"))]})]}),e.jsx(Y,{variant:"secondary",className:"shrink-0 px-2.5 py-1 text-[11px]",children:d("providers.groupCount",{count:b.length})})]})]}),t?e.jsx("div",{className:"flex min-h-[160px] items-center justify-center text-sm text-muted-foreground",children:d("common.loading")}):g===0?e.jsx("div",{className:"p-4",children:e.jsx(fe,{compact:!0,title:d("providers.emptyState"),description:e.jsxs(e.Fragment,{children:[e.jsx("p",{children:d("providers.emptyStateSub")}),e.jsx("p",{className:"mt-1",children:d("workbench.list.emptyHint")})]})})}):b.length===0?e.jsx("div",{className:"p-4",children:e.jsx(fe,{compact:!0,title:d("providers.emptyFiltered")})}):e.jsx("ul",{className:"max-h-[60vh] overflow-y-auto p-2 lg:max-h-[calc(100vh-320px)]",children:b.map(y=>{const U=y.id===p,B=s.testResults[y.id]??null,J=B!==null&&!B.ok,u=J?B.message?`${d("providers.masterDetail.testFailedShort")}: ${B.message}`:d("providers.masterDetail.testFailedShort"):void 0;return e.jsx("li",{children:e.jsxs("button",{type:"button","data-testid":"provider-rail-row",onClick:()=>F(y.id),"aria-current":U?"true":void 0,className:te("motion-surface w-full border border-transparent px-3 py-2.5 text-left",U?"border-foreground bg-secondary":"hover:bg-muted/40"),children:[e.jsxs("span",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-1.5 text-sm font-medium",children:[J?e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-destructive",title:u,"aria-label":d("providers.masterDetail.testFailedShort")}):null,e.jsx("span",{className:"truncate",children:y.label||y.id})]}),e.jsx(Y,{variant:U?"default":"secondary",className:"shrink-0 text-[10px]",children:Ie(y.type,d)})]}),e.jsxs("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",children:[y.id," · ",D(y)]})]})},y.id)})})]})}),e.jsxs("div",{className:te("min-w-0",T?"block":"hidden lg:block"),children:[P?e.jsxs(k,{type:"button",variant:"ghost",size:"sm",className:"mb-2 lg:hidden",onClick:()=>l(!1),children:[e.jsx(us,{className:"mr-1.5 h-4 w-4","aria-hidden":"true"}),d("providers.masterDetail.backToList")]}):null,t?e.jsx(be,{children:e.jsx(je,{className:"flex min-h-[240px] items-center justify-center text-sm text-muted-foreground",children:d("common.loading")})}):P?e.jsx(Vs,{provider:P,allProviders:s.providers,testResult:s.testResults[P.id]??null,testing:s.testingProviderId===P.id,onTest:j,onRequestDelete:x,onSubmit:s.handleUpdateProvider,onDirtyChange:L,startInEdit:a===P.id},P.id):e.jsx(be,{children:e.jsx(je,{className:"p-0",children:e.jsx(fe,{title:d("providers.masterDetail.emptyDetailTitle"),description:d("providers.masterDetail.emptyDetailHint")})})})]}),e.jsx(de,{open:!!A,onOpenChange:y=>{y||$(null)},title:d("providers.masterDetail.unsavedTitle"),description:d("providers.masterDetail.unsavedBody"),confirmLabel:d("providers.masterDetail.unsavedConfirm"),cancelLabel:d("common.actions.cancel"),onConfirm:()=>{A&&(n(A),l(!0)),$(null)}})]})})}function Ws({open:s,provider:t,options:i,usePreset:r,preservedExtras:p,onPresetChange:n,onConfirm:j,onClose:x}){const{t:h}=q();return t?e.jsx(ye,{open:s,onOpenChange:a=>!a&&x(),children:e.jsxs(Ne,{className:"max-w-2xl",onInteractOutside:a=>a.preventDefault(),children:[e.jsxs(we,{children:[e.jsx(Ce,{children:h("providers.testDialog.title")}),e.jsx(Se,{children:h("providers.testDialog.subtitle",{name:t.label||t.id})})]}),e.jsxs(ke,{className:"space-y-4",children:[e.jsx("div",{className:"rounded-xl bg-secondary p-4 text-sm text-muted-foreground",children:h("providers.testDialog.description")}),e.jsxs("div",{className:"space-y-4 rounded-xl bg-secondary/50 p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"provider-test-preset",children:h("providers.testDialog.presetLabel")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:h("providers.testDialog.presetDescription")})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(Ms,{id:"provider-test-preset",checked:r,onCheckedChange:n})})]}),r?e.jsx("div",{className:"space-y-2",children:e.jsxs("details",{className:"border border-border bg-card p-2 text-xs",children:[e.jsx("summary",{className:"cursor-pointer text-foreground underline decoration-muted-foreground/40 underline-offset-2 hover:decoration-foreground",children:h("providers.testDialog.presetPreviewSummary")}),e.jsx("div",{className:"mt-2 space-y-1",children:i.map(a=>e.jsxs("code",{className:"block rounded-lg bg-secondary px-2 py-1 text-xs",children:[a.key,": ",a.value]},a.key))})]})}):e.jsx("p",{className:"text-xs text-muted-foreground",children:h("providers.testDialog.presetDescription")})]}),Object.keys(p).length>0&&e.jsxs("div",{className:"space-y-2 rounded-xl bg-secondary/50 p-4 text-xs",children:[e.jsx("p",{className:"font-medium",children:h("providers.testDialog.preservedInfo")}),Object.entries(p).map(([a,d])=>e.jsxs("code",{className:"block border border-border bg-card px-2 py-1",children:[a,": ",d]},a))]})]}),e.jsxs(Me,{children:[e.jsx(k,{variant:"outline",onClick:x,children:h("providers.testDialog.cancel")}),e.jsx(k,{onClick:()=>void j(),children:h("providers.testDialog.primary")})]})]})}):null}function ht(){var T;const{t:s}=q(),t=gs(),i=Ps(t),[r,p]=m.useState(null),[n,j]=m.useState(!1),[x,h]=m.useState(!1),[a,d]=m.useState(!1),b=m.useRef(!1),c=m.useCallback(l=>{b.current=l,d(l)},[]),[o,E]=m.useState(null),O=Ds(({currentLocation:l,nextLocation:w})=>a&&l.pathname!==w.pathname),[g,v]=m.useState(()=>typeof window>"u"?null:window.localStorage.getItem(De.workbench.providerSelection)),[M,A]=m.useState(null);m.useEffect(()=>{M&&g!==M&&A(null)},[M,g]),m.useEffect(()=>{if(!g){window.localStorage.removeItem(De.workbench.providerSelection);return}window.localStorage.setItem(De.workbench.providerSelection,g)},[g]),m.useEffect(()=>{g&&(t.configQuery.isPending||t.configQuery.isFetching||i.providers.some(l=>l.id===g)||v(null))},[g,i.providers,t.configQuery.isPending,t.configQuery.isFetching]);const $=async()=>{if(r){j(!0);try{r.kind==="provider"&&await i.handleDeleteProvider(r.provider),p(null)}finally{j(!1)}}},L=(r==null?void 0:r.kind)==="provider"?hs(t.config,t.customEndpoints,r.provider.id):{routes:0,defaults:0,aggregateMembers:0};return e.jsxs("div",{className:"flex flex-col gap-6",children:[e.jsx(ms,{status:e.jsx(Y,{variant:"secondary",children:s("providers.groupCount",{count:i.providerCount})}),actions:e.jsx(k,{size:"sm",onClick:()=>h(!0),children:s("providers.actions.add")})}),e.jsx(Qs,{providers:i,configPending:t.configQuery.isPending||!t.config&&t.configQuery.isFetching,configError:!t.config&&t.configQuery.isError?((T=t.configQuery.error)==null?void 0:T.message)??s("common.status.error"):null,onRetryConfig:()=>void t.configQuery.refetch(),selectedProviderId:g,onSelectProvider:v,onTest:l=>i.initiateTestConnection(l),onRequestDelete:l=>p({kind:"provider",provider:l}),onDirtyChange:c,autoEditProviderId:M}),e.jsx(Rs,{open:x,onOpenChange:h,existingProviderIds:i.providers.map(l=>l.id),onSubmit:i.handleCreateProvider,onCreated:l=>{t.configQuery.refetch().then(()=>{if(b.current){E(l);return}v(l),A(l)})}}),e.jsx(Ws,{open:i.testDialogOpen,provider:i.testDialogProvider,options:i.anthropicTestHeaderOptions,preservedExtras:i.testDialogPreservedExtras,usePreset:i.testDialogUsePreset,onPresetChange:i.setTestDialogUsePreset,onConfirm:i.confirmTestDialog,onClose:i.closeTestDialog}),e.jsx(Es,{open:!!i.noModelDialogProvider,provider:i.noModelDialogProvider,onClose:()=>i.setNoModelDialogProvider(null),onEdit:l=>{i.setNoModelDialogProvider(null),v(l.id),A(l.id)}}),e.jsx(de,{open:!!r,onOpenChange:l=>{!l&&!n&&p(null)},title:(r==null?void 0:r.kind)==="provider"?s("providers.actions.delete"):"",description:(r==null?void 0:r.kind)==="provider"?s("providers.confirm.delete",{name:r.provider.label||r.provider.id}):"",confirmLabel:s(n?"common.actions.loading":"common.delete"),cancelLabel:s("common.actions.cancel"),loading:n,onConfirm:$,children:(r==null?void 0:r.kind)==="provider"?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"rounded-xl border border-destructive/20 bg-destructive/5 px-3 py-2 font-mono text-xs text-foreground",children:r.provider.label||r.provider.id}),L.routes>0?e.jsx("p",{className:"text-xs text-muted-foreground",children:s("providers.confirm.deleteImpact",{count:L.routes})}):null,L.defaults>0?e.jsx("p",{className:"text-xs text-muted-foreground",children:s("providers.confirm.deleteDefaultsImpact",{count:L.defaults})}):null,L.aggregateMembers>0?e.jsx("p",{className:"text-xs text-muted-foreground",children:s("providers.confirm.deleteAggregateImpact",{count:L.aggregateMembers})}):null]}):null}),e.jsx(de,{open:O.state==="blocked",onOpenChange:l=>{!l&&O.state==="blocked"&&O.reset()},title:s("providers.masterDetail.unsavedTitle"),description:s("providers.masterDetail.unsavedBody"),confirmLabel:s("providers.masterDetail.unsavedConfirm"),cancelLabel:s("common.actions.cancel"),onConfirm:()=>{O.state==="blocked"&&O.proceed()}}),e.jsx(de,{open:!!o,onOpenChange:l=>{l||E(null)},title:s("providers.masterDetail.unsavedTitle"),description:s("providers.masterDetail.unsavedBody"),confirmLabel:s("providers.masterDetail.unsavedConfirm"),cancelLabel:s("common.actions.cancel"),onConfirm:()=>{o&&v(o),E(null)}})]})}export{ht as default};
|
|
1
|
+
import{r as m,j as e,aL as Ge,aM as Ue,aN as Je,aO as Xe,aP as Ye,aQ as Ze,aR as es,aS as ss,aT as ts,aU as rs,aV as as,aG as ns,aW as is,aX as ls,aY as os,a4 as ds,ay as cs,aZ as us}from"./vendor-C-lQMZp3.js";import{C as de}from"./ConfirmDialog-_CIYYtzo.js";import{P as ms}from"./PageToolbar-GyUQBhmq.js";import{B as Y}from"./badge-CWbm9P64.js";import{t as ce,b as Te,q as ue,B as k,u as Ke,e as _e,d as ze,C as be,c as je,s as De}from"./app-DZpd2fu9.js";import{r as ps,m as Ve,a as xs,u as gs,s as hs}from"./modelManagement-Dc7L1tJw.js";import{g as Pe}from"./gateway-DxaHzVOF.js";import{L as ee,I as G}from"./label-09axTkPo.js";import{D as ye,A as Ne,a as we,b as Ce,c as Se,d as ke,e as Me}from"./DialogShell-D1T4HXtd.js";import{S as Re,a as Ee,b as Oe,c as Ae,e as He,f as $e,d as ne,D as Qe}from"./disclosure-W_XtxMJz.js";import{P as fs,a as vs,d as bs,b as js,p as Le,u as ys,B as Ns,M as ws,c as Cs}from"./useProviderForm-B_wmywxX.js";import{u as q}from"./i18n-ClvfZhYc.js";import{a as fe}from"./PageState-Bbhr4fy6.js";import{c as te}from"./global-BCYo_xAt.js";import{T as Ss}from"./TargetCombobox-CSnHZqDY.js";import{u as We}from"./useAppMutation-CsoNTPQ7.js";import{c as ks}from"./clipboard-DqvcglYs.js";import{S as Ms}from"./switch-C58zWdHT.js";import{g as Ds}from"./router-Bkbjq53m.js";import"./query-1Ng1fzmE.js";import"./radix-DONH6gHT.js";import"./popover-CX5HRHKk.js";function Ps(s){const{t,pushToast:i,config:r,setConfig:p,configQuery:n,customEndpoints:j,ensureConfig:x}=s,[h,a]=m.useState(""),[d,b]=m.useState("all"),[c,o]=m.useState(null),[E,O]=m.useState({}),[g,v]=m.useState(!1),[M,A]=m.useState(null),[$,I]=m.useState(!0),[T,l]=m.useState({}),[w,F]=m.useState(null),P=(r==null?void 0:r.providers)??[],D=P.length,y=m.useMemo(()=>P.filter(f=>{var z;if(!(d==="all"||(f.type??"custom")===d))return!1;const S=h.trim().toLowerCase();return S?[f.id,f.label??"",f.baseUrl??"",f.defaultModel??"",...((z=f.models)==null?void 0:z.map(re=>re.id))??[]].join(" ").toLowerCase().includes(S):!0}),[h,d,P]),U=m.useMemo(()=>{const f=new Map;for(const C of P){if(!C.defaultModel||!C.models)continue;const S=C.models.find(N=>N.id===C.defaultModel);S&&f.set(C.id,ps(S))}return f},[P]),B=m.useMemo(()=>[{key:"anthropic-beta",value:"claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14",label:t("providers.testDialog.options.beta.label"),description:t("providers.testDialog.options.beta.description")}],[t]),J=async f=>{if(!r)throw new Error(t("settings.toast.missingConfig"));const C={...r,providers:[...P,f]};await Pe.saveConfig(C),p(C),n.refetch(),i({title:t("providers.toast.createSuccess",{name:f.label||f.id}),variant:"success"})},u=async f=>{if(!r)throw new Error(t("settings.toast.missingConfig"));const C={...r,providers:P.map(S=>S.id===f.id?f:S)};await Pe.saveConfig(C),p(C),n.refetch(),i({title:t("providers.toast.updateSuccess",{name:f.label||f.id}),variant:"success"})},L=(f,C)=>{O(S=>({...S,[f]:C}))},_=async(f,C)=>{o(f.id);try{const S={provider:f};C!=null&&C.headers&&Object.keys(C.headers).length>0&&(S.headers=C.headers),C!=null&&C.query&&C.query.trim().length>0&&(S.query=C.query.trim());const N=await Ve.testProvider(f.id,S);if(N.ok){L(f.id,{ok:!0,status:N.status,statusText:N.statusText,durationMs:N.durationMs,testedAt:Date.now()}),i({title:t("providers.toast.testSuccess"),description:t("providers.toast.testSuccessDesc",{status:N.status,duration:N.durationMs?`${N.durationMs} ms`:"—"}),variant:"success"});return}L(f.id,{ok:!1,status:N.status,statusText:N.statusText,durationMs:N.durationMs,message:`${N.status} ${N.statusText}`,testedAt:Date.now()}),i({title:t("providers.toast.testFailure",{message:`${N.status} ${N.statusText}`}),variant:"error"})}catch(S){const N=ce(S),z=N.status?`${N.status} ${N.message}`:N.message;L(f.id,{ok:!1,status:N.status,message:z,testedAt:Date.now()}),i({title:t("providers.toast.testFailure",{message:z}),variant:"error"})}finally{o(null)}},W=f=>{var me,pe;if(!(!!((me=f.defaultModel)!=null&&me.trim())||!!((pe=f.models)!=null&&pe.some(X=>X.id.trim().length>0)))){F(f);return}if(f.type!=="anthropic"){_(f);return}const S=f.extraHeaders??{},N=new Map(B.map(X=>[X.key.toLowerCase(),X])),z={};let re=!0;for(const X of B){const ae=Object.entries(S).find(([ge])=>ge.toLowerCase()===X.key.toLowerCase());if(!ae)continue;const[xe,ie]=ae;String(ie??"")!==X.value&&(re=!1,z[xe]=String(ie??""))}for(const[X,ae]of Object.entries(S))N.has(X.toLowerCase())||(z[X]=String(ae??""));l(z),I(re),A(f),v(!0)},K=()=>{v(!1),A(null),I(!0),l({})};return{providers:P,providerCount:D,filteredProviders:y,providerSearch:h,setProviderSearch:a,providerTypeFilter:d,setProviderTypeFilter:b,defaultLabels:U,testingProviderId:c,testResults:E,testDialogOpen:g,testDialogProvider:M,testDialogUsePreset:$,setTestDialogUsePreset:I,testDialogPreservedExtras:T,noModelDialogProvider:w,setNoModelDialogProvider:F,anthropicTestHeaderOptions:B,handleCreateProvider:J,handleUpdateProvider:u,handleDeleteProvider:async f=>{var ae,xe,ie,ge,Ie,Fe;if(!x())return;const C=P.filter(R=>R.id!==f.id).map(R=>{if(R.type!=="aggregate"||!R.models)return R;const H=R.models.map(Z=>({...Z,members:(Z.members??[]).filter(he=>he.target.split(":")[0]!==f.id)})).filter(Z=>(Z.members??[]).length>0),se=H.some(Z=>Z.id===R.defaultModel)?R.defaultModel:void 0;return{...R,models:H,defaultModel:se}}),S=R=>{const H={};if(!R)return H;for(const[se,Z]of Object.entries(R)){if(!Z)continue;const[he]=Z.split(":");he&&he===f.id||Z===f.id||(H[se]=Z)}return H},N=R=>{if(!R)return R;const H=se=>se&&xs(se,f.id)?null:se;return{...R,completion:H(R.completion),reasoning:H(R.reasoning),background:H(R.background)}},z=(r==null?void 0:r.endpointRouting)??{},re=S(((ae=z.anthropic)==null?void 0:ae.modelRoutes)??(r==null?void 0:r.modelRoutes)??{}),me=S(((xe=z.openai)==null?void 0:xe.modelRoutes)??{}),pe=((r==null?void 0:r.customEndpoints)??j).map(R=>{const H=R.routing;if(!H)return R;const se=H.defaults?N(H.defaults):H.modelRoutes?N(r.defaults):void 0;return{...R,routing:{...H,...se?{defaults:se}:{},...H.modelRoutes?{modelRoutes:S(H.modelRoutes)}:{}}}}),X={...r,providers:C,defaults:N(r.defaults)??r.defaults,modelRoutes:re,customEndpoints:pe,endpointRouting:{anthropic:{defaults:N(((ie=z.anthropic)==null?void 0:ie.defaults)??r.defaults)??r.defaults,modelRoutes:re,compatibility:(ge=z.anthropic)==null?void 0:ge.compatibility},openai:{defaults:N(((Ie=z.openai)==null?void 0:Ie.defaults)??r.defaults)??r.defaults,modelRoutes:me,compatibility:(Fe=z.openai)==null?void 0:Fe.compatibility}}};try{await Pe.saveConfig(X),p(X),i({title:t("providers.toast.deleteSuccess",{name:f.label||f.id}),variant:"success"}),n.refetch()}catch(R){i({title:t("providers.toast.deleteFailure",{message:ce(R).message}),variant:"error"})}},handleTestConnection:_,initiateTestConnection:W,closeTestDialog:K,confirmTestDialog:async()=>{if(!M)return;const f={};if($)for(const N of B)f[N.key]=N.value;const C=new Map(B.map(N=>[N.key.toLowerCase(),N]));for(const[N,z]of Object.entries(T))C.get(N.toLowerCase())&&$||(f[N]=z);const S=M;K(),await _(S,{headers:Object.keys(f).length>0?f:void 0})}}}const le="preset:",oe="manual:",Ts=[{value:"openai",labelKey:"providers.presets.manualOpenAiCompatible"},{value:"anthropic",labelKey:"providers.presets.manualAnthropicCompatible"},{value:"aggregate",labelKey:"providers.aggregate.typeLabel"}];function Rs({open:s,onOpenChange:t,existingProviderIds:i,onSubmit:r,onCreated:p}){const{t:n,i18n:j}=q(),[x,h]=m.useState(""),[a,d]=m.useState(""),[b,c]=m.useState(""),[o,E]=m.useState(""),[O,g]=m.useState({}),[v,M]=m.useState(null),[A,$]=m.useState(!1),I=Te(ue.providers.presets(),{url:"/api/provider-presets",method:"GET"},{retry:!1,staleTime:1/0,enabled:s}),T=m.useMemo(()=>{var u;return((u=I.data)==null?void 0:u.presets)??[]},[I.data]),l=()=>{h(""),d(""),c(""),E(""),g({}),M(null),$(!1)},w=u=>{u||(t(!1),l())},F=u=>{var L;if(h(u),M(null),u.startsWith(le)){const _=T.find(W=>W.id===u.slice(le.length));if(_){E(_.baseUrl),g(Object.fromEntries(_.endpoints.map(W=>[W.id,W.baseUrl])));return}}if(u.startsWith(oe)){const _=u.slice(oe.length);E(((L=vs[_??"custom"])==null?void 0:L.baseUrl)??"")}g({})},P=u=>{d(u),(!b.trim()||b===a)&&c(u)},D=x.startsWith(le)?T.find(u=>u.id===x.slice(le.length)):void 0,y=x.startsWith(oe)?x.slice(oe.length):void 0,U=y==="aggregate",B=u=>{var L;return(L=j.resolvedLanguage)!=null&&L.startsWith("en")?n(`providers.presets.catalog.${u.id}`,{defaultValue:u.description}):u.description},J=async()=>{const u=a.trim(),L=o.trim();if(!u){M({field:"id",message:n("providers.drawer.errors.idRequired")});return}if(i.includes(u)){M({field:"id",message:n("providers.drawer.errors.idDuplicate")});return}if(!U){if(!L){M({field:"baseUrl",message:n("providers.drawer.errors.baseUrlInvalid")});return}try{new URL(L)}catch{M({field:"baseUrl",message:n("providers.drawer.errors.baseUrlInvalid")});return}for(const V of(D==null?void 0:D.endpoints)??[]){const Q=(O[V.id]??V.baseUrl).trim();try{new URL(Q)}catch{M({field:"endpointUrl",endpointId:V.id,message:n("providers.endpoints.errors.baseUrlInvalid")});return}}}const _=D?D.type:y??"custom",W=bs(_),K={id:u,label:b.trim()||u,type:_,baseUrl:U?void 0:L,authMode:W==="apiKey"&&_!=="anthropic"?void 0:W,...D!=null&&D.balanceAdapter?{balanceAdapter:D.balanceAdapter}:null,...D&&D.endpoints.length>0?{endpoints:D.endpoints.map(V=>({id:V.id,protocol:V.protocol,baseUrl:(O[V.id]??V.baseUrl).trim()}))}:null};D&&D.defaultModels.length>0&&(K.models=D.defaultModels.map(V=>({id:V})),K.defaultModel=D.defaultModels[0]),$(!0);try{await r(K)}catch(V){$(!1),M({field:null,message:n("providers.drawer.toast.saveFailure",{message:ce(V).message})});return}p(u),w(!1)};return e.jsx(ye,{open:s,onOpenChange:w,children:e.jsxs(Ne,{className:"max-w-lg",children:[e.jsxs(we,{children:[e.jsx(Ce,{children:n("providers.presets.title")}),e.jsx(Se,{children:n("providers.presets.description")})]}),e.jsxs(ke,{className:"space-y-4",children:[e.jsxs(ee,{className:"flex flex-col gap-2 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:n("providers.presets.template")}),e.jsxs(Re,{value:x,onValueChange:F,children:[e.jsx(Ee,{"aria-label":n("providers.presets.template"),children:e.jsx(Oe,{placeholder:n("providers.presets.templatePlaceholder")})}),e.jsxs(Ae,{children:[T.length>0?e.jsxs(He,{children:[e.jsx($e,{children:n("providers.presets.groupPresets")}),T.map(u=>e.jsx(ne,{value:`${le}${u.id}`,children:e.jsxs("span",{className:"flex flex-col",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:B(u)})]})},u.id))]}):null,e.jsxs(He,{children:[e.jsx($e,{children:n("providers.presets.groupManual")}),Ts.map(u=>e.jsx(ne,{value:`${oe}${u.value}`,children:n(u.labelKey)},u.value))]})]})]})]}),D?e.jsxs("p",{className:"border border-border bg-secondary/50 px-3 py-2 text-xs leading-relaxed text-muted-foreground",children:[B(D),D.noModelProbe?` ${n("providers.presets.noModelProbeNote")}`:""]}):null,e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs(ee,{className:"flex flex-col gap-2 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:n("providers.drawer.fields.id")}),e.jsx(G,{value:a,onChange:u=>P(u.target.value),placeholder:n("providers.drawer.fields.idPlaceholder"),"aria-invalid":(v==null?void 0:v.field)==="id","aria-describedby":v?"create-provider-error":void 0})]}),e.jsxs(ee,{className:"flex flex-col gap-2 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:n("providers.drawer.fields.label")}),e.jsx(G,{value:b,onChange:u=>c(u.target.value),placeholder:n("providers.drawer.fields.labelPlaceholder")})]})]}),U?e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:n("providers.aggregate.drawer.explainerBody")}):e.jsxs(ee,{className:"flex flex-col gap-2 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:n("providers.drawer.fields.baseUrl")}),e.jsx(G,{value:o,onChange:u=>E(u.target.value),placeholder:n("providers.drawer.fields.baseUrlPlaceholder"),"aria-invalid":(v==null?void 0:v.field)==="baseUrl","aria-describedby":v?"create-provider-error":void 0})]}),D&&D.endpoints.length>0&&!U?e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:n("providers.presets.endpointsHint")}),D.endpoints.map(u=>{var _;const L=((_=fs.find(W=>W.value===u.protocol))==null?void 0:_.label)??u.protocol;return e.jsxs(ee,{className:"flex flex-col gap-2 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:n("providers.presets.endpointBaseUrl",{protocol:L})}),e.jsx(G,{value:O[u.id]??u.baseUrl,onChange:W=>g(K=>({...K,[u.id]:W.target.value})),"aria-invalid":(v==null?void 0:v.field)==="endpointUrl"&&v.endpointId===u.id,"aria-describedby":v?"create-provider-error":void 0})]},u.id)})]}):null,v?e.jsx("p",{id:"create-provider-error",className:"text-xs text-destructive","aria-live":"polite",children:v.message}):null]}),e.jsxs(Me,{children:[e.jsx(k,{variant:"outline",onClick:()=>w(!1),disabled:A,children:n("common.actions.cancel")}),e.jsx(k,{onClick:()=>void J(),disabled:A||!x,children:n(A?"common.actions.saving":"providers.presets.createAction")})]})]})})}function Es({open:s,provider:t,onClose:i,onEdit:r}){const{t:p}=q();return t?e.jsx(ye,{open:s,onOpenChange:n=>!n&&i(),children:e.jsxs(Ne,{className:"max-w-md",children:[e.jsxs(we,{children:[e.jsx(Ce,{children:p("providers.noModelDialog.title")}),e.jsx(Se,{children:p("providers.noModelDialog.subtitle",{name:t.label||t.id})})]}),e.jsxs(ke,{className:"space-y-4",children:[e.jsx("div",{className:"rounded-xl bg-secondary p-4 text-sm text-muted-foreground",children:p("providers.noModelDialog.description")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:p("providers.noModelDialog.hint")})]}),e.jsxs(Me,{children:[e.jsx(k,{variant:"outline",onClick:i,children:p("common.actions.close")}),e.jsx(k,{onClick:()=>r(t),children:p("providers.noModelDialog.primary")})]})]})}):null}function Os(s){const{t}=q(),{form:i,errors:r,onModelIdChange:p,onAddModel:n,onRemoveModel:j,onAddMember:x,onRemoveMember:h,onMemberTargetChange:a,onReorderMembers:d,onModelFailoverChange:b,memberOptions:c}=s;return e.jsx("div",{className:"space-y-8",children:e.jsxs("section",{className:"space-y-4","aria-labelledby":"aggregate-model-fields",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{id:"aggregate-model-fields",className:"text-sm font-semibold",children:t("providers.aggregate.drawer.stepTitle")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t("providers.aggregate.drawer.modelsDescription")})]}),e.jsx(k,{type:"button",variant:"outline",size:"sm",onClick:n,className:"bg-card text-xs",children:t("providers.drawer.fields.addModel")})]}),r.models?e.jsx("p",{className:"text-xs text-destructive",children:r.models}):null,e.jsxs("div",{className:"space-y-4",children:[i.models.map((o,E)=>{var O,g;return e.jsxs("div",{"data-testid":"aggregate-model-card",className:"border border-border bg-card p-3",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(ee,{className:"flex flex-col gap-2 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:t("providers.aggregate.drawer.modelIdLabel")}),e.jsx(G,{value:o.id,onChange:v=>p(E,v.target.value),placeholder:t("providers.aggregate.drawer.modelIdPlaceholder"),className:"font-mono"})]}),e.jsx("p",{className:"self-end text-xs leading-relaxed text-muted-foreground",children:t("providers.aggregate.drawer.modelIdHint")})]}),e.jsx(As,{modelKey:o._key,members:o.members,options:c,error:(O=r.members)==null?void 0:O[o._key],onAddMember:x,onRemoveMember:h,onMemberTargetChange:a,onReorderMembers:d}),e.jsxs(Qe,{summary:t("providers.aggregate.drawer.failoverTitle"),className:"mt-3 bg-secondary/50",summaryClassName:"px-3 py-2 text-xs font-medium",contentClassName:"space-y-4 px-3 py-3",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs(ee,{className:"flex flex-col gap-1.5 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:t("providers.aggregate.drawer.consecutiveFailures")}),e.jsx(G,{type:"number",min:1,value:o.failover.consecutiveFailures,onChange:v=>b(o._key,{consecutiveFailures:v.target.value}),placeholder:t("providers.aggregate.drawer.consecutiveFailuresHint")})]}),e.jsxs(ee,{className:"flex flex-col gap-1.5 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:t("providers.aggregate.drawer.cooldownSeconds")}),e.jsx(G,{type:"number",min:1,max:86400,value:o.failover.cooldownSeconds,onChange:v=>b(o._key,{cooldownSeconds:v.target.value}),placeholder:t("providers.aggregate.drawer.cooldownSecondsHint")})]}),e.jsxs(ee,{className:"flex flex-col gap-1.5 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:t("providers.aggregate.drawer.failureWindowSeconds")}),e.jsx(G,{type:"number",min:1,value:o.failover.failureWindowSeconds,onChange:v=>b(o._key,{failureWindowSeconds:v.target.value}),placeholder:t("providers.aggregate.drawer.failureWindowSecondsHint")})]})]}),e.jsxs(ee,{className:"flex flex-col gap-1.5 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:t("providers.aggregate.drawer.triggerStatusCodes")}),e.jsx(G,{value:o.failover.triggerStatusCodes,onChange:v=>b(o._key,{triggerStatusCodes:v.target.value}),placeholder:t("providers.aggregate.drawer.triggerStatusCodesHint"),className:"font-mono text-xs",spellCheck:!1})]}),(g=r.failover)!=null&&g[o._key]?e.jsx("p",{className:"text-xs text-destructive",children:r.failover[o._key]}):null,e.jsx("p",{className:"text-[11px] text-muted-foreground",children:t("providers.aggregate.drawer.defaultsHint")})]}),e.jsx("div",{className:"mt-3 flex justify-end",children:e.jsx(k,{type:"button",variant:"ghost",size:"sm",className:"h-auto px-2 text-destructive",onClick:()=>j(E),children:t("providers.drawer.fields.removeModel")})})]},o._key)}),i.models.length===0?e.jsxs("div",{className:"rounded-xl border border-warning/30 bg-warning-bg p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-warning",children:t("providers.aggregate.drawer.noModelsTitle")}),e.jsx("p",{className:"mt-1 text-xs leading-relaxed text-warning",children:t("providers.aggregate.drawer.noModelsHint")})]}):null]})]})})}function As({modelKey:s,members:t,options:i,error:r,onAddMember:p,onRemoveMember:n,onMemberTargetChange:j,onReorderMembers:x}){const{t:h}=q(),a=Ge(Ue(Ye,{activationConstraint:{distance:6}}),Ue(Xe,{coordinateGetter:Je})),d=b=>{const{active:c,over:o}=b;!o||c.id===o.id||x(s,String(c.id),String(o.id))};return e.jsxs("div",{className:"mt-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:"text-xs font-medium text-foreground",children:h("providers.aggregate.drawer.membersTitle")}),e.jsx(k,{type:"button",variant:"outline",size:"sm","data-testid":"aggregate-add-member",onClick:()=>p(s),className:"h-7 bg-card px-2.5 text-[11px]",children:h("providers.aggregate.drawer.addMember")})]}),r?e.jsx("p",{className:"text-xs text-destructive",children:r}):null,t.length===0?e.jsx("p",{className:"border border-dashed border-border bg-secondary/40 px-3 py-3 text-xs text-muted-foreground",children:h("providers.aggregate.drawer.memberEmptyHint")}):e.jsx(Ze,{sensors:a,collisionDetection:es,onDragEnd:d,children:e.jsx(ss,{items:t.map(b=>b._key),strategy:ts,children:e.jsx("div",{className:"flex flex-col gap-1.5",children:t.map((b,c)=>e.jsx(Ls,{modelKey:s,member:b,index:c,options:i,onRemoveMember:n,onMemberTargetChange:j},b._key))})})}),e.jsx("p",{className:"text-[11px] leading-relaxed text-muted-foreground",children:h("providers.aggregate.drawer.memberHint")})]})}function Ls({modelKey:s,member:t,index:i,options:r,onRemoveMember:p,onMemberTargetChange:n}){const{t:j}=q(),{attributes:x,listeners:h,setNodeRef:a,setActivatorNodeRef:d,transform:b,transition:c,isDragging:o}=rs({id:t._key});return e.jsxs("div",{ref:a,"data-testid":"aggregate-member-row",style:{transform:is.Transform.toString(b),transition:c},className:te("flex items-center gap-2 border border-border bg-card p-2",o&&"z-10 opacity-60 shadow-[var(--surface-shadow-lg)]"),children:[e.jsx("button",{ref:d,type:"button","data-testid":"aggregate-member-grip","aria-label":j("workbench.routing.dragHandle"),className:"flex h-7 w-4 shrink-0 cursor-grab touch-none items-center justify-center text-muted-foreground hover:text-foreground active:cursor-grabbing",...x,...h,children:e.jsx(as,{className:"h-4 w-4","aria-hidden":!0})}),e.jsx("span",{className:"w-4 shrink-0 text-center text-[10.5px] tabular-nums text-muted-foreground",children:i+1}),i===0?e.jsx(Y,{variant:"outline",className:"shrink-0 px-1.5 text-[10px] font-normal text-muted-foreground",children:j("providers.aggregate.drawer.primaryBadge")}):null,e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(Ss,{value:t.target,onChange:E=>n(s,t._key,E),options:r,placeholder:j("providers.aggregate.drawer.memberPlaceholder"),ariaLabel:j("providers.aggregate.drawer.memberTarget")})}),e.jsx(k,{variant:"ghost",size:"icon","data-testid":"aggregate-member-delete",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>p(s,t._key),"aria-label":j("common.delete"),children:e.jsx(ns,{className:"h-3.5 w-3.5","aria-hidden":!0})})]})}function Is({open:s,providerId:t,providerName:i,existingModelIds:r,draft:p,onImport:n,onClose:j}){const{t:x}=q(),{pushToast:h}=Ke(),[a,d]=m.useState({phase:"loading"}),[b,c]=m.useState(""),[o,E]=m.useState(new Set),O=m.useRef(p);O.current=p,m.useEffect(()=>{if(!s)return;d({phase:"loading"}),c(""),E(new Set);let l=!1;return Ve.probeModels(t,O.current).then(w=>{var F;l||(w.ok&&w.models?d({phase:"ready",models:w.models}):d({phase:"error",message:((F=w.statusText)==null?void 0:F.trim())||x("providers.drawer.probe.failedFallback"),status:w.status>0?w.status:void 0}))}).catch(w=>{l||d({phase:"error",message:ce(w).message})}),()=>{l=!0}},[s,t,x]);const g=m.useMemo(()=>new Set(r),[r]),v=m.useMemo(()=>{if(a.phase!=="ready")return[];const l=b.trim().toLowerCase();return l?a.models.filter(w=>w.id.toLowerCase().includes(l)||(w.label??"").toLowerCase().includes(l)):a.models},[a,b]),M=m.useMemo(()=>v.map(l=>l.id).filter(l=>!g.has(l)),[v,g]),A=l=>{E(w=>{const F=new Set(w);return F.has(l)?F.delete(l):F.add(l),F})},$=()=>{E(l=>new Set([...l,...M]))},I=()=>{E(new Set)},T=()=>{if(a.phase!=="ready"||o.size===0)return;const l=a.models.filter(w=>o.has(w.id));n(l),h({title:x("providers.drawer.probe.importSuccess",{count:l.length}),variant:"success"}),j()};return e.jsx(ye,{open:s,onOpenChange:l=>!l&&j(),children:e.jsxs(Ne,{className:"max-w-2xl",children:[e.jsxs(we,{children:[e.jsx(Ce,{children:x("providers.drawer.probe.title")}),e.jsx(Se,{children:x("providers.drawer.probe.subtitle",{name:i})})]}),e.jsxs(ke,{className:"space-y-4",children:[a.phase==="loading"?e.jsx("p",{className:"rounded-xl bg-secondary/50 px-4 py-6 text-center text-sm text-muted-foreground",children:x("providers.drawer.probe.loading")}):null,a.phase==="error"?e.jsxs("div",{className:"space-y-2 rounded-xl border border-warning/30 bg-warning-bg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-semibold text-warning",children:x("providers.drawer.probe.failedTitle")}),a.status?e.jsxs(Y,{variant:"warning",className:"shrink-0",children:["HTTP ",a.status]}):null]}),e.jsx("p",{className:"break-words text-xs leading-relaxed text-warning",children:a.message}),e.jsx("p",{className:"text-xs text-muted-foreground",children:x("providers.drawer.probe.failedHint")})]}):null,a.phase==="ready"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(G,{value:b,onChange:l=>c(l.target.value),placeholder:x("providers.drawer.probe.searchPlaceholder"),className:"h-9"}),e.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:x("providers.drawer.probe.totalCount",{count:a.models.length})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"h-auto bg-card px-2 py-1 text-xs",onClick:$,disabled:M.length===0,children:x("providers.drawer.probe.selectAll")}),e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"h-auto bg-card px-2 py-1 text-xs",onClick:I,disabled:o.size===0,children:x("providers.drawer.probe.clearSelection")})]}),e.jsx("span",{className:"text-muted-foreground",children:x("providers.drawer.probe.selectedCount",{count:o.size})})]}),v.length===0?e.jsx("p",{className:"rounded-xl bg-secondary/50 px-4 py-6 text-center text-sm text-muted-foreground",children:x("providers.drawer.probe.emptyResult")}):e.jsx("div",{className:"grid max-h-80 gap-1 overflow-y-auto",children:v.map(l=>{const w=g.has(l.id),F=o.has(l.id);return e.jsxs("label",{className:te("flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2.5 transition-colors",w?"cursor-not-allowed opacity-60":"cursor-pointer hover:border-foreground/30 hover:bg-accent/50",F&&"border-foreground bg-secondary"),children:[e.jsx("input",{type:"checkbox",className:"h-4 w-4 shrink-0 rounded border-input accent-primary",checked:F,disabled:w,onChange:()=>A(l.id)}),e.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-xs",children:l.id}),l.label?e.jsx("span",{className:"shrink-0 truncate text-xs text-muted-foreground",children:l.label}):null,w?e.jsx(Y,{variant:"secondary",className:"shrink-0",children:x("providers.drawer.probe.imported")}):null]},l.id)})})]}):null]}),e.jsxs(Me,{children:[e.jsx(k,{variant:"outline",onClick:j,children:x("common.actions.cancel")}),e.jsx(k,{onClick:T,disabled:a.phase!=="ready"||o.size===0,children:x("providers.drawer.probe.importAction",{count:o.size})})]})]})})}const qe={refresh(s){return _e(ze.post(`/api/providers/${s}/balance/refresh`))},all(){return _e(ze.get("/api/providers/balances"))}},Fs=[{value:"deepseek",label:"DeepSeek"},{value:"moonshot",label:"Moonshot / Kimi"},{value:"siliconflow",label:"SiliconFlow"},{value:"openrouter",label:"OpenRouter"}];function Us({form:s,errors:t,onKeyChange:i,onAddKey:r,onRemoveKey:p}){const{t:n}=q(),[j,x]=m.useState(new Set),h=a=>{x(d=>{const b=new Set(d);return b.has(a)?b.delete(a):b.add(a),b})};return e.jsxs("section",{className:"space-y-3","aria-labelledby":"provider-keys-fields",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{id:"provider-keys-fields",className:"text-sm font-semibold",children:s.keys.length>0?`${n("providers.keys.title")} (${s.keys.length})`:n("providers.keys.title")}),e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:n("providers.keys.hint")})]}),e.jsx(k,{type:"button",variant:"outline",size:"sm",onClick:r,className:"bg-card text-xs",children:n("providers.keys.add")})]}),s.keys.length>0?e.jsx("div",{className:"divide-y divide-border border border-border",children:s.keys.map((a,d)=>{var c;const b=(c=t.keys)==null?void 0:c[a._key];return e.jsxs("div",{className:"space-y-2 p-3","data-testid":"provider-key-row",children:[e.jsxs("div",{className:"grid gap-2 md:grid-cols-[auto_minmax(0,0.8fr)_minmax(0,0.8fr)_minmax(0,2fr)_auto_auto] md:items-center",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx("input",{type:"radio",name:`provider-active-key-${s.id}`,checked:a.active,onChange:()=>i(d,{active:!0}),"aria-label":n("providers.keys.active"),className:"h-4 w-4 accent-primary"}),n("providers.keys.active")]}),e.jsx(G,{value:a.id,onChange:o=>i(d,{id:o.target.value}),placeholder:n("providers.keys.idPlaceholder"),"aria-label":n("providers.keys.id"),className:"h-8 text-xs","aria-invalid":!!b}),e.jsx(G,{value:a.label,onChange:o=>i(d,{label:o.target.value}),placeholder:n("providers.keys.labelPlaceholder"),"aria-label":n("providers.keys.label"),className:"h-8 text-xs"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx(G,{type:j.has(a._key)?"text":"password",value:a.value,onChange:o=>i(d,{value:o.target.value}),placeholder:n("providers.keys.valuePlaceholder"),"aria-label":n("providers.keys.value"),autoComplete:"off",className:"h-8 font-mono text-xs"}),e.jsx(k,{type:"button",variant:"ghost",size:"sm",className:"h-8 w-8 shrink-0 px-0",onClick:()=>h(a._key),"aria-label":j.has(a._key)?n("providers.keys.hide"):n("providers.keys.reveal"),children:j.has(a._key)?e.jsx(ls,{className:"h-4 w-4","aria-hidden":"true"}):e.jsx(os,{className:"h-4 w-4","aria-hidden":"true"})})]}),e.jsx("span",{className:"text-right",children:e.jsx(k,{type:"button",variant:"ghost",size:"sm",className:"h-auto px-2 text-xs text-destructive",onClick:()=>p(d),children:n("common.delete")})})]}),b?e.jsx("p",{className:"text-xs text-destructive",children:b}):null]},a._key)})}):e.jsx("p",{className:"border border-dashed border-border px-3 py-3 text-xs text-muted-foreground",children:n("providers.keys.empty")})]})}function _s({value:s,onChange:t}){const{t:i}=q();return e.jsxs(Re,{value:s||"none",onValueChange:r=>t(r==="none"?"":r),children:[e.jsx(Ee,{className:"h-8 w-[220px] text-xs","aria-label":i("providers.balance.adapter"),children:e.jsx(Oe,{placeholder:i("providers.balance.adapterNone")})}),e.jsxs(Ae,{children:[e.jsx(ne,{value:"none",children:i("providers.balance.adapterNone")}),Fs.map(r=>e.jsx(ne,{value:r.value,children:r.label},r.value))]})]})}function zs({providerId:s,adapter:t,savedAdapter:i,onAdapterChange:r}){const{t:p}=q(),n=Te(ue.providers.balances(),{url:"/api/providers/balances",method:"GET"},{retry:!1}),j=m.useMemo(()=>{var a;return((a=n.data)==null?void 0:a.balances.find(d=>d.providerId===s))??null},[n.data,s]),x=We({mutationFn:()=>qe.refresh(s),successToast:a=>({title:p("providers.balance.refreshSuccess"),description:a.display??p("providers.balance.displayEmpty")}),errorToast:a=>({title:p("providers.balance.refreshFailure",{message:a.message})}),invalidateKeys:[ue.providers.balances()]}),h=(t||void 0)!==i;return e.jsxs("section",{className:"space-y-3","aria-labelledby":"provider-balance-fields",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{id:"provider-balance-fields",className:"text-sm font-semibold",children:p("providers.balance.title")}),e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:p("providers.balance.hint")})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(_s,{value:t,onChange:r}),e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"bg-card text-xs",onClick:()=>x.mutate(),disabled:!i||h||x.isPending,title:i?h?p("providers.balance.unsavedAdapter"):void 0:p("providers.balance.noAdapter"),children:x.isPending?p("providers.balance.refreshing"):p("providers.balance.refresh")}),h&&i?e.jsx("span",{className:"text-xs text-muted-foreground",children:p("providers.balance.unsavedAdapter")}):null]}),j?e.jsxs("div",{className:"border border-border p-4",children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground",children:p("providers.balance.snapshotLabel")}),e.jsx("p",{className:"mt-2 font-mono text-sm font-semibold tabular-nums",children:j.display??p("providers.balance.displayEmpty")}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:p("providers.balance.fetchedAt",{time:new Date(j.fetchedAt).toLocaleString()})}),e.jsx(Qe,{summary:p("providers.balance.rawTitle"),className:"mt-3 bg-secondary/50",summaryClassName:"px-3 py-2 text-xs font-medium",contentClassName:"px-3 py-3",children:e.jsx("pre",{className:"max-h-64 overflow-auto font-mono text-xs leading-relaxed text-foreground",children:JSON.stringify(j.raw,null,2)})})]}):i?e.jsx("p",{className:"border border-dashed border-border px-3 py-3 text-xs text-muted-foreground",children:p("providers.balance.neverRefreshed")}):null]})}const Hs={anthropic:"Anthropic",openai:"OpenAI Chat","openai-responses":"Responses"};function ve({label:s,children:t}){return e.jsxs("div",{className:"grid gap-1 py-2 sm:grid-cols-[110px_minmax(0,1fr)] sm:gap-3 sm:py-1.5",children:[e.jsx("dt",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:s}),e.jsx("dd",{className:"min-w-0 text-xs text-foreground",children:t})]})}function Be({value:s}){const{t}=q(),{pushToast:i}=Ke(),[r,p]=m.useState(!1),n=async()=>{try{await ks(s),p(!0),window.setTimeout(()=>p(!1),1500)}catch{i({title:t("common.actions.copyFailed"),variant:"error"})}};return e.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[e.jsx("span",{className:"truncate font-mono",children:s}),e.jsx(k,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 shrink-0 px-0 text-muted-foreground hover:text-foreground",onClick:()=>void n(),"aria-label":t("providers.profile.copy"),children:r?e.jsx(ds,{className:"h-3.5 w-3.5 text-foreground","aria-hidden":"true"}):e.jsx(cs,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]})}function $s({provider:s}){var b;const{t}=q(),i=s.type==="aggregate",r=m.useMemo(()=>!s.keys||s.keys.length===0?null:s.keys.find(c=>c.active)??s.keys[0],[s.keys]),p=r?t("providers.profile.namedKeys",{count:((b=s.keys)==null?void 0:b.length)??0,id:r.label||r.id}):s.apiKey?t("providers.profile.singleKey"):t("providers.profile.noKey"),n=m.useMemo(()=>{const c=[];s.nonStreamViaStream&&c.push(t("providers.drawer.fields.nonStreamViaStream")),s.useAbsoluteUrl&&c.push(t("providers.drawer.fields.useAbsoluteUrl")),s.streamUsage&&c.push(t("providers.drawer.fields.streamUsage")),s.rpmLimit&&c.push(`RPM ${s.rpmLimit}`),s.rpmMaxWaitSeconds&&c.push(t("providers.profile.rpmWait",{seconds:s.rpmMaxWaitSeconds}));const o=Object.keys(s.extraHeaders??{}).length;return o>0&&c.push(t("providers.profile.headers",{count:o})),c},[s,t]),j=Te(ue.providers.balances(),{url:"/api/providers/balances",method:"GET"},{retry:!1,enabled:!!s.balanceAdapter}),x=m.useMemo(()=>{var c;return((c=j.data)==null?void 0:c.balances.find(o=>o.providerId===s.id))??null},[j.data,s.id]),h=We({mutationFn:()=>qe.refresh(s.id),successToast:c=>({title:t("providers.balance.refreshSuccess"),description:c.display??t("providers.balance.displayEmpty")}),errorToast:c=>({title:t("providers.balance.refreshFailure",{message:c.message})}),invalidateKeys:[ue.providers.balances()]}),a=s.models??[],d=s.defaultModel;return e.jsxs("div",{className:"space-y-5","data-testid":"provider-profile-view",children:[e.jsxs("section",{"aria-labelledby":"provider-profile-connection",className:"space-y-2",children:[e.jsx("h3",{id:"provider-profile-connection",className:"text-sm font-semibold",children:t("providers.profile.connection")}),i?e.jsx("p",{className:"border border-border bg-secondary/40 px-3 py-2.5 text-xs leading-relaxed text-muted-foreground",children:t("providers.aggregate.drawer.explainerBody")}):e.jsxs("dl",{className:"divide-y divide-border border border-border px-3 py-1.5",children:[e.jsx(ve,{label:t("providers.profile.primaryEndpoint"),children:s.baseUrl?e.jsx(Be,{value:s.baseUrl}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),(s.endpoints??[]).map(c=>e.jsx(ve,{label:t("providers.profile.protocolEndpoint"),children:e.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[e.jsx(Y,{variant:"outline",className:"shrink-0 text-[10px]",children:Hs[c.protocol]}),e.jsx(Be,{value:c.baseUrl})]})},c.id)),e.jsx(ve,{label:t("providers.drawer.sections.auth"),children:e.jsxs("span",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{children:js(s.type,s.authMode??"apiKey",t)}),e.jsx("span",{className:"text-muted-foreground",children:"·"}),e.jsx("span",{className:te(r||s.apiKey?"text-foreground":"text-warning"),children:p})]})}),s.balanceAdapter?e.jsx(ve,{label:t("providers.balance.title"),children:e.jsxs("span",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{children:s.balanceAdapter}),x!=null&&x.display?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"·"}),e.jsx("span",{className:"font-medium",children:x.display})]}):null,e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"h-6 bg-card px-2 text-[11px]",onClick:()=>h.mutate(),disabled:h.isPending,children:h.isPending?t("common.loading"):t("providers.balance.refresh")})]})}):null]}),n.length>0?e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:t("providers.profile.advanced")}),n.map(c=>e.jsx(Y,{variant:"secondary",className:"text-[10px] font-normal",children:c},c))]}):null]}),e.jsxs("section",{"aria-labelledby":"provider-profile-models",className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("h3",{id:"provider-profile-models",className:"text-sm font-semibold",children:a.length>0?`${t("providers.drawer.fields.models")} (${a.length})`:t("providers.drawer.fields.models")}),i?null:e.jsx("span",{className:"text-[11px] text-muted-foreground",children:t("providers.profile.defaultIs",{model:d??t("providers.card.noDefault")})})]}),a.length===0?e.jsx("p",{className:"border border-dashed border-border px-3 py-4 text-xs text-muted-foreground",children:t("providers.profile.noModelsHint")}):i?e.jsx("ul",{className:"divide-y divide-border border border-border",children:a.map(c=>e.jsxs("li",{className:"px-3 py-2",children:[e.jsx("p",{className:"font-mono text-xs",children:c.id}),c.members&&c.members.length>0?e.jsx("p",{className:"mt-0.5 truncate font-mono text-[11px] text-muted-foreground",title:c.members.map(o=>o.target).join(" → "),children:c.members.map(o=>o.target).join(" → ")}):null]},c.id))}):e.jsx("div",{className:"grid gap-1.5 sm:grid-cols-2 lg:grid-cols-3",children:a.map(c=>{const o=c.id===d;return e.jsxs("div",{className:te("flex min-w-0 items-center gap-2 border px-2.5 py-1.5",o?"border-foreground/60 bg-secondary/60":"border-border bg-secondary/30"),title:c.label?`${c.label} (${c.id})`:c.id,children:[e.jsx("span",{className:te("h-1.5 w-1.5 shrink-0 rounded-full",o?"bg-foreground":"bg-border"),"aria-hidden":"true"}),e.jsx("span",{className:"truncate font-mono text-xs",children:c.id}),o?e.jsx("span",{className:"ml-auto shrink-0 text-[10px] font-medium text-foreground",children:t("providers.profile.defaultTag")}):null]},c.id)})})]}),!i&&s.type&&s.type!=="openai"&&s.type!=="anthropic"?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:t("providers.profile.typeFootnote",{type:Le(s.type,t)})}):null]})}function Bs({provider:s,providers:t,onSubmit:i}){const r=ys({mode:"edit",provider:s,existingProviderIds:[],providers:t}),[p,n]=m.useState(!1),[j,x]=m.useState(null),h=m.useRef(null);h.current===null&&(h.current=JSON.stringify(r.form));const a=JSON.stringify(r.form)!==h.current,d=m.useRef(s);return d.current!==s&&(d.current=s,a||(r.resetForm(),h.current=null)),{providerForm:r,dirty:a,saving:p,saveError:j,save:async()=>{if(!r.validate())return!1;n(!0),x(null);try{const o=r.serialize();return await i(o),h.current=JSON.stringify(r.form),!0}catch(o){return x(ce(o).message),!1}finally{n(!1)}},discard:()=>{r.resetForm(),h.current=null,x(null)}}}const Ks={anthropic:"Anthropic",openai:"OpenAI Chat","openai-responses":"Responses"};function Vs({provider:s,allProviders:t,testResult:i,testing:r,onTest:p,onRequestDelete:n,onSubmit:j,onDirtyChange:x,startInEdit:h=!1}){const{t:a}=q(),[d,b]=m.useState(!1),[c,o]=m.useState(h?"edit":"view"),[E,O]=m.useState(!1),{providerForm:g,dirty:v,saving:M,saveError:A,save:$,discard:I}=Bs({provider:s,providers:t,onSubmit:j}),{form:T,errors:l,advancedOpen:w,providerIdRef:F}=g,P=T.type==="aggregate";m.useEffect(()=>{h&&o("edit")},[h]);const D=async()=>{await $()&&o("view")},y=()=>{I(),o("view")},U=()=>{if(v){O(!0);return}o("view")};m.useEffect(()=>(x==null||x(v),()=>x==null?void 0:x(!1)),[v,x]);const B=m.useMemo(()=>{var V;const K=[];for(const Q of t){if(Q.type==="aggregate")continue;const f=Q.label&&Q.label!==Q.id?`${Q.label} (${Q.id})`:Q.id,C=(V=Q.models)!=null&&V.length?Q.models:Q.defaultModel?[{id:Q.defaultModel}]:[];for(const S of C)K.push({value:`${Q.id}:${S.id}`,label:`${f} · ${S.label??S.id}`,providerId:Q.id,providerLabel:f,modelId:S.id,modelLabel:S.label??S.id,kind:"model"})}return K},[t]),J={form:T,errors:l,isCreate:!1,advancedOpen:w,onAdvancedOpenChange:g.setAdvancedOpen,idInputRef:F,onProviderIdChange:g.handleProviderIdChange,onFieldChange:g.handleFieldChange,onTypeChange:g.handleTypeChange,onAuthModeChange:g.handleAuthModeChange,onNonStreamViaStreamChange:g.handleProviderNonStreamViaStreamChange,onUseAbsoluteUrlChange:g.handleUseAbsoluteUrlChange,onStreamUsageChange:g.handleStreamUsageChange,onAddHeader:g.handleAddHeader,onRemoveHeader:g.handleRemoveHeader,onHeaderChange:g.handleHeaderChange,onModelIdChange:g.handleModelIdChange,onModelChange:g.handleModelChange,onAddModel:g.handleAddModel,onRemoveModel:g.handleRemoveModel,onModelNonStreamViaStreamChange:g.handleModelNonStreamViaStreamChange,onSetDefaultModel:g.handleSetDefaultModel,onEndpointChange:g.handleEndpointChange,onAddEndpoint:g.handleAddEndpoint,onRemoveEndpoint:g.handleRemoveEndpoint,memberOptions:B,onAddMember:g.handleAddMember,onRemoveMember:g.handleRemoveMember,onMemberTargetChange:g.handleMemberTargetChange,onReorderMembers:g.handleReorderMembers,onModelFailoverChange:g.handleModelFailoverChange,testVerification:P?void 0:{available:!0,testing:r,result:i,onTest:()=>p(g.serialize())},probeModels:P?void 0:{available:T.baseUrl.trim().length>0,onProbe:()=>b(!0)}},u=c==="edit",L=u?T.type:s.type,_=u?T.endpoints:s.endpoints??[],W=u?T.models.length:(s.models??[]).length;return e.jsxs(be,{className:"overflow-hidden","data-testid":"provider-detail-panel",children:[e.jsxs("header",{className:"flex flex-wrap items-start justify-between gap-3 border-b border-border bg-secondary/50 px-5 py-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h2",{className:"truncate text-base font-semibold tracking-[-0.02em]",children:s.label||s.id}),i?i.ok?e.jsx(Y,{variant:"success",className:"shrink-0 text-[10px]",children:i.durationMs!==void 0?`${a("providers.masterDetail.testOkShort")} · ${i.durationMs}ms`:a("providers.masterDetail.testOkShort")}):e.jsx(Y,{variant:"destructive",className:"shrink-0 text-[10px]",title:i.message??void 0,children:a("providers.masterDetail.testFailedShort")}):null,u?e.jsx(Y,{variant:"outline",className:"shrink-0 text-[10px] text-muted-foreground",children:a("providers.profile.editingTag")}):null]}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5",children:[e.jsx(Y,{variant:"secondary",className:"text-[10px]",children:Le(L,a)}),L==="aggregate"?null:_.map(K=>e.jsxs(Y,{variant:"outline",className:"text-[10px]",children:["+ ",Ks[K.protocol]]},K.id)),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:a("providers.masterDetail.modelsMeta",{count:W})})]}),e.jsx("p",{className:"mt-0.5 font-mono text-xs text-muted-foreground",children:s.id})]}),e.jsxs("div",{className:"flex shrink-0 gap-2",children:[P?null:e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"bg-card text-xs",onClick:()=>p(g.serialize()),disabled:r,children:a(r?"common.actions.testingConnection":"providers.actions.test")}),u?e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"bg-card text-xs",onClick:U,disabled:M,children:a("providers.profile.cancelEdit")}):e.jsx(k,{type:"button",variant:"outline",size:"sm","data-testid":"provider-edit",onClick:()=>o("edit"),children:a("providers.profile.edit")}),e.jsx(k,{type:"button",variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive",onClick:()=>n(s),disabled:M,children:a("providers.actions.delete")})]})]}),e.jsx(je,{className:"p-5",children:u?e.jsxs("div",{className:"space-y-5",children:[e.jsx(Ns,{...J}),P?null:e.jsxs(e.Fragment,{children:[e.jsx(Us,{form:T,errors:l,onKeyChange:g.handleKeyChange,onAddKey:g.handleAddKey,onRemoveKey:g.handleRemoveKey}),e.jsx(zs,{providerId:s.id,adapter:T.balanceAdapter,savedAdapter:s.balanceAdapter,onAdapterChange:g.handleBalanceAdapterChange})]}),P?e.jsx(Os,{...J}):e.jsx(ws,{...J})]}):e.jsx($s,{provider:s})}),u&&(v||A)?e.jsxs("footer",{className:"sticky bottom-0 flex flex-wrap items-center justify-between gap-3 border-t border-border bg-card px-5 py-3",children:[e.jsx("div",{className:"min-w-0 text-xs",children:e.jsx("span",{className:te("font-medium",A?"text-destructive":"text-foreground"),"aria-live":"polite",children:A?a("providers.drawer.toast.saveFailure",{message:A}):a("providers.masterDetail.dirtyHint")})}),e.jsxs("div",{className:"flex shrink-0 gap-2",children:[e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"bg-card text-xs",onClick:y,disabled:M,children:a("providers.masterDetail.discard")}),e.jsx(k,{type:"button",variant:"outline",size:"sm","data-testid":"provider-save",onClick:()=>void D(),disabled:M,children:a(M?"common.actions.saving":"providers.masterDetail.save")})]})]}):null,e.jsx(de,{open:E,onOpenChange:O,title:a("providers.masterDetail.unsavedTitle"),description:a("providers.masterDetail.unsavedBody"),confirmLabel:a("providers.masterDetail.unsavedConfirm"),cancelLabel:a("common.actions.cancel"),onConfirm:()=>{I(),o("view"),O(!1)}}),e.jsx(Is,{open:d,providerId:s.id,providerName:s.label||s.id,existingModelIds:T.models.map(K=>K.id.trim()).filter(Boolean),draft:g.serialize(),onImport:g.handleImportModels,onClose:()=>b(!1)})]})}function Qs({providers:s,configPending:t,configError:i,onRetryConfig:r,selectedProviderId:p,onSelectProvider:n,onTest:j,onRequestDelete:x,onDirtyChange:h,autoEditProviderId:a}){const{t:d}=q(),{filteredProviders:b,providerSearch:c,setProviderSearch:o,providerTypeFilter:E,setProviderTypeFilter:O}=s,g=s.providers.length,[v,M]=m.useState(!1),[A,$]=m.useState(null),I=m.useCallback(y=>{M(y),h==null||h(y)},[h]),[T,l]=m.useState(!1),w=m.useRef(!0);m.useEffect(()=>{if(w.current){w.current=!1;return}l(!!p)},[p]),m.useEffect(()=>{if(!v)return;const y=U=>{U.preventDefault(),U.returnValue=""};return window.addEventListener("beforeunload",y),()=>window.removeEventListener("beforeunload",y)},[v]);const F=y=>{if(v&&y!==p){$(y);return}n(y),l(!0)},P=s.providers.find(y=>y.id===p)??null,D=y=>{var J,u;const U=[],B=((J=y.models)==null?void 0:J.length)??0;if(U.push(d("providers.masterDetail.modelsMeta",{count:B})),y.type!=="aggregate"){const L=((u=y.keys)==null?void 0:u.length)??0;U.push(L>0?d("providers.masterDetail.keysMeta",{count:L}):d("providers.masterDetail.noKeysMeta"))}return U.join(" · ")};return e.jsx("div",{className:"grid gap-4 lg:grid-cols-[300px_minmax(0,1fr)]",children:i?e.jsx(fe,{className:"lg:col-span-2",tone:"danger",title:d("common.status.error"),description:i,action:r?e.jsx(k,{variant:"outline",onClick:r,children:d("common.actions.refresh")}):void 0}):e.jsxs(e.Fragment,{children:[e.jsx(be,{className:te("h-fit overflow-hidden lg:sticky lg:top-4",T&&P?"hidden lg:block":""),children:e.jsxs(je,{className:"p-0",children:[e.jsxs("div",{className:"space-y-2 border-b border-border bg-secondary/50 px-3 py-3",children:[e.jsx(G,{value:c,onChange:y=>o(y.target.value),placeholder:d("providers.filters.searchPlaceholder"),className:"h-9"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Re,{value:E,onValueChange:O,children:[e.jsx(Ee,{className:"h-9 flex-1 text-xs","aria-label":d("providers.table.type"),children:e.jsx(Oe,{})}),e.jsxs(Ae,{children:[e.jsx(ne,{value:"all",children:d("providers.filters.typeAll")}),Cs.map(y=>e.jsx(ne,{value:y.value??"custom",children:y.label},y.value??"custom"))]})]}),e.jsx(Y,{variant:"secondary",className:"shrink-0 px-2.5 py-1 text-[11px]",children:d("providers.groupCount",{count:b.length})})]})]}),t?e.jsx("div",{className:"flex min-h-[160px] items-center justify-center text-sm text-muted-foreground",children:d("common.loading")}):g===0?e.jsx("div",{className:"p-4",children:e.jsx(fe,{compact:!0,title:d("providers.emptyState"),description:e.jsxs(e.Fragment,{children:[e.jsx("p",{children:d("providers.emptyStateSub")}),e.jsx("p",{className:"mt-1",children:d("workbench.list.emptyHint")})]})})}):b.length===0?e.jsx("div",{className:"p-4",children:e.jsx(fe,{compact:!0,title:d("providers.emptyFiltered")})}):e.jsx("ul",{className:"max-h-[60vh] overflow-y-auto p-2 lg:max-h-[calc(100vh-320px)]",children:b.map(y=>{const U=y.id===p,B=s.testResults[y.id]??null,J=B!==null&&!B.ok,u=J?B.message?`${d("providers.masterDetail.testFailedShort")}: ${B.message}`:d("providers.masterDetail.testFailedShort"):void 0;return e.jsx("li",{children:e.jsxs("button",{type:"button","data-testid":"provider-rail-row",onClick:()=>F(y.id),"aria-current":U?"true":void 0,className:te("motion-surface w-full border border-transparent px-3 py-2.5 text-left",U?"border-foreground bg-secondary":"hover:bg-muted/40"),children:[e.jsxs("span",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-1.5 text-sm font-medium",children:[J?e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-destructive",title:u,"aria-label":d("providers.masterDetail.testFailedShort")}):null,e.jsx("span",{className:"truncate",children:y.label||y.id})]}),e.jsx(Y,{variant:U?"default":"secondary",className:"shrink-0 text-[10px]",children:Le(y.type,d)})]}),e.jsxs("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",children:[y.id," · ",D(y)]})]})},y.id)})})]})}),e.jsxs("div",{className:te("min-w-0",T?"block":"hidden lg:block"),children:[P?e.jsxs(k,{type:"button",variant:"ghost",size:"sm",className:"mb-2 lg:hidden",onClick:()=>l(!1),children:[e.jsx(us,{className:"mr-1.5 h-4 w-4","aria-hidden":"true"}),d("providers.masterDetail.backToList")]}):null,t?e.jsx(be,{children:e.jsx(je,{className:"flex min-h-[240px] items-center justify-center text-sm text-muted-foreground",children:d("common.loading")})}):P?e.jsx(Vs,{provider:P,allProviders:s.providers,testResult:s.testResults[P.id]??null,testing:s.testingProviderId===P.id,onTest:j,onRequestDelete:x,onSubmit:s.handleUpdateProvider,onDirtyChange:I,startInEdit:a===P.id},P.id):e.jsx(be,{children:e.jsx(je,{className:"p-0",children:e.jsx(fe,{title:d("providers.masterDetail.emptyDetailTitle"),description:d("providers.masterDetail.emptyDetailHint")})})})]}),e.jsx(de,{open:!!A,onOpenChange:y=>{y||$(null)},title:d("providers.masterDetail.unsavedTitle"),description:d("providers.masterDetail.unsavedBody"),confirmLabel:d("providers.masterDetail.unsavedConfirm"),cancelLabel:d("common.actions.cancel"),onConfirm:()=>{A&&(n(A),l(!0)),$(null)}})]})})}function Ws({open:s,provider:t,options:i,usePreset:r,preservedExtras:p,onPresetChange:n,onConfirm:j,onClose:x}){const{t:h}=q();return t?e.jsx(ye,{open:s,onOpenChange:a=>!a&&x(),children:e.jsxs(Ne,{className:"max-w-2xl",onInteractOutside:a=>a.preventDefault(),children:[e.jsxs(we,{children:[e.jsx(Ce,{children:h("providers.testDialog.title")}),e.jsx(Se,{children:h("providers.testDialog.subtitle",{name:t.label||t.id})})]}),e.jsxs(ke,{className:"space-y-4",children:[e.jsx("div",{className:"rounded-xl bg-secondary p-4 text-sm text-muted-foreground",children:h("providers.testDialog.description")}),e.jsxs("div",{className:"space-y-4 rounded-xl bg-secondary/50 p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"provider-test-preset",children:h("providers.testDialog.presetLabel")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:h("providers.testDialog.presetDescription")})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(Ms,{id:"provider-test-preset",checked:r,onCheckedChange:n})})]}),r?e.jsx("div",{className:"space-y-2",children:e.jsxs("details",{className:"border border-border bg-card p-2 text-xs",children:[e.jsx("summary",{className:"cursor-pointer text-foreground underline decoration-muted-foreground/40 underline-offset-2 hover:decoration-foreground",children:h("providers.testDialog.presetPreviewSummary")}),e.jsx("div",{className:"mt-2 space-y-1",children:i.map(a=>e.jsxs("code",{className:"block rounded-lg bg-secondary px-2 py-1 text-xs",children:[a.key,": ",a.value]},a.key))})]})}):e.jsx("p",{className:"text-xs text-muted-foreground",children:h("providers.testDialog.presetDescription")})]}),Object.keys(p).length>0&&e.jsxs("div",{className:"space-y-2 rounded-xl bg-secondary/50 p-4 text-xs",children:[e.jsx("p",{className:"font-medium",children:h("providers.testDialog.preservedInfo")}),Object.entries(p).map(([a,d])=>e.jsxs("code",{className:"block border border-border bg-card px-2 py-1",children:[a,": ",d]},a))]})]}),e.jsxs(Me,{children:[e.jsx(k,{variant:"outline",onClick:x,children:h("providers.testDialog.cancel")}),e.jsx(k,{onClick:()=>void j(),children:h("providers.testDialog.primary")})]})]})}):null}function ht(){var T;const{t:s}=q(),t=gs(),i=Ps(t),[r,p]=m.useState(null),[n,j]=m.useState(!1),[x,h]=m.useState(!1),[a,d]=m.useState(!1),b=m.useRef(!1),c=m.useCallback(l=>{b.current=l,d(l)},[]),[o,E]=m.useState(null),O=Ds(({currentLocation:l,nextLocation:w})=>a&&l.pathname!==w.pathname),[g,v]=m.useState(()=>typeof window>"u"?null:window.localStorage.getItem(De.workbench.providerSelection)),[M,A]=m.useState(null);m.useEffect(()=>{M&&g!==M&&A(null)},[M,g]),m.useEffect(()=>{if(!g){window.localStorage.removeItem(De.workbench.providerSelection);return}window.localStorage.setItem(De.workbench.providerSelection,g)},[g]),m.useEffect(()=>{g&&(t.configQuery.isPending||t.configQuery.isFetching||i.providers.some(l=>l.id===g)||v(null))},[g,i.providers,t.configQuery.isPending,t.configQuery.isFetching]);const $=async()=>{if(r){j(!0);try{r.kind==="provider"&&await i.handleDeleteProvider(r.provider),p(null)}finally{j(!1)}}},I=(r==null?void 0:r.kind)==="provider"?hs(t.config,t.customEndpoints,r.provider.id):{routes:0,defaults:0,aggregateMembers:0};return e.jsxs("div",{className:"flex flex-col gap-6",children:[e.jsx(ms,{status:e.jsx(Y,{variant:"secondary",children:s("providers.groupCount",{count:i.providerCount})}),actions:e.jsx(k,{size:"sm",onClick:()=>h(!0),children:s("providers.actions.add")})}),e.jsx(Qs,{providers:i,configPending:t.configQuery.isPending||!t.config&&t.configQuery.isFetching,configError:!t.config&&t.configQuery.isError?((T=t.configQuery.error)==null?void 0:T.message)??s("common.status.error"):null,onRetryConfig:()=>void t.configQuery.refetch(),selectedProviderId:g,onSelectProvider:v,onTest:l=>i.initiateTestConnection(l),onRequestDelete:l=>p({kind:"provider",provider:l}),onDirtyChange:c,autoEditProviderId:M}),e.jsx(Rs,{open:x,onOpenChange:h,existingProviderIds:i.providers.map(l=>l.id),onSubmit:i.handleCreateProvider,onCreated:l=>{t.configQuery.refetch().then(()=>{if(b.current){E(l);return}v(l),A(l)})}}),e.jsx(Ws,{open:i.testDialogOpen,provider:i.testDialogProvider,options:i.anthropicTestHeaderOptions,preservedExtras:i.testDialogPreservedExtras,usePreset:i.testDialogUsePreset,onPresetChange:i.setTestDialogUsePreset,onConfirm:i.confirmTestDialog,onClose:i.closeTestDialog}),e.jsx(Es,{open:!!i.noModelDialogProvider,provider:i.noModelDialogProvider,onClose:()=>i.setNoModelDialogProvider(null),onEdit:l=>{i.setNoModelDialogProvider(null),v(l.id),A(l.id)}}),e.jsx(de,{open:!!r,onOpenChange:l=>{!l&&!n&&p(null)},title:(r==null?void 0:r.kind)==="provider"?s("providers.actions.delete"):"",description:(r==null?void 0:r.kind)==="provider"?s("providers.confirm.delete",{name:r.provider.label||r.provider.id}):"",confirmLabel:s(n?"common.actions.loading":"common.delete"),cancelLabel:s("common.actions.cancel"),loading:n,onConfirm:$,children:(r==null?void 0:r.kind)==="provider"?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"rounded-xl border border-destructive/20 bg-destructive/5 px-3 py-2 font-mono text-xs text-foreground",children:r.provider.label||r.provider.id}),I.routes>0?e.jsx("p",{className:"text-xs text-muted-foreground",children:s("providers.confirm.deleteImpact",{count:I.routes})}):null,I.defaults>0?e.jsx("p",{className:"text-xs text-muted-foreground",children:s("providers.confirm.deleteDefaultsImpact",{count:I.defaults})}):null,I.aggregateMembers>0?e.jsx("p",{className:"text-xs text-muted-foreground",children:s("providers.confirm.deleteAggregateImpact",{count:I.aggregateMembers})}):null]}):null}),e.jsx(de,{open:O.state==="blocked",onOpenChange:l=>{!l&&O.state==="blocked"&&O.reset()},title:s("providers.masterDetail.unsavedTitle"),description:s("providers.masterDetail.unsavedBody"),confirmLabel:s("providers.masterDetail.unsavedConfirm"),cancelLabel:s("common.actions.cancel"),onConfirm:()=>{O.state==="blocked"&&O.proceed()}}),e.jsx(de,{open:!!o,onOpenChange:l=>{l||E(null)},title:s("providers.masterDetail.unsavedTitle"),description:s("providers.masterDetail.unsavedBody"),confirmLabel:s("providers.masterDetail.unsavedConfirm"),cancelLabel:s("common.actions.cancel"),onConfirm:()=>{o&&v(o),E(null)}})]})}export{ht as default};
|