@chenpu17/cc-gw 0.12.0 → 0.13.0
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-B4KoKSAM.js → About-BJbSQIDc.js} +1 -1
- package/src/web/dist/assets/{ApiKeys-CwiStTlS.js → ApiKeys-C8I9ti-a.js} +1 -1
- package/src/web/dist/assets/{ConfirmDialog-cZsL-k-v.js → ConfirmDialog-BOe5HI56.js} +1 -1
- package/src/web/dist/assets/{Dashboard-khRk8U0-.js → Dashboard-C7n9KzBy.js} +1 -1
- package/src/web/dist/assets/{Events-BGQklKqB.js → Events-BGfmA69d.js} +1 -1
- package/src/web/dist/assets/{Help-B2MDKuj8.js → Help-DUrs56_n.js} +1 -1
- package/src/web/dist/assets/{Login-CrvH8tn2.js → Login-Dxeq-BfV.js} +1 -1
- package/src/web/dist/assets/{Logs-DoAgVjw3.js → Logs-VRdCNMkl.js} +1 -1
- package/src/web/dist/assets/{ProvidersWorkbench-CI7TbMf1.js → ProvidersWorkbench-DOGrU9Xl.js} +1 -1
- package/src/web/dist/assets/{Settings-BnqMqPol.js → Settings-CGxWfI_h.js} +1 -1
- package/src/web/dist/assets/{Setup-deGPdPcE.js → Setup-yKUdrXJQ.js} +1 -1
- package/src/web/dist/assets/{apiKeys-Ol_q3sZL.js → apiKeys-B-WRyKci.js} +1 -1
- package/src/web/dist/assets/{app-BBAnVEPg.js → app-BnQl39hq.js} +2 -2
- package/src/web/dist/assets/{gateway-B_xLF-Rk.js → gateway-DxCj_uok.js} +1 -1
- package/src/web/dist/assets/{landing-MsSWlQKc.js → landing-BuuM1jg8.js} +1 -1
- package/src/web/dist/assets/package-CKkVmaOi.js +1 -0
- package/src/web/dist/assets/{shared-BIsbTzWd.js → shared-DHBfRHZV.js} +1 -1
- package/src/web/dist/assets/{useAppMutation-Ds2SX3kE.js → useAppMutation-Cix9n50u.js} +1 -1
- package/src/web/dist/assets/{useProviderForm-CtZEenP9.js → useProviderForm-CsPV2Cqr.js} +1 -1
- package/src/web/dist/index.html +1 -1
- package/src/web/dist/landing.html +2 -2
- package/src/web/dist/assets/package-DHb277_G.js +0 -1
package/src/web/dist/assets/{ProvidersWorkbench-CI7TbMf1.js → ProvidersWorkbench-DOGrU9Xl.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as v,ax as Ft,j as e,ay as It,as as ut,ab as ke,az as bt,aA as tt,aB as vt,aC as jt,aD as yt,aE as Nt,aF as wt,aG as kt,aH as Ct,aI as St,aJ as Mt,aK as Pt,aL as At,aM as Bt,aN as Ht,aO as $t}from"./vendor-D2wC0h2o.js";import{d as zt}from"./router-CUBM_FND.js";import{C as _t}from"./ConfirmDialog-cZsL-k-v.js";import{P as Ut}from"./PageToolbar-BnDacS2l.js";import{t as ge,q as Ee,e as _e,B as A,b as qt,s as Vt,a as Qt,c as dt,T as Gt,f as Kt,g as Wt,h as Jt}from"./app-BBAnVEPg.js";import{B as re}from"./badge-RZTsODn-.js";import{c as je}from"./global-CJOj9WGx.js";import{d as mt,g as pt,a as ht,b as Xt,c as xt,e as gt,r as Yt,f as ze,m as Be,h as Zt,u as es,p as Et,i as ts,P as Oe,S as ss,B as as,M as rs,j as Dt,k as ns,l as os,C as Rt,O as Tt,n as ls,o as is}from"./useProviderForm-CtZEenP9.js";import{a as ds}from"./query-DVc6ZTRQ.js";import{g as Ie}from"./gateway-B_xLF-Rk.js";import{u as st}from"./useAppMutation-Ds2SX3kE.js";import{D as qe,A as Ve,a as Qe,b as Ge,c as Ke,d as We,e as Je}from"./DialogShell-BbpG8sot.js";import{L as ce,I as le}from"./label-Da-JMxO2.js";import{S as at,a as rt,b as nt,c as ot,d as Ae}from"./select-BTwqvh0l.js";import{S as lt}from"./switch-CeKtgMDT.js";import{u as W}from"./i18n-Dp-o1LhZ.js";import{D as Lt}from"./disclosure-CJdf1-ap.js";import{P as cs,c as us,b as ms}from"./popover-JpUYyIhi.js";import{C as Xe,a as Ye}from"./card-DhuLMeO9.js";import{a as ct}from"./PageState-U6DpaNu4.js";import{b as ps}from"./types-DYz12j32.js";import"./radix-B9EIjzyN.js";function hs(a){const{t,pushToast:r,config:s,setConfig:l,configQuery:p,customEndpoints:h,tabs:j,ensureConfig:g}=a,y=ds(),[u,i]=v.useState({}),[o,d]=v.useState({}),[w,m]=v.useState(null),[N,b]=v.useState({}),[M,L]=v.useState({}),[U,B]=v.useState({}),[Y,x]=v.useState(null),[P,C]=v.useState(null),[z,G]=v.useState(null),[K,O]=v.useState(!1),[J,pe]=v.useState(null),[E,F]=v.useState({}),[V,Se]=v.useState(null),ue=v.useRef(null),[He,fe]=v.useState(null),ye=n=>{ue.current=n,fe(n)},Ne=()=>{ue.current=null,fe(null)},ne=v.useMemo(()=>j.filter(n=>n.key!=="providers"),[j]);v.useEffect(()=>{if(!p.data)return;const n=p.data;i(f=>{const c=mt(n,h);if(!f||Object.keys(f).length===0)return c;const k={...c};for(const[D,I]of Object.entries(f)){if(!(D in c))continue;const $=pt(n,h,D);if(ht(I,$))k[D]=I;else{const se=new Map(I.map(X=>[X.source,X.id]));k[D]=c[D].map(X=>({...X,id:se.get(X.source)??X.id}))}}return k}),F(f=>{const c=Xt(n,h);if(!f||Object.keys(f).length===0)return c;const k={...c};for(const[D,I]of Object.entries(f)){if(!(D in c))continue;const $=xt(n,h,D);JSON.stringify(I)!==JSON.stringify($)&&(k[D]=I)}return k}),d({}),b(gt(n,h))},[p.data,h]);const Me=(s==null?void 0:s.providers)??[],Pe=v.useMemo(()=>{const n=[],f=new Set;for(const c of Me){const k=c.label&&c.label!==c.id?`${c.label} (${c.id})`:c.id,D=c.models??[];if(D.length>0)for(const $ of D){const se=`${c.id}:${$.id}`;f.has(se)||(f.add(se),n.push({value:se,label:`${k} · ${$.label??$.id}`,providerId:c.id,providerLabel:k,modelId:$.id,modelLabel:$.label??$.id,kind:"model",isDefault:c.defaultModel===$.id}))}else if(c.defaultModel){const $=`${c.id}:${c.defaultModel}`;f.has($)||(f.add($),n.push({value:$,label:`${k} · ${c.defaultModel}`,providerId:c.id,providerLabel:k,modelId:c.defaultModel,modelLabel:c.defaultModel,kind:"model",isDefault:!0}))}const I=`${c.id}:*`;f.has(I)||(f.add(I),n.push({value:I,label:t("settings.routing.providerPassthroughOption",{provider:k}),providerId:c.id,providerLabel:k,modelId:"*",modelLabel:"*",kind:"passthrough"}))}for(const c of Object.values(u).flat()){const k=c.target.trim();k&&!f.has(k)&&(f.add(k),n.push({value:k,label:k,modelId:k,modelLabel:k,kind:"custom"}))}return n},[Me,u,t]),$e=n=>s?pt(s,h,n):{},De=v.useMemo(()=>{const n={};for(const f of ne){const c=u[f.key]||[];n[f.key]=ht(c,$e(f.key))}return n},[s,h,u,ne]),Te=v.useMemo(()=>{const n={};if(!s)return n;for(const f of ne){const c=E[f.key];if(!c){n[f.key]=!1;continue}const k=xt(s,h,f.key);n[f.key]=JSON.stringify(c)!==JSON.stringify(k)}return n},[s,h,E,ne]),Le=(n,f,c)=>{F(k=>({...k,[n]:{...k[n]??{completion:null,reasoning:null,background:null,longContextThreshold:6e4},[f]:c}}))},R=async n=>{var k,D,I,$,se,X,Z,de;if(!g()||ue.current)return;const f=E[n];if(!f)return;const c={completion:(k=f.completion)!=null&&k.trim()?f.completion.trim():null,reasoning:(D=f.reasoning)!=null&&D.trim()?f.reasoning.trim():null,background:(I=f.background)!=null&&I.trim()?f.background.trim():null,longContextThreshold:Number.isFinite(f.longContextThreshold)&&f.longContextThreshold>0?Math.floor(f.longContextThreshold):s.defaults.longContextThreshold};Se(n),ye(n);try{const oe=h.find(ee=>ee.id===n);if(oe){const ee={...oe.routing??{},defaults:c,modelRoutes:(($=oe.routing)==null?void 0:$.modelRoutes)??{}};await _e.update(n,{routing:ee}),l(xe=>{if(!xe)return xe;const et=[...xe.customEndpoints??[]],it=et.findIndex(Ot=>Ot.id===n);return it===-1?xe:(et[it]={...et[it],routing:ee},{...xe,customEndpoints:et})}),await y.invalidateQueries({queryKey:Ee.customEndpoints.all()})}else{const ee=n,xe={...s,endpointRouting:{...s.endpointRouting??{},[ee]:{defaults:c,modelRoutes:((X=(se=s.endpointRouting)==null?void 0:se[ee])==null?void 0:X.modelRoutes)??(ee==="anthropic"?s.modelRoutes??{}:{}),compatibility:(de=(Z=s.endpointRouting)==null?void 0:Z[ee])==null?void 0:de.compatibility}}};await Ie.saveConfig(xe),l(xe)}F(ee=>({...ee,[n]:c})),r({title:t("workbench.defaults.saveSuccess"),variant:"success"}),p.refetch()}catch(oe){r({title:t("workbench.defaults.saveFailure",{message:ge(oe).message}),variant:"error"})}finally{Se(null),Ne()}},q=(n,f)=>{b(c=>({...c,[n]:f})),l(c=>{if(!c)return c;if(n==="anthropic"||n==="openai")return{...c,routingPresets:{...c.routingPresets,[n]:f}};const k=[...c.customEndpoints??[]],D=k.findIndex(I=>I.id===n);return D===-1?c:(k[D]={...k[D],routingPresets:f},{...c,customEndpoints:k})})},Q=(n,f)=>{L(c=>({...c,[n]:f})),f.trim()&&B(c=>({...c,[n]:null}))},T=async n=>{if(!g()||ue.current)return;const f=(M[n]??"").trim();if(!f){B(c=>({...c,[n]:t("modelManagement.validation.presetName")}));return}if((N[n]??[]).some(c=>c.name.toLowerCase()===f.toLowerCase())){B(c=>({...c,[n]:t("modelManagement.validation.presetDuplicate",{name:f})}));return}x(n),ye(n);try{const k=(await Be.savePreset(n,f)).presets??[];q(n,k),L(D=>({...D,[n]:""})),B(D=>({...D,[n]:null})),r({title:t("modelManagement.toast.presetSaved",{name:f}),variant:"success"})}catch(c){r({title:t("modelManagement.toast.presetSaveFailure",{message:ge(c).message}),variant:"error"})}finally{x(null),Ne(),p.refetch()}},ae=async(n,f)=>{if(g()&&!ue.current){C({endpoint:n,name:f.name}),ye(n);try{const k=(await Be.applyPreset(n,f.name)).config;l(k);const D=mt(k,h);i(I=>({...I,[n]:D[n]??[]})),b(gt(k,h)),n!=="anthropic"&&n!=="openai"&&await y.invalidateQueries({queryKey:Ee.customEndpoints.all()}),r({title:t("modelManagement.toast.presetApplySuccess",{name:f.name}),variant:"success"})}catch(c){r({title:t("modelManagement.toast.presetApplyFailure",{message:ge(c).message}),variant:"error"})}finally{C(null),Ne(),p.refetch()}}},be=async(n,f)=>{if(g()&&!ue.current){G({endpoint:n,name:f.name}),ye(n);try{const c=await Be.deletePreset(n,f.name);q(n,c.presets??[]),r({title:t("modelManagement.toast.presetDeleteSuccess",{name:f.name}),variant:"success"})}catch(c){r({title:t("modelManagement.toast.presetDeleteFailure",{message:ge(c).message}),variant:"error"})}finally{G(null),Ne(),p.refetch()}}},we=async n=>{const f=h.find(c=>c.id===n);if(!(!f||f.deletable===!1))try{await _e.delete(n),await y.invalidateQueries({queryKey:Ee.customEndpoints.all()}),l(c=>c&&{...c,customEndpoints:(c.customEndpoints??[]).filter(k=>k.id!==n)}),p.refetch(),r({title:t("modelManagement.deleteEndpointSuccess"),variant:"success"})}catch(c){const k=ge(c);r({title:t("modelManagement.deleteEndpointError",{error:k.message}),variant:"error"})}},S=n=>{i(f=>({...f,[n]:[...f[n]||[],{id:ze(),source:"",target:""}]})),d(f=>({...f,[n]:null}))},_=async(n,f)=>{if(g()&&!ue.current){O(!0),ye(n);try{if(n==="anthropic"||n==="openai"){const c=n,k=s.endpointRouting?{...s.endpointRouting}:{},D=k[c]??{defaults:s.defaults,modelRoutes:(c==="anthropic"?s.modelRoutes:{})??{}},I={defaults:D.defaults??s.defaults,modelRoutes:D.modelRoutes??{}},$={...s,endpointRouting:{...k,[c]:f?{...I,compatibility:{enabled:!0}}:{...I}}};await Ie.saveConfig($),l($)}else{const c=[...s.customEndpoints??[]],k=c.findIndex(se=>se.id===n);if(k===-1)throw new Error(t("modelManagement.toast.endpointNotFound"));const D=c[k],I=D.routing??{defaults:s.defaults,modelRoutes:{}};c[k]={...D,routing:f?{...I,compatibility:{enabled:!0}}:{defaults:I.defaults,modelRoutes:I.modelRoutes}};const $={...s,customEndpoints:c};await Ie.saveConfig($),l($)}r({title:t("modelManagement.toast.compatibilitySaved",{state:t(f?"common.status.enabled":"common.status.disabled")}),variant:"success"}),p.refetch()}catch(c){const k=ge(c);r({title:t("modelManagement.toast.compatibilitySaveFailure",{message:k.message}),variant:"error"})}finally{O(!1),Ne()}}},H=(n,f)=>{i(c=>{const k=c[n]||[];return k.some(D=>D.source.trim()===f.trim())?c:{...c,[n]:[...k,{id:ze(),source:f,target:""}]}}),d(c=>({...c,[n]:null}))},ve=(n,f,c,k)=>{i(D=>({...D,[n]:(D[n]||[]).map(I=>I.id===f?{...I,[c]:k}:I)})),d(D=>({...D,[n]:null}))},Ce=(n,f)=>{i(c=>({...c,[n]:(c[n]||[]).filter(k=>k.id!==f)})),d(c=>({...c,[n]:null}))},me=(n,f,c)=>{f!==c&&(i(k=>{const D=k[n]||[],I=D.findIndex(se=>se.id===f),$=D.findIndex(se=>se.id===c);return I===-1||$===-1?k:{...k,[n]:Ft(D,I,$)}}),d(k=>({...k,[n]:null})))},Ze=n=>{var c;if(!s)return;const f=(s.customEndpoints??h).find(k=>k.id===n);if(f)i(k=>{var D;return{...k,[n]:Object.entries(((D=f.routing)==null?void 0:D.modelRoutes)??{}).map(([I,$])=>({id:ze(),source:I,target:$}))}});else{const k=s.endpointRouting??{},D=n,I=D==="anthropic"?s.modelRoutes??{}:{},$=((c=k[D])==null?void 0:c.modelRoutes)??I;i(se=>({...se,[n]:Object.entries($).map(([X,Z])=>({id:ze(),source:X,target:Z}))}))}d(k=>({...k,[n]:null}))},te=st({mutationFn:async n=>(await Ie.saveConfig(n.nextConfig),n)}),ie=st({mutationFn:async n=>(await _e.update(n.endpoint,{routing:n.routing}),n)});return{endpointTabs:ne,routesByEndpoint:u,setRoutesByEndpoint:i,routeError:o,savingRouteFor:w,presetsByEndpoint:N,presetNameByEndpoint:M,presetErrorByEndpoint:U,savingPresetFor:Y,applyingPreset:P,deletingPreset:z,savingCompatibilityPolicy:K,writingEndpoint:He,presetDiffDialog:J,setPresetDiffDialog:pe,providerModelOptions:Pe,isDirtyByEndpoint:De,defaultsByEndpoint:E,isDefaultsDirtyByEndpoint:Te,savingDefaultsFor:V,handleDefaultsChange:Le,handleSaveDefaults:R,handlePresetNameChange:Q,handleSavePreset:T,handleApplyPreset:ae,handleDeletePreset:be,handleDeleteEndpoint:we,handleAddRoute:S,handleAddSuggestion:H,handleRouteChange:ve,handleRemoveRoute:Ce,handleReorderRules:me,handleResetRoutes:Ze,handleSaveRoutes:async n=>{var k,D,I,$,se;if(!g()||ue.current)return;const f=u[n]||[],c={};for(const X of f){const Z=X.source.trim(),de=X.target.trim();if(!(!Z&&!de)){if(!Z||!de){d(oe=>({...oe,[n]:t("settings.validation.routePair")}));return}if(c[Z]){d(oe=>({...oe,[n]:t("settings.validation.routeDuplicate",{model:Z})}));return}c[Z]=de}}d(X=>({...X,[n]:null})),m(n),ye(n);try{const X=h.find(Z=>Z.id===n);if(X){const Z={...X.routing??{},modelRoutes:c,defaults:((k=X.routing)==null?void 0:k.defaults)||s.defaults};await ie.mutateAsync({endpoint:n,routing:Z}),l(de=>{if(!de)return de;const oe=[...de.customEndpoints??[]],ee=oe.findIndex(xe=>xe.id===n);return ee===-1?de:(oe[ee]={...oe[ee],routing:Z},{...de,customEndpoints:oe})}),await y.invalidateQueries({queryKey:Ee.customEndpoints.all()})}else{const Z={...s,endpointRouting:{...s.endpointRouting??{},[n]:{defaults:((I=(D=s.endpointRouting)==null?void 0:D[n])==null?void 0:I.defaults)??s.defaults,modelRoutes:c,compatibility:(se=($=s.endpointRouting)==null?void 0:$[n])==null?void 0:se.compatibility}},modelRoutes:n==="anthropic"?c:s.modelRoutes??{}};await te.mutateAsync({endpoint:n,nextConfig:Z}),l(Z)}i(Z=>{const de=Z[n]??[],oe=new Map(de.map(ee=>[ee.source.trim(),ee.id]));return{...Z,[n]:Object.entries(c).map(([ee,xe])=>({id:oe.get(ee.trim())??ze(),source:ee,target:xe}))}}),r({title:t("modelManagement.toast.routesSaved"),variant:"success"}),p.refetch()}catch(X){r({title:t("modelManagement.toast.routesSaveFailure",{message:ge(X).message}),variant:"error"})}finally{m(null),Ne()}},handleCompatibilityEnabledChange:_,sanitizeDraftsForProvider:n=>{i(f=>{const c={};for(const[k,D]of Object.entries(f))c[k]=D.filter(I=>!Yt(I.target.trim(),n));return c})}}}function xs(a,t){const{t:r,pushToast:s,config:l,setConfig:p,configQuery:h,customEndpoints:j,ensureConfig:g}=a,{sanitizeDraftsForProvider:y}=t??{},[u,i]=v.useState(""),[o,d]=v.useState("all"),[w,m]=v.useState(!1),[N,b]=v.useState("create"),[M,L]=v.useState(void 0),[U,B]=v.useState(null),[Y,x]=v.useState({}),[P,C]=v.useState(!1),[z,G]=v.useState(null),[K,O]=v.useState(!0),[J,pe]=v.useState({}),[E,F]=v.useState(null),V=(l==null?void 0:l.providers)??[],Se=V.length,ue=v.useMemo(()=>V.filter(R=>{var ae;if(!(o==="all"||(R.type??"custom")===o))return!1;const Q=u.trim().toLowerCase();return Q?[R.id,R.label??"",R.baseUrl??"",R.defaultModel??"",...((ae=R.models)==null?void 0:ae.map(be=>be.id))??[]].join(" ").toLowerCase().includes(Q):!0}),[u,o,V]),He=v.useMemo(()=>{const R=new Map;for(const q of V){if(!q.defaultModel||!q.models)continue;const Q=q.models.find(T=>T.id===q.defaultModel);Q&&R.set(q.id,Zt(Q))}return R},[V]),fe=v.useMemo(()=>[{key:"anthropic-beta",value:"claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14",label:r("providers.testDialog.options.beta.label"),description:r("providers.testDialog.options.beta.description")}],[r]),ye=()=>{g()&&(b("create"),L(void 0),m(!0))},Ne=R=>{g()&&(b("edit"),L(R),m(!0))},ne=async R=>{if(!l)throw new Error(r("settings.toast.missingConfig"));const q=N==="create"?[...V,R]:V.map(T=>M&&T.id===M.id?{...R,id:M.id}:T),Q={...l,providers:q};await Ie.saveConfig(Q),p(Q),h.refetch(),s({title:N==="create"?r("providers.toast.createSuccess",{name:R.label||R.id}):r("providers.toast.updateSuccess",{name:R.label||R.id}),variant:"success"})},Me=(R,q)=>{x(Q=>({...Q,[R]:q}))},Pe=async(R,q)=>{B(R.id);try{const Q=q&&(q.headers||q.query)?{headers:q.headers&&Object.keys(q.headers).length>0?q.headers:void 0,query:q.query&&q.query.trim().length>0?q.query.trim():void 0}:void 0,T=await Be.testProvider(R.id,Q);if(T.ok){Me(R.id,{ok:!0,status:T.status,statusText:T.statusText,durationMs:T.durationMs,testedAt:Date.now()}),s({title:r("providers.toast.testSuccess"),description:r("providers.toast.testSuccessDesc",{status:T.status,duration:T.durationMs?`${T.durationMs} ms`:"—"}),variant:"success"});return}Me(R.id,{ok:!1,status:T.status,statusText:T.statusText,durationMs:T.durationMs,message:`${T.status} ${T.statusText}`,testedAt:Date.now()}),s({title:r("providers.toast.testFailure",{message:`${T.status} ${T.statusText}`}),variant:"error"})}catch(Q){const T=ge(Q),ae=T.status?`${T.status} ${T.message}`:T.message;Me(R.id,{ok:!1,status:T.status,message:ae,testedAt:Date.now()}),s({title:r("providers.toast.testFailure",{message:ae}),variant:"error"})}finally{B(null)}},$e=R=>{var we,S;if(!(!!((we=R.defaultModel)!=null&&we.trim())||!!((S=R.models)!=null&&S.some(_=>_.id.trim().length>0)))){F(R);return}if(R.type!=="anthropic"){Pe(R);return}const Q=R.extraHeaders??{},T=new Map(fe.map(_=>[_.key.toLowerCase(),_])),ae={};let be=!0;for(const _ of fe){const H=Object.entries(Q).find(([me])=>me.toLowerCase()===_.key.toLowerCase());if(!H)continue;const[ve,Ce]=H;String(Ce??"")!==_.value&&(be=!1,ae[ve]=String(Ce??""))}for(const[_,H]of Object.entries(Q))T.has(_.toLowerCase())||(ae[_]=String(H??""));pe(ae),O(be),G(R),C(!0)},De=()=>{C(!1),G(null),O(!0),pe({})};return{providers:V,providerCount:Se,filteredProviders:ue,providerSearch:u,setProviderSearch:i,providerTypeFilter:o,setProviderTypeFilter:d,defaultLabels:He,drawerOpen:w,setDrawerOpen:m,drawerMode:N,setDrawerMode:b,editingProvider:M,setEditingProvider:L,testingProviderId:U,testResults:Y,testDialogOpen:P,testDialogProvider:z,testDialogUsePreset:K,setTestDialogUsePreset:O,testDialogPreservedExtras:J,noModelDialogProvider:E,setNoModelDialogProvider:F,anthropicTestHeaderOptions:fe,handleOpenCreate:ye,handleOpenEdit:Ne,handleProviderSubmit:ne,handleDeleteProvider:async R=>{var _,H,ve,Ce,me,Ze;if(!g())return;const q=V.filter(te=>te.id!==R.id).map(te=>{if(te.type!=="aggregate"||!te.models)return te;const ie=te.models.map(he=>({...he,members:(he.members??[]).filter(n=>n.target.split(":")[0]!==R.id)})).filter(he=>(he.members??[]).length>0),Re=ie.some(he=>he.id===te.defaultModel)?te.defaultModel:void 0;return{...te,models:ie,defaultModel:Re}}),Q=te=>{const ie={};if(!te)return ie;for(const[Re,he]of Object.entries(te)){if(!he)continue;const[n]=he.split(":");n&&n===R.id||he===R.id||(ie[Re]=he)}return ie},T=(l==null?void 0:l.endpointRouting)??{},ae=Q(((_=T.anthropic)==null?void 0:_.modelRoutes)??(l==null?void 0:l.modelRoutes)??{}),be=Q(((H=T.openai)==null?void 0:H.modelRoutes)??{}),we=((l==null?void 0:l.customEndpoints)??j).map(te=>{const ie=te.routing,Re=ie==null?void 0:ie.modelRoutes;return Re?{...te,routing:{...ie,defaults:ie.defaults??l.defaults,modelRoutes:Q(Re)}}:te}),S={...l,providers:q,modelRoutes:ae,customEndpoints:we,endpointRouting:{anthropic:{defaults:((ve=T.anthropic)==null?void 0:ve.defaults)??l.defaults,modelRoutes:ae,compatibility:(Ce=T.anthropic)==null?void 0:Ce.compatibility},openai:{defaults:((me=T.openai)==null?void 0:me.defaults)??l.defaults,modelRoutes:be,compatibility:(Ze=T.openai)==null?void 0:Ze.compatibility}}};try{await Ie.saveConfig(S),p(S),y==null||y(R.id),(M==null?void 0:M.id)===R.id&&(m(!1),L(void 0),b("create")),s({title:r("providers.toast.deleteSuccess",{name:R.label||R.id}),variant:"success"}),h.refetch()}catch(te){s({title:r("providers.toast.deleteFailure",{message:ge(te).message}),variant:"error"})}},handleTestConnection:Pe,initiateTestConnection:$e,closeTestDialog:De,confirmTestDialog:async()=>{if(!z)return;const R={};if(K)for(const T of fe)R[T.key]=T.value;const q=new Map(fe.map(T=>[T.key.toLowerCase(),T]));for(const[T,ae]of Object.entries(J))q.get(T.toLowerCase())&&K||(R[T]=ae);const Q=z;De(),await Pe(Q,{headers:Object.keys(R).length>0?R:void 0})}}}const gs=["anthropic","openai-auto","openai-chat","openai-responses"];function fs({open:a,endpoint:t,onClose:r,onSuccess:s}){const{t:l}=W(),[p,h]=v.useState({id:"",label:"",paths:[{path:"",protocol:"openai-auto"}],enabled:!0});v.useEffect(()=>{if(a){if(t){const m=t.paths&&t.paths.length>0?t.paths:t.path&&t.protocol?[{path:t.path,protocol:t.protocol}]:[{path:"",protocol:"openai-auto"}];h({id:t.id,label:t.label,paths:m,enabled:t.enabled!==!1});return}h({id:"",label:"",paths:[{path:"",protocol:"openai-auto"}],enabled:!0})}},[t,a]);const j=st({mutationFn:_e.create,invalidateKeys:[Ee.customEndpoints.all()],successToast:()=>({title:l("modelManagement.createEndpointSuccess")}),errorToast:m=>({title:l("modelManagement.createEndpointError",{error:m.message})}),onSuccess:async()=>{s(),r()}}),g=st({mutationFn:m=>_e.update(m.id,m.updates),invalidateKeys:[Ee.customEndpoints.all()],successToast:()=>({title:l("modelManagement.updateEndpointSuccess")}),errorToast:m=>({title:l("modelManagement.updateEndpointError",{error:m.message})}),onSuccess:async()=>{s(),r()}}),y=()=>{h(m=>({...m,paths:[...m.paths,{path:"",protocol:"anthropic"}]}))},u=m=>{p.paths.length!==1&&h(N=>({...N,paths:N.paths.filter((b,M)=>M!==m)}))},i=(m,N,b)=>{h(M=>{const L=[...M.paths];return L[m]={...L[m],[N]:b},{...M,paths:L}})},o=m=>{if(m==null||m.preventDefault(),!p.id.trim()||!p.label.trim())return;for(const b of p.paths)if(!b.path.trim())return;const N=p.paths.map(b=>({path:b.path.trim(),protocol:b.protocol}));if(t){g.mutate({id:t.id,updates:{label:p.label.trim(),paths:N,enabled:p.enabled}});return}j.mutate({id:p.id.trim(),label:p.label.trim(),paths:N,enabled:p.enabled})},d=j.isPending||g.isPending,w=p.paths.length===0?l("modelManagement.atLeastOnePath"):!p.id.trim()||!p.label.trim()?l("modelManagement.endpointValidationError"):p.paths.some(m=>!m.path.trim())?l("modelManagement.pathValidationError"):null;return e.jsx(qe,{open:a,onOpenChange:m=>!m&&r(),children:e.jsxs(Ve,{className:"max-w-lg",onInteractOutside:m=>m.preventDefault(),children:[e.jsxs(Qe,{children:[e.jsx(Ge,{children:l(t?"modelManagement.editEndpoint":"modelManagement.createEndpoint")}),e.jsx(Ke,{className:"truncate font-mono text-xs",children:t?t.id:l("modelManagement.endpointRoutingHint")})]}),e.jsx(We,{children:e.jsxs("form",{id:"endpoint-form",onSubmit:o,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ce,{children:[l("modelManagement.endpointId")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(le,{value:p.id,onChange:m=>h(N=>({...N,id:m.target.value})),placeholder:l("modelManagement.endpointIdPlaceholder"),disabled:!!t,required:!0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l("modelManagement.endpointIdHint")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ce,{children:[l("modelManagement.endpointLabel")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(le,{value:p.label,onChange:m=>h(N=>({...N,label:m.target.value})),placeholder:l("modelManagement.endpointLabelPlaceholder"),required:!0})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ce,{children:[l("modelManagement.endpointPaths")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsxs(A,{type:"button",variant:"ghost",size:"sm",onClick:y,children:[e.jsx(It,{className:"mr-1 h-3 w-3"}),l("modelManagement.addPath")]})]}),e.jsx("div",{className:"space-y-3",children:p.paths.map((m,N)=>e.jsxs("div",{className:"space-y-2 rounded-xl border border-transparent bg-card p-3 shadow-[var(--surface-shadow)]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(le,{value:m.path,onChange:b=>i(N,"path",b.target.value),placeholder:l("modelManagement.endpointPathPlaceholder"),required:!0}),e.jsxs(at,{value:m.protocol,onValueChange:b=>i(N,"protocol",b),children:[e.jsx(rt,{children:e.jsx(nt,{})}),e.jsx(ot,{children:gs.map(b=>e.jsx(Ae,{value:b,children:l(b==="anthropic"?"modelManagement.protocolAnthropic":b==="openai-auto"?"modelManagement.protocolOpenAI":b==="openai-chat"?"modelManagement.protocolOpenAIChat":"modelManagement.protocolOpenAIResponses")},b))})]})]}),p.paths.length>1?e.jsx(A,{type:"button",variant:"ghost",size:"sm",onClick:()=>u(N),className:"text-destructive",children:e.jsx(ut,{className:"h-4 w-4"})}):null]}),e.jsxs("div",{className:"space-y-1 text-xs text-muted-foreground",children:[N===0?e.jsx("p",{children:l("modelManagement.endpointPathHint")}):null,e.jsx("p",{children:l(`modelManagement.protocolHints.${m.protocol}`)})]})]},`${m.protocol}-${N}`))}),w?e.jsx("p",{className:"text-xs text-destructive",children:w}):null]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(lt,{id:"endpoint-enabled",checked:p.enabled,onCheckedChange:m=>h(N=>({...N,enabled:m}))}),e.jsx(ce,{htmlFor:"endpoint-enabled",children:l("modelManagement.endpointEnabled")})]}),t?null:e.jsx("div",{className:"rounded-xl bg-accent p-4",children:e.jsx("p",{className:"text-sm text-primary",children:l("modelManagement.endpointRoutingHint")})})]})}),e.jsxs(Je,{children:[e.jsx(A,{variant:"outline",onClick:r,disabled:d,children:l("common.cancel")}),e.jsx(A,{type:"submit",form:"endpoint-form",disabled:d,children:l(d?"common.saving":t?"common.save":"common.create")})]})]})})}function bs({open:a,provider:t,onClose:r,onEdit:s}){const{t:l}=W();return t?e.jsx(qe,{open:a,onOpenChange:p=>!p&&r(),children:e.jsxs(Ve,{className:"max-w-md",children:[e.jsxs(Qe,{children:[e.jsx(Ge,{children:l("providers.noModelDialog.title")}),e.jsx(Ke,{children:l("providers.noModelDialog.subtitle",{name:t.label||t.id})})]}),e.jsxs(We,{className:"space-y-4",children:[e.jsx("div",{className:"rounded-xl bg-accent p-4 text-sm text-primary",children:l("providers.noModelDialog.description")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l("providers.noModelDialog.hint")})]}),e.jsxs(Je,{children:[e.jsx(A,{variant:"outline",onClick:r,children:l("common.actions.close")}),e.jsx(A,{onClick:()=>s(t),children:l("providers.noModelDialog.primary")})]})]})}):null}function vs({dialog:a,currentRoutes:t,onConfirm:r,onClose:s}){const{t:l}=W();if(!a)return null;const{endpoint:p,preset:h}=a,j=h.modelRoutes??{},g={};for(const w of t){const m=w.source.trim(),N=w.target.trim();m&&N&&(g[m]=N)}const y=new Set([...Object.keys(g),...Object.keys(j)]),u=[],i=[],o=[];for(const w of y){const m=w in g,N=w in j;N&&!m?u.push([w,j[w]]):m&&!N?i.push([w,g[w]]):m&&N&&g[w]!==j[w]&&o.push([w,g[w],j[w]])}const d=u.length>0||i.length>0||o.length>0;return e.jsx(qe,{open:!0,onOpenChange:w=>!w&&s(),children:e.jsxs(Ve,{className:"max-w-2xl",children:[e.jsxs(Qe,{children:[e.jsx(Ge,{children:l("modelManagement.presets.diffTitle")}),e.jsx(Ke,{children:l("modelManagement.presets.diffDescription",{name:h.name})})]}),e.jsx(We,{children:d?e.jsxs("div",{className:"max-h-80 space-y-2 rounded-xl bg-secondary/50 p-3 text-sm",children:[u.map(([w,m])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-success-bg px-2 py-1.5 text-success",children:[e.jsx(re,{variant:"outline",className:"border-success/30 text-xs",children:l("modelManagement.presets.diffAdded")}),e.jsx("span",{className:"truncate",children:w}),e.jsx(ke,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:m})]},`add-${w}`)),i.map(([w,m])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-error-bg px-2 py-1.5 text-error",children:[e.jsx(re,{variant:"outline",className:"border-error/30 text-xs",children:l("modelManagement.presets.diffRemoved")}),e.jsx("span",{className:"truncate",children:w}),e.jsx(ke,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:m})]},`rm-${w}`)),o.map(([w,m,N])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-warning-bg px-2 py-1.5 text-warning",children:[e.jsx(re,{variant:"outline",className:"border-warning/30 text-xs",children:l("modelManagement.presets.diffChanged")}),e.jsx("span",{className:"truncate",children:w}),e.jsx(ke,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate line-through opacity-60",children:m}),e.jsx(ke,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:N})]},`chg-${w}`))]}):e.jsx("p",{className:"rounded-xl bg-secondary/50 py-8 text-center text-sm text-muted-foreground",children:l("modelManagement.presets.diffEmpty")})}),e.jsxs(Je,{children:[e.jsx(A,{variant:"outline",onClick:s,children:l("common.cancel")}),e.jsx(A,{onClick:()=>r(p,h),disabled:!d,children:l("modelManagement.presets.diffConfirm")})]})]})})}const ft=6;function Ue({value:a,onChange:t,options:r,disabled:s,placeholder:l,ariaLabel:p}){const{t:h}=W(),j=v.useId(),[g,y]=v.useState(!1),[u,i]=v.useState(""),o=v.useRef(null),d=v.useRef(!1),[w,m]=qt(Vt.modelManagement.recentRouteTargets,[]),N=v.useMemo(()=>{const x=new Map;for(const P of r)x.set(P.value,P);return x},[r]),b=(x,P)=>P?[x.label,x.value,x.providerId??"",x.providerLabel??"",x.modelId??"",x.modelLabel??""].join(" ").toLowerCase().includes(P):!0,M=v.useMemo(()=>{const x=u.trim().toLowerCase(),P=r.filter(O=>b(O,x)),C=w.map(O=>N.get(O)??(x?void 0:{value:O,label:O,kind:"custom"})).filter(O=>!!O).filter(O=>b(O,x)).slice(0,ft),z=[];C.length>0&&z.push({key:"recent",label:h("modelManagement.targetPicker.recent"),options:C});const G=new Map,K=[];for(const O of P){if(O.kind==="custom"||!O.providerId){K.push(O);continue}const J=`provider:${O.providerId}`,pe=G.get(J);pe?pe.options.push(O):G.set(J,{key:J,label:O.providerLabel??O.providerId,options:[O]})}return z.push(...G.values()),K.length>0&&z.push({key:"custom",label:h("modelManagement.targetPicker.custom"),options:K,muted:!0}),z},[N,r,w,u,h]),L=M.reduce((x,P)=>x+P.options.length,0),U=x=>{t(x),m(P=>[x,...P.filter(C=>C!==x)].slice(0,ft)),i(""),d.current=!0,typeof document<"u"&&document.activeElement instanceof HTMLElement&&document.activeElement.blur(),y(!1),typeof window<"u"?window.requestAnimationFrame(()=>{d.current=!1}):d.current=!1},B=x=>x.kind==="passthrough"?h("modelManagement.targetPicker.passthrough"):x.kind==="custom"?h("modelManagement.targetPicker.customValue"):h("modelManagement.targetPicker.model"),Y=x=>x.kind==="passthrough"||x.kind==="custom"?x.label:x.modelLabel??x.label;return e.jsxs(cs,{open:g,onOpenChange:x=>{x&&d.current||(y(x),x&&i(""))},children:[e.jsx(us,{asChild:!0,children:e.jsx(le,{value:a,onChange:x=>{t(x.target.value),i(x.target.value),g||y(!0)},onFocus:()=>{i(""),y(!0)},onClick:()=>{g||y(!0)},placeholder:l,disabled:s,autoComplete:"off",role:"combobox","aria-label":p,"aria-expanded":g,"aria-controls":j,"aria-autocomplete":"list"})}),e.jsxs(ms,{className:"flex max-h-[min(28rem,var(--radix-popover-content-available-height))] flex-col overflow-hidden rounded-xl border border-[color:var(--surface-border)] bg-popover p-0 shadow-[var(--surface-shadow-lg)]",style:{width:"max(var(--radix-popover-trigger-width), 360px)"},align:"start",onOpenAutoFocus:x=>{var P;x.preventDefault(),(P=o.current)==null||P.focus()},onCloseAutoFocus:x=>{x.preventDefault()},children:[e.jsxs("div",{className:"space-y-2 border-b border-border px-3 py-3",children:[e.jsx(le,{ref:o,value:u,onChange:x=>i(x.target.value),placeholder:h("modelManagement.targetPicker.searchPlaceholder"),className:"h-9",autoComplete:"off"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:u.trim()?h("modelManagement.targetPicker.matchCount",{count:L}):h("modelManagement.targetPicker.helper")})]}),L===0?e.jsx("div",{className:"px-3 py-4 text-center text-xs text-muted-foreground",children:h("common.noMatches")}):e.jsx("div",{id:j,role:"listbox",className:"min-h-0 flex-1 overflow-y-auto p-1.5",children:M.map(x=>e.jsxs("div",{className:"py-1",children:[e.jsxs("div",{className:je("sticky top-0 z-10 flex items-center justify-between bg-popover px-2 py-1 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",x.muted&&"opacity-80"),children:[e.jsx("span",{className:"truncate",children:x.label}),e.jsx("span",{children:x.options.length})]}),e.jsx("div",{className:"space-y-1",children:x.options.map(P=>e.jsxs("button",{type:"button",role:"option","aria-selected":P.value===a.trim(),className:je("flex w-full min-w-0 items-center gap-2 rounded-lg px-3 py-2 text-left text-sm transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",P.value===a.trim()&&"bg-accent text-accent-foreground"),onMouseDown:C=>{C.preventDefault()},onClick:()=>U(P.value),children:[e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate font-medium",children:Y(P)}),e.jsx("span",{className:"block truncate text-xs text-muted-foreground",children:P.value})]}),e.jsxs("span",{className:"flex shrink-0 items-center gap-1",children:[P.isDefault?e.jsx(re,{variant:"secondary",className:"text-[10px]",children:h("modelManagement.targetPicker.default")}):null,e.jsx(re,{variant:P.kind==="passthrough"?"outline":"secondary",className:"text-[10px]",children:B(P)})]})]},`${x.key}-${P.value}`))})]},x.key))})]})]})}function js(a){const{t}=W(),{form:r,errors:s,onModelIdChange:l,onAddModel:p,onRemoveModel:h,onAddMember:j,onRemoveMember:g,onMemberTargetChange:y,onReorderMembers:u,onModelFailoverChange:i,memberOptions:o}=a;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(A,{type:"button",variant:"outline",size:"sm",onClick:p,className:"bg-card text-xs",children:t("providers.drawer.fields.addModel")})]}),s.models?e.jsx("p",{className:"text-xs text-destructive",children:s.models}):null,e.jsxs("div",{className:"space-y-4",children:[r.models.map((d,w)=>{var m,N;return e.jsxs("div",{"data-testid":"aggregate-model-card",className:"rounded-xl border border-transparent bg-card p-4 shadow-[var(--surface-shadow)]",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(ce,{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(le,{value:d.id,onChange:b=>l(w,b.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(ys,{modelKey:d._key,members:d.members,options:o,error:(m=s.members)==null?void 0:m[d._key],onAddMember:j,onRemoveMember:g,onMemberTargetChange:y,onReorderMembers:u}),e.jsxs(Lt,{summary:t("providers.aggregate.drawer.failoverTitle"),className:"mt-4 rounded-xl 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(ce,{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(le,{type:"number",min:1,value:d.failover.consecutiveFailures,onChange:b=>i(d._key,{consecutiveFailures:b.target.value}),placeholder:t("providers.aggregate.drawer.consecutiveFailuresHint")})]}),e.jsxs(ce,{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(le,{type:"number",min:1,max:86400,value:d.failover.cooldownSeconds,onChange:b=>i(d._key,{cooldownSeconds:b.target.value}),placeholder:t("providers.aggregate.drawer.cooldownSecondsHint")})]}),e.jsxs(ce,{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(le,{type:"number",min:1,value:d.failover.failureWindowSeconds,onChange:b=>i(d._key,{failureWindowSeconds:b.target.value}),placeholder:t("providers.aggregate.drawer.failureWindowSecondsHint")})]})]}),e.jsxs(ce,{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(le,{value:d.failover.triggerStatusCodes,onChange:b=>i(d._key,{triggerStatusCodes:b.target.value}),placeholder:t("providers.aggregate.drawer.triggerStatusCodesHint"),className:"font-mono text-xs",spellCheck:!1})]}),(N=s.failover)!=null&&N[d._key]?e.jsx("p",{className:"text-xs text-destructive",children:s.failover[d._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(A,{type:"button",variant:"ghost",size:"sm",className:"h-auto px-2 text-destructive",onClick:()=>h(w),children:t("providers.drawer.fields.removeModel")})})]},d._key)}),r.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 ys({modelKey:a,members:t,options:r,error:s,onAddMember:l,onRemoveMember:p,onMemberTargetChange:h,onReorderMembers:j}){const{t:g}=W(),y=bt(tt(yt,{activationConstraint:{distance:6}}),tt(jt,{coordinateGetter:vt})),u=i=>{const{active:o,over:d}=i;!d||o.id===d.id||j(a,String(o.id),String(d.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:g("providers.aggregate.drawer.membersTitle")}),e.jsx(A,{type:"button",variant:"outline",size:"sm","data-testid":"aggregate-add-member",onClick:()=>l(a),className:"h-7 bg-card px-2.5 text-[11px]",children:g("providers.aggregate.drawer.addMember")})]}),s?e.jsx("p",{className:"text-xs text-destructive",children:s}):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:g("providers.aggregate.drawer.memberEmptyHint")}):e.jsx(Nt,{sensors:y,collisionDetection:wt,onDragEnd:u,children:e.jsx(kt,{items:t.map(i=>i._key),strategy:Ct,children:e.jsx("div",{className:"flex flex-col gap-1.5",children:t.map((i,o)=>e.jsx(Ns,{modelKey:a,member:i,index:o,options:r,onRemoveMember:p,onMemberTargetChange:h},i._key))})})}),e.jsx("p",{className:"text-[11px] leading-relaxed text-muted-foreground",children:g("providers.aggregate.drawer.memberHint")})]})}function Ns({modelKey:a,member:t,index:r,options:s,onRemoveMember:l,onMemberTargetChange:p}){const{t:h}=W(),{attributes:j,listeners:g,setNodeRef:y,setActivatorNodeRef:u,transform:i,transition:o,isDragging:d}=St({id:t._key});return e.jsxs("div",{ref:y,"data-testid":"aggregate-member-row",style:{transform:Pt.Transform.toString(i),transition:o},className:je("flex items-center gap-2 border border-border bg-card p-2",d&&"z-10 opacity-60 shadow-[var(--surface-shadow-lg)]"),children:[e.jsx("button",{ref:u,type:"button","data-testid":"aggregate-member-grip","aria-label":h("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",...j,...g,children:e.jsx(Mt,{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:r+1}),r===0?e.jsx(re,{variant:"outline",className:"shrink-0 px-1.5 text-[10px] font-normal text-muted-foreground",children:h("providers.aggregate.drawer.primaryBadge")}):null,e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(Ue,{value:t.target,onChange:w=>p(a,t._key,w),options:s,placeholder:h("providers.aggregate.drawer.memberPlaceholder"),ariaLabel:h("providers.aggregate.drawer.memberTarget")})}),e.jsx(A,{variant:"ghost",size:"icon","data-testid":"aggregate-member-delete",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>l(a,t._key),"aria-label":h("common.delete"),children:e.jsx(ut,{className:"h-3.5 w-3.5","aria-hidden":!0})})]})}function ws({open:a,providerId:t,providerName:r,existingModelIds:s,draft:l,onImport:p,onClose:h}){const{t:j}=W(),{pushToast:g}=Qt(),[y,u]=v.useState({phase:"loading"}),[i,o]=v.useState(""),[d,w]=v.useState(new Set),m=v.useRef(l);m.current=l,v.useEffect(()=>{if(!a)return;u({phase:"loading"}),o(""),w(new Set);let x=!1;return Be.probeModels(t,m.current).then(P=>{var C;x||(P.ok&&P.models?u({phase:"ready",models:P.models}):u({phase:"error",message:((C=P.statusText)==null?void 0:C.trim())||j("providers.drawer.probe.failedFallback"),status:P.status>0?P.status:void 0}))}).catch(P=>{x||u({phase:"error",message:ge(P).message})}),()=>{x=!0}},[a,t,j]);const N=v.useMemo(()=>new Set(s),[s]),b=v.useMemo(()=>{if(y.phase!=="ready")return[];const x=i.trim().toLowerCase();return x?y.models.filter(P=>P.id.toLowerCase().includes(x)||(P.label??"").toLowerCase().includes(x)):y.models},[y,i]),M=v.useMemo(()=>b.map(x=>x.id).filter(x=>!N.has(x)),[b,N]),L=x=>{w(P=>{const C=new Set(P);return C.has(x)?C.delete(x):C.add(x),C})},U=()=>{w(x=>new Set([...x,...M]))},B=()=>{w(new Set)},Y=()=>{if(y.phase!=="ready"||d.size===0)return;const x=y.models.filter(P=>d.has(P.id));p(x),g({title:j("providers.drawer.probe.importSuccess",{count:x.length}),variant:"success"}),h()};return e.jsx(qe,{open:a,onOpenChange:x=>!x&&h(),children:e.jsxs(Ve,{className:"max-w-2xl",children:[e.jsxs(Qe,{children:[e.jsx(Ge,{children:j("providers.drawer.probe.title")}),e.jsx(Ke,{children:j("providers.drawer.probe.subtitle",{name:r})})]}),e.jsxs(We,{className:"space-y-4",children:[y.phase==="loading"?e.jsx("p",{className:"rounded-xl bg-secondary/50 px-4 py-6 text-center text-sm text-muted-foreground",children:j("providers.drawer.probe.loading")}):null,y.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:j("providers.drawer.probe.failedTitle")}),y.status?e.jsxs(re,{variant:"warning",className:"shrink-0",children:["HTTP ",y.status]}):null]}),e.jsx("p",{className:"break-words text-xs leading-relaxed text-warning",children:y.message}),e.jsx("p",{className:"text-xs text-muted-foreground",children:j("providers.drawer.probe.failedHint")})]}):null,y.phase==="ready"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(le,{value:i,onChange:x=>o(x.target.value),placeholder:j("providers.drawer.probe.searchPlaceholder"),className:"h-9"}),e.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:j("providers.drawer.probe.totalCount",{count:y.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(A,{type:"button",variant:"outline",size:"sm",className:"h-auto bg-card px-2 py-1 text-xs",onClick:U,disabled:M.length===0,children:j("providers.drawer.probe.selectAll")}),e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"h-auto bg-card px-2 py-1 text-xs",onClick:B,disabled:d.size===0,children:j("providers.drawer.probe.clearSelection")})]}),e.jsx("span",{className:"text-muted-foreground",children:j("providers.drawer.probe.selectedCount",{count:d.size})})]}),b.length===0?e.jsx("p",{className:"rounded-xl bg-secondary/50 px-4 py-6 text-center text-sm text-muted-foreground",children:j("providers.drawer.probe.emptyResult")}):e.jsx("div",{className:"grid max-h-80 gap-1 overflow-y-auto",children:b.map(x=>{const P=N.has(x.id),C=d.has(x.id);return e.jsxs("label",{className:je("flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2.5 transition-colors",P?"cursor-not-allowed opacity-60":"cursor-pointer hover:border-primary/20 hover:bg-accent/50",C&&"border-primary/30 bg-primary/10"),children:[e.jsx("input",{type:"checkbox",className:"h-4 w-4 shrink-0 rounded border-input accent-primary",checked:C,disabled:P,onChange:()=>L(x.id)}),e.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-xs",children:x.id}),x.label?e.jsx("span",{className:"shrink-0 truncate text-xs text-muted-foreground",children:x.label}):null,P?e.jsx(re,{variant:"secondary",className:"shrink-0",children:j("providers.drawer.probe.imported")}):null]},x.id)})})]}):null]}),e.jsxs(Je,{children:[e.jsx(A,{variant:"outline",onClick:h,children:j("common.actions.cancel")}),e.jsx(A,{onClick:Y,disabled:y.phase!=="ready"||d.size===0,children:j("providers.drawer.probe.importAction",{count:d.size})})]})]})})}function ks({open:a,mode:t,provider:r,existingProviderIds:s,allProviders:l,onClose:p,onSubmit:h,testResult:j,testing:g,onTest:y,onDelete:u}){const{t:i}=W(),o=es({mode:t,provider:r,existingProviderIds:s,providers:l}),{form:d,errors:w,advancedOpen:m,providerIdRef:N}=o,[b,M]=v.useState(!1),[L,U]=v.useState(null),[B,Y]=v.useState("basics"),[x,P]=v.useState(!1),[C,z]=v.useState(!1),[G,K]=v.useState(null),O=v.useRef(null),J=v.useRef(null);v.useEffect(()=>{a&&(o.resetForm(),U(null),M(!1),Y("basics"),P(!1),z(!1),K(null))},[a,r,t,o.resetForm]);const pe=v.useRef(p);pe.current=p,v.useEffect(()=>{if(!a)return;const S=_=>{_.key==="Escape"&&(document.querySelector('[role="dialog"][data-state="open"], [role="listbox"][data-state="open"], [data-radix-popper-content-wrapper]')||pe.current())};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[a]),v.useEffect(()=>{if(a){if(t==="create"&&N.current){N.current.focus();return}J.current&&J.current.focus()}},[a,t]);const E=t==="create",F=d.type==="aggregate",V=v.useMemo(()=>d.models.filter(S=>S.id.trim().length>0),[d.models]),Se=v.useMemo(()=>Et(d.type,i),[d.type,i]),ue=v.useMemo(()=>d.models.reduce((S,_)=>S+_.members.filter(H=>H.target.trim().length>0).length,0),[d.models]),He=d.label.trim()||d.id.trim()||i("providers.drawer.summary.untitled"),fe=v.useMemo(()=>F?[{label:i("providers.drawer.summary.type"),value:Se},{label:i("providers.drawer.summary.models"),value:V.length.toLocaleString()},{label:i("providers.aggregate.drawer.summaryMembers"),value:ue.toLocaleString()}]:[{label:i("providers.drawer.summary.type"),value:Se},{label:i("providers.drawer.summary.auth"),value:ts(d.type,d.authMode,i)},{label:i("providers.drawer.summary.models"),value:V.length.toLocaleString()}],[F,V.length,ue,d.authMode,d.type,Se,i]),ye=v.useMemo(()=>{var _;const S=[];for(const H of l){if(H.type==="aggregate")continue;const ve=H.label&&H.label!==H.id?`${H.label} (${H.id})`:H.id,Ce=(_=H.models)!=null&&_.length?H.models:H.defaultModel?[{id:H.defaultModel}]:[];for(const me of Ce)S.push({value:`${H.id}:${me.id}`,label:`${ve} · ${me.label??me.id}`,providerId:H.id,providerLabel:ve,modelId:me.id,modelLabel:me.label??me.id,kind:"model"})}return S},[l]),Ne=async()=>{U(null);const S=o.validateErrors();if(Object.keys(S).length>0){S.baseUrl||S.id||S.extraHeaders?(Y("basics"),S.extraHeaders&&o.setAdvancedOpen(!0)):(S.models||S.members||S.failover)&&Y("models");return}M(!0);try{const _=o.serialize();await h(_)}catch(_){U(i("providers.drawer.toast.saveFailure",{message:ge(_).message})),M(!1);return}M(!1),p()};if(!a)return null;const ne=Oe.findIndex(S=>S.id===B),Me=ne===Oe.length-1,Pe=d.id.trim(),$e=Pe.length>0&&(t==="edit"||!s.includes(Pe)),De=d.baseUrl.trim();let Te=F||De.length>0;if(Te&&!F)try{new URL(De)}catch{Te=!1}let Le=!d.defaultModel||d.models.some(S=>S.id===d.defaultModel);if(Le){const S=new Set;Le=!d.models.some(_=>{const H=_.id.trim();return H.length===0||S.has(H)?!0:(S.add(H),!1)})}const R={basics:$e&&Te,models:Le},q=Oe.map((S,_)=>{let H;_===ne?H="current":_<ne?H=R[S.id]?"complete":"error":H="upcoming";const ve=F&&S.id==="models"?"providers.drawer.steps.aggregateModels":S.labelKey;return{id:S.id,label:i(ve),status:H}}),Q=S=>{Y(S)},T=async()=>{z(!0),K(null);try{const S=await Be.testProvider(d.id.trim()||"draft",{provider:o.serialize()});K({ok:S.ok,status:S.status,statusText:S.statusText,durationMs:S.durationMs,message:S.ok?void 0:S.statusText,testedAt:Date.now()})}catch(S){K({ok:!1,message:ge(S).message,testedAt:Date.now()})}finally{z(!1)}},ae=()=>{ne<Oe.length-1&&Y(Oe[ne+1].id)},be=()=>{ne>0&&Y(Oe[ne-1].id)},we={form:d,errors:w,isCreate:E,advancedOpen:m,onAdvancedOpenChange:o.setAdvancedOpen,idInputRef:N,onProviderIdChange:o.handleProviderIdChange,onFieldChange:o.handleFieldChange,onTypeChange:o.handleTypeChange,onAuthModeChange:o.handleAuthModeChange,onNonStreamViaStreamChange:o.handleProviderNonStreamViaStreamChange,onUseAbsoluteUrlChange:o.handleUseAbsoluteUrlChange,onStreamUsageChange:o.handleStreamUsageChange,onAddHeader:o.handleAddHeader,onRemoveHeader:o.handleRemoveHeader,onHeaderChange:o.handleHeaderChange,onModelIdChange:o.handleModelIdChange,onModelChange:o.handleModelChange,onAddModel:o.handleAddModel,onRemoveModel:o.handleRemoveModel,onModelNonStreamViaStreamChange:o.handleModelNonStreamViaStreamChange,onSetDefaultModel:o.handleSetDefaultModel,memberOptions:ye,onAddMember:o.handleAddMember,onRemoveMember:o.handleRemoveMember,onMemberTargetChange:o.handleMemberTargetChange,onReorderMembers:o.handleReorderMembers,onModelFailoverChange:o.handleModelFailoverChange,testVerification:F?void 0:t==="edit"?y?{available:!0,testing:g??!1,result:j??null,onTest:y}:void 0:{available:!0,testing:C,result:G,onTest:()=>void T()},probeModels:F?void 0:{available:d.baseUrl.trim().length>0,onProbe:()=>P(!0)}};return e.jsxs("div",{className:"fixed inset-0 z-50 flex",children:[e.jsx("div",{className:"flex-1 bg-background/95","aria-hidden":"true"}),e.jsxs("aside",{ref:O,role:"dialog","aria-modal":"true","aria-labelledby":"provider-drawer-title","aria-describedby":"provider-drawer-desc",className:"flex h-full min-h-0 w-full max-w-5xl flex-col border-l border-border bg-background shadow-[var(--surface-shadow-lg)]",children:[e.jsxs("header",{className:"border-b border-border bg-secondary px-6 py-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"inline-flex rounded-full border border-primary/20 bg-primary/10 px-3 py-1 text-[11px] font-medium uppercase tracking-[0.18em] text-primary",children:i(E?"providers.drawer.quickStart":"providers.drawer.editTitle")}),e.jsxs("div",{children:[e.jsx("h2",{id:"provider-drawer-title",className:"text-lg font-semibold tracking-[-0.02em]",children:i(E?"providers.drawer.createTitle":"providers.drawer.editTitle")}),e.jsx("p",{id:"provider-drawer-desc",className:"text-sm text-muted-foreground",children:i("providers.drawer.description")})]})]}),e.jsx(A,{type:"button",ref:J,variant:"outline",onClick:p,className:"bg-card",children:i("common.actions.close")})]}),e.jsx("div",{className:"mt-4 grid gap-3 md:grid-cols-3",children:fe.map(S=>e.jsxs("div",{className:"rounded-xl border border-transparent bg-card px-4 py-3 shadow-[var(--surface-shadow)]",children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground",children:S.label}),e.jsx("p",{className:"mt-2 text-sm font-semibold text-foreground",children:S.value})]},S.label))})]}),e.jsxs("div",{className:"grid min-h-0 flex-1 overflow-hidden xl:grid-cols-[minmax(0,1fr)_280px]",children:[e.jsxs("div",{className:"min-h-0 overflow-y-auto px-6 py-5 pb-10",children:[e.jsx(ss,{steps:q,current:B,onSelect:Q,className:"mb-6"}),B==="basics"?e.jsx(as,{...we}):null,B==="models"?F?e.jsx(js,{...we}):e.jsx(rs,{...we}):null]}),e.jsx("aside",{className:"hidden min-h-0 overflow-y-auto border-l border-border/45 bg-secondary/40 px-5 py-5 xl:block",children:e.jsxs("div",{className:"sticky top-0 space-y-5",children:[e.jsxs("div",{className:"rounded-xl border border-transparent bg-card p-4 shadow-[var(--surface-shadow)]",children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground",children:i("providers.drawer.formSummary")}),e.jsx("p",{className:"mt-2 text-base font-semibold",children:He}),e.jsx("div",{className:"mt-4 space-y-3 text-sm",children:fe.map(S=>e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("span",{className:"text-muted-foreground",children:S.label}),e.jsx("span",{className:"text-right font-medium",children:S.value})]},S.label))})]}),e.jsxs("div",{className:"rounded-xl border border-transparent bg-card p-4 shadow-[var(--surface-shadow)]",children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground",children:i("providers.drawer.sections.checklist")}),e.jsx("ul",{className:"mt-3 space-y-2 text-sm text-muted-foreground",children:F?e.jsxs(e.Fragment,{children:[e.jsx("li",{children:i("providers.aggregate.drawer.checkMembers")}),e.jsx("li",{children:i("providers.aggregate.drawer.checkPriority")}),e.jsx("li",{children:i("providers.aggregate.drawer.checkFailover")})]}):e.jsxs(e.Fragment,{children:[e.jsx("li",{children:i("providers.drawer.hints.checkUrl")}),e.jsx("li",{children:i("providers.drawer.hints.checkAuth")}),e.jsx("li",{children:i("providers.drawer.hints.checkModels")})]})})]}),m&&e.jsxs("div",{className:"rounded-xl bg-accent p-4 text-sm text-foreground",children:[e.jsx("p",{className:"font-medium text-primary",children:i("providers.drawer.hints.advancedTitle")}),e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:i("providers.drawer.hints.advancedBody")})]})]})})]}),e.jsxs("footer",{className:"flex items-center justify-between gap-3 border-t border-border bg-secondary px-6 py-4 text-sm",children:[e.jsxs("div",{className:"flex flex-col gap-1 text-xs",children:[!E&&u?e.jsx("button",{type:"button",onClick:u,disabled:b,className:"text-muted-foreground underline-offset-2 hover:text-destructive hover:underline disabled:opacity-50",children:i("providers.actions.delete")}):null,L?e.jsx("span",{className:"text-destructive","aria-live":"polite",children:L}):null]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(A,{type:"button",variant:"outline",onClick:p,disabled:b,className:"bg-card",children:i("common.actions.cancel")}),e.jsx(A,{type:"button",variant:"outline",onClick:be,disabled:b||ne===0,className:"bg-card",children:i("common.actions.previous")}),Me?null:e.jsx(A,{type:"button",onClick:ae,disabled:b,children:i("common.actions.next")}),e.jsx(A,{type:"button",onClick:Ne,disabled:b,children:i(b?"common.actions.saving":"common.actions.save")})]})]})]}),e.jsx(ws,{open:x,providerId:(r==null?void 0:r.id)??(d.id.trim()||"draft"),providerName:(r==null?void 0:r.label)||d.label.trim()||d.id.trim()||i("providers.drawer.summary.untitled"),existingModelIds:d.models.map(S=>S.id.trim()).filter(Boolean),draft:o.serialize(),onImport:o.handleImportModels,onClose:()=>P(!1)})]})}function Cs({provider:a,defaultModel:t,modelCount:r,requests24h:s,avgLatencyMs:l,routeCount:p,testResult:h,backendsHealth:j,onTest:g,onEdit:y}){var L;const{t:u}=W(),i=a.label||a.id,o=i.slice(0,1).toUpperCase()||"?",d=a.type==="aggregate",w=d?Et(a.type,u):((L=Dt.find(U=>U.value===(a.type??"custom")))==null?void 0:L.label)??a.type??"custom",m=h?h.ok?"ok":"fail":"untested",N=a.models??[],b=N.reduce((U,B)=>{var Y;return U+(((Y=B.members)==null?void 0:Y.length)??0)},0),M=d?N.flatMap(U=>(U.members??[]).map(B=>({target:B.target,entry:j==null?void 0:j.get(B.target)})).filter(B=>!!(B.entry&&B.entry.state!=="healthy"))):[];return e.jsxs("div",{"data-testid":"provider-card",className:"flex flex-col rounded-lg border border-border bg-card p-4 transition-colors hover:border-primary/40",children:[e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-secondary text-sm font-semibold text-muted-foreground",children:o}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"truncate text-[13px] font-semibold text-foreground",title:i,children:i}),e.jsx(re,{variant:d?"default":"outline",className:"shrink-0 rounded-full px-2 py-0 text-[10px] font-normal",children:w})]}),d?e.jsx("code",{className:"mt-0.5 block truncate font-mono text-[10.5px] text-muted-foreground",children:N.length>0?N.map(U=>`${U.id} → ${(U.members??[]).map(B=>B.target).join(" › ")}`).join(" ; "):u("providers.aggregate.card.noMembers")}):e.jsx("code",{className:"mt-0.5 block truncate font-mono text-[10.5px] text-muted-foreground",title:a.baseUrl,children:a.baseUrl})]}),d?null:e.jsx(Ms,{state:m})]}),e.jsx("div",{className:"mt-3 grid grid-cols-3 gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(Fe,{label:u("providers.aggregate.card.statAggregateModels"),value:r>0?String(r):"—"}),e.jsx(Fe,{label:u("providers.aggregate.card.statMembers"),value:b>0?String(b):"—"}),e.jsx(Fe,{label:u("providers.card.statRequests24h"),value:s!=null?s.toLocaleString():"—"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Fe,{label:u("providers.card.statModels"),value:r>0?String(r):"—"}),e.jsx(Fe,{label:u("providers.card.statRequests24h"),value:s!=null?s.toLocaleString():"—"}),e.jsx(Fe,{label:u("providers.card.statAvgLatency"),value:ps(l,u("common.units.ms"),{maximumFractionDigits:0})})]})}),d?e.jsx("div",{className:"mt-2.5 flex flex-wrap items-center gap-1.5 text-[11px]",children:M.length>0?M.slice(0,3).map(U=>e.jsx(Ss,{target:U.target,entry:U.entry},U.target)):b>0?e.jsx("span",{className:"text-success",children:u("providers.aggregate.card.allHealthy")}):null}):e.jsxs("div",{className:"mt-2.5 flex items-center gap-1.5 text-[11px] text-muted-foreground",children:[e.jsx("span",{className:"shrink-0",children:u("providers.card.defaultModelLabel")}),t?e.jsx("code",{className:"min-w-0 truncate rounded bg-secondary px-1.5 py-0.5 font-mono text-[10.5px] text-foreground",title:t,children:t}):e.jsx("span",{children:"—"})]}),e.jsxs("div",{className:"mt-3 flex items-center gap-1.5 border-t border-border pt-2.5 text-[10.5px] text-muted-foreground",children:[e.jsx("span",{className:"truncate",children:u("providers.card.routeCount",{count:p})}),e.jsxs("div",{className:"ml-auto flex shrink-0 gap-1.5",children:[d?null:e.jsx(A,{variant:"outline",size:"sm",className:"h-7 px-2.5 text-[11px]",onClick:g,children:u("providers.actions.test")}),e.jsx(A,{variant:"outline",size:"sm",className:"h-7 px-2.5 text-[11px]",onClick:y,children:u("providers.actions.edit")})]})]})]})}function Ss({target:a,entry:t}){const{t:r}=W();if(t.state==="cooling"){const s=Math.max(1,Math.ceil((t.cooldownRemainingSeconds??0)/60));return e.jsxs(re,{variant:"destructive",className:"rounded-full px-1.5 py-0 text-[10px] font-normal",title:a,children:[a," · ",r("providers.aggregate.card.coolingBadge",{minutes:s})]})}return e.jsxs(re,{variant:"warning",className:"rounded-full px-1.5 py-0 text-[10px] font-normal",title:a,children:[a," · ",r("providers.aggregate.card.degradedBadge",{count:t.consecutiveFailures})]})}function Fe({label:a,value:t}){return e.jsxs("div",{className:"rounded bg-secondary/60 px-2.5 py-2",children:[e.jsx("div",{className:"text-[10px] text-muted-foreground",children:a}),e.jsx("div",{className:"metric-number mt-0.5 truncate text-[13px] font-semibold text-foreground",children:t})]})}function Ms({state:a}){const{t}=W();return a==="ok"?e.jsx(re,{variant:"success",className:"shrink-0 rounded-full px-1.5 py-0 text-[10px]",children:t("providers.card.health.ok")}):a==="fail"?e.jsx(re,{variant:"destructive",className:"shrink-0 rounded-full px-1.5 py-0 text-[10px]",children:t("providers.card.health.fail")}):e.jsx(re,{variant:"secondary",className:"shrink-0 rounded-full px-1.5 py-0 text-[10px]",children:t("providers.card.health.untested")})}const Ps=1e4;function Es({providersLength:a,filteredProviders:t,testResults:r,providerSearch:s,providerTypeFilter:l,configPending:p,defaultLabels:h,config:j,customEndpoints:g,onTest:y,onEdit:u,onProviderSearchChange:i,onProviderTypeChange:o,onResetFilters:d}){const{t:w}=W(),[m,N]=v.useState("usage"),b=dt(Ee.stats.model(1,50),{url:"/api/stats/model",method:"GET",params:{days:1,limit:50}},{retry:!1}),M=t.some(C=>C.type==="aggregate"),L=dt(Ee.providers.backendsHealth(),{url:"/api/providers/backends/health",method:"GET"},{retry:!1,refetchInterval:Ps,enabled:M}),U=v.useMemo(()=>{var z;const C=new Map;for(const G of((z=L.data)==null?void 0:z.backends)??[])C.set(G.key,G);return C},[L.data]),{requestsByProvider:B,latencyByProvider:Y}=v.useMemo(()=>{const C=new Map,z=new Map,G=new Map;for(const O of b.data??[]){const J=O.provider;C.set(J,(C.get(J)??0)+O.requests),O.avgLatencyMs>0&&(z.set(J,(z.get(J)??0)+O.avgLatencyMs*O.requests),G.set(J,(G.get(J)??0)+O.requests))}const K=new Map;for(const O of C.keys()){const J=G.get(O)??0;K.set(O,J>0?(z.get(O)??0)/J:null)}return{requestsByProvider:C,latencyByProvider:K}},[b.data]),x=v.useMemo(()=>{const C=new Map;for(const z of t)C.set(z.id,ns(j,g,z.id).length);return C},[j,g,t]),P=v.useMemo(()=>{const C=[...t],z=(G,K)=>(G.label||G.id).localeCompare(K.label||K.id);return m==="usage"&&b.isSuccess?C.sort((G,K)=>(B.get(K.id)??0)-(B.get(G.id)??0)||z(G,K)):C.sort(z),C},[t,m,b.isSuccess,B]);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(Xe,{className:"overflow-hidden",children:e.jsx(Ye,{className:"p-0",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2 bg-secondary/50 px-4 py-3",children:[e.jsx(le,{value:s,onChange:C=>i(C.target.value),placeholder:w("providers.filters.searchPlaceholder"),className:"h-9 w-full sm:w-64"}),e.jsxs(at,{value:l,onValueChange:o,children:[e.jsx(rt,{className:"h-9 w-[130px] text-xs",children:e.jsx(nt,{})}),e.jsxs(ot,{children:[e.jsx(Ae,{value:"all",children:w("providers.filters.typeAll")}),Dt.map(C=>e.jsx(Ae,{value:C.value??"custom",children:C.label},C.value??"custom"))]})]}),e.jsxs(at,{value:m,onValueChange:C=>N(C),children:[e.jsx(rt,{className:"h-9 w-[104px] text-xs","aria-label":w("providers.list.sortLabel"),children:e.jsx(nt,{})}),e.jsxs(ot,{children:[e.jsx(Ae,{value:"usage",children:w("providers.list.sortUsage")}),e.jsx(Ae,{value:"name",children:w("providers.list.sortName")})]})]}),e.jsx(re,{variant:"secondary",className:"shrink-0 rounded-full px-2.5 py-1 text-[11px]",children:t.length}),e.jsx(A,{variant:"ghost",size:"sm",onClick:d,disabled:!s.trim()&&l==="all",className:"h-9 shrink-0 rounded-full px-2.5 text-xs",children:w("common.actions.reset")})]})})}),p?e.jsx("div",{className:"flex min-h-[160px] items-center justify-center text-sm text-muted-foreground",children:w("common.loading")}):a===0?e.jsx(ct,{compact:!0,title:w("providers.emptyState"),description:e.jsxs(e.Fragment,{children:[e.jsx("p",{children:w("providers.emptyStateSub")}),e.jsx("p",{className:"mt-1",children:w("workbench.list.emptyHint")})]})}):t.length===0?e.jsx(ct,{compact:!0,title:w("providers.emptyFiltered")}):e.jsx("div",{className:"grid gap-3.5 sm:grid-cols-2 xl:grid-cols-3",children:P.map(C=>{var z;return e.jsx(Cs,{provider:C,defaultModel:h.get(C.id),modelCount:((z=C.models)==null?void 0:z.length)??0,requests24h:b.isSuccess?B.get(C.id)??0:null,avgLatencyMs:b.isSuccess?Y.get(C.id)??null:null,routeCount:x.get(C.id)??0,testResult:r[C.id]??null,backendsHealth:U,onTest:()=>y(C),onEdit:()=>u(C)},C.id)})})]})}function Ds({routing:a,endpoint:t,tabInfo:r,config:s,customEndpoints:l}){var N,b;const{t:p}=W(),h=a.routesByEndpoint[t]||[],j=a.savingRouteFor===t,g=a.savingCompatibilityPolicy,y=a.writingEndpoint===t,u=((N=r==null?void 0:r.protocols)==null?void 0:N.some(M=>M.startsWith("openai")))??t==="openai",i=os(t,s,l),o=u?(i==null?void 0:i.enabled)??!1:!1,w=((b=r==null?void 0:r.protocols)==null?void 0:b.includes("anthropic"))??t==="anthropic"?Rt:Tt,m=new Set(h.map(M=>M.source.trim()).filter(Boolean));return e.jsx(Xe,{"data-testid":"endpoint-config-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(Ye,{className:"space-y-3 p-4",children:[e.jsx("h3",{className:"text-[12.5px] font-semibold",children:p("workbench.endpointConfig.title")}),u?e.jsxs("div",{className:"flex items-center justify-between gap-2 border border-border/60 bg-secondary/30 px-2.5 py-2",children:[e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsx(ce,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:p("modelManagement.openaiCompatibility.toggleLabel")}),e.jsx("p",{className:"text-[10.5px] text-muted-foreground",children:p(o?"modelManagement.openaiCompatibility.enabledHint":"modelManagement.openaiCompatibility.disabledHint")})]}),e.jsx(lt,{"data-testid":"compatibility-toggle",checked:o,onCheckedChange:M=>void a.handleCompatibilityEnabledChange(t,M),disabled:g||y,"aria-label":p("modelManagement.openaiCompatibility.toggleLabel")})]}):null,e.jsxs("div",{children:[e.jsx("p",{className:"mb-1.5 text-[11px] text-muted-foreground",children:p("settings.routing.suggested")}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:w.map(M=>{const L=m.has(M);return e.jsx("button",{"data-testid":"suggestion-chip",type:"button",onClick:()=>a.handleAddSuggestion(t,M),disabled:j||L,className:je("h-6 border px-2 text-[10.5px] transition-colors",L?"border-border bg-secondary/40 text-muted-foreground/50":"border-border bg-card hover:border-primary hover:text-primary"),children:M},`${t}-${M}`)})})]})]})})}function Rs({routing:a,endpoint:t}){const{t:r}=W(),s=a.defaultsByEndpoint[t]??null,l=a.isDefaultsDirtyByEndpoint[t]??!1,p=a.savingDefaultsFor===t,h=a.writingEndpoint===t,j=a.providerModelOptions;return e.jsx(Xe,{"data-testid":"routing-defaults-card",className:"border-primary/40 bg-primary/5 shadow-none",children:e.jsxs(Ye,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-[13px] font-semibold text-primary",children:r("workbench.defaults.title")}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:r("workbench.defaults.cardSubtitle")})]}),e.jsxs(Lt,{summary:e.jsx("span",{className:"text-[11px] font-medium text-muted-foreground",children:r("workbench.defaults.moreLabel")}),summaryClassName:"px-2 py-1",contentClassName:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:r("workbench.defaults.reasoningLabel")}),e.jsx(Ue,{value:(s==null?void 0:s.reasoning)??"",onChange:g=>a.handleDefaultsChange(t,"reasoning",g),options:j,disabled:p,ariaLabel:r("workbench.defaults.reasoningLabel"),placeholder:r("workbench.defaults.targetPlaceholder")})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:r("workbench.defaults.backgroundLabel")}),e.jsx(Ue,{value:(s==null?void 0:s.background)??"",onChange:g=>a.handleDefaultsChange(t,"background",g),options:j,disabled:p,ariaLabel:r("workbench.defaults.backgroundLabel"),placeholder:r("workbench.defaults.targetPlaceholder")})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:r("workbench.defaults.thresholdLabel")}),e.jsx(le,{type:"number",min:1,value:(s==null?void 0:s.longContextThreshold)||"",onChange:g=>{const y=Number.parseInt(g.target.value,10);a.handleDefaultsChange(t,"longContextThreshold",Number.isFinite(y)?y:0)},disabled:p,className:"md:w-56"})]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"border border-border bg-card px-2.5 py-2 font-mono text-xs",children:"*"}),e.jsx(ke,{className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground","aria-hidden":!0}),e.jsx("div",{"data-testid":"default-target",className:"min-w-[180px] flex-1",children:e.jsx(Ue,{value:(s==null?void 0:s.completion)??"",onChange:g=>a.handleDefaultsChange(t,"completion",g),options:j,disabled:p,ariaLabel:r("workbench.defaults.completionLabel"),placeholder:r("workbench.defaults.targetPlaceholder")})}),e.jsxs(A,{size:"sm","data-testid":"save-defaults",onClick:()=>void a.handleSaveDefaults(t),disabled:p||!l||h,className:"relative",children:[r(p?"common.actions.saving":"workbench.defaults.save"),l?e.jsx("span",{className:"absolute -right-1 -top-1 h-2 w-2 rounded-full bg-warning"}):null]})]})]})})}const Ts={anthropic:"/anthropic",openai:"/openai"};function Ls(a){var t;return(t=a.paths)!=null&&t.length?a.paths[0].path:a.path?a.path:`/${a.id}`}function Os({tabs:a,customEndpoints:t,routeCounts:r,selectedEndpointId:s,onSelect:l,onCreate:p,onEditEndpoint:h,onDeleteEndpoint:j}){const{t:g}=W(),y=a.map(u=>{const i=t.find(d=>d.id===u.key);if(!i)return{key:u.key,label:u.label,path:Ts[u.key]??`/${u.key}`,protocols:u.protocols??[],enabled:!0};const o=i.paths??(i.path?[{path:i.path,protocol:i.protocol??"anthropic"}]:[]);return{key:u.key,label:i.label||i.id,path:Ls(i),protocols:[...new Set(o.map(d=>d.protocol))],enabled:i.enabled!==!1,custom:i}});return e.jsxs("section",{"data-testid":"endpoint-rail",className:"flex gap-2 overflow-x-auto border border-border bg-card shadow-[var(--surface-shadow)] lg:h-full lg:flex-col lg:overflow-visible",children:[e.jsxs("div",{className:"hidden shrink-0 border-b border-border/60 px-3 py-2.5 lg:block",children:[e.jsx("h2",{className:"text-[12.5px] font-semibold",children:g("workbench.endpointRail.title")}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:g("workbench.endpointRail.subtitle")})]}),e.jsxs("div",{className:"flex gap-1.5 p-2 lg:flex-col lg:gap-1",children:[y.map(u=>{const i=u.key===s,o=r[u.key]??0,d=!u.enabled;return e.jsxs("div",{"data-testid":"endpoint-row",className:je("flex shrink-0 items-stretch border transition-colors lg:shrink",i?"border-primary/40 bg-primary/5":"border-border bg-card hover:bg-accent",d?"opacity-60":""),children:[e.jsxs("button",{type:"button",onClick:()=>l(u.key),className:"flex min-w-0 flex-1 items-center gap-2 px-2.5 py-2 text-left",children:[e.jsx("span",{className:je("h-1.5 w-1.5 shrink-0 rounded-full",i?"bg-primary":"bg-muted-foreground/40"),"aria-hidden":!0}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-[11.5px] font-medium",title:u.label,children:u.label}),e.jsxs("span",{className:"mt-0.5 flex items-center gap-1.5 text-[10px] text-muted-foreground",children:[e.jsx("span",{className:"truncate font-mono",children:u.path}),e.jsx("span",{"aria-hidden":!0,children:"·"}),e.jsx("span",{className:"shrink-0 tabular-nums",children:g("workbench.endpointRail.ruleCount",{count:o})})]})]})]}),u.custom?e.jsxs("div",{className:"flex items-center gap-0.5 pr-1",children:[e.jsx("button",{type:"button",onClick:()=>h(u.custom),className:"flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-foreground",title:g("common.edit"),"aria-label":g("common.edit"),children:e.jsx(At,{className:"h-3 w-3","aria-hidden":!0})}),u.custom.deletable!==!1?e.jsx("button",{type:"button",onClick:()=>j(u.custom),className:"flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-destructive",title:g("common.delete"),"aria-label":g("common.delete"),children:e.jsx(Bt,{className:"h-3 w-3","aria-hidden":!0})}):null]}):null]},u.key)}),e.jsxs("button",{type:"button","data-testid":"create-endpoint",onClick:p,className:"flex shrink-0 items-center justify-center border border-dashed border-border px-3 py-2 text-[11.5px] text-muted-foreground transition-colors hover:border-primary hover:text-primary lg:shrink",children:["+ ",g("workbench.endpointRail.add")]})]})]})}function Fs({endpointPath:a,defaultTarget:t}){const{t:r}=W();return e.jsxs("section",{"data-testid":"routing-flow-banner",className:"flex flex-wrap items-center gap-x-3 gap-y-2 border border-border bg-card px-4 py-3 shadow-[var(--surface-shadow)]",children:[e.jsx("span",{className:"text-[10.5px] font-semibold uppercase tracking-[0.06em] text-muted-foreground",children:r("workbench.flow.title")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[e.jsx("span",{className:"border border-border bg-secondary px-2.5 py-1 font-mono text-[11px]",children:r("workbench.flow.clientStep")}),e.jsx(ke,{className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0}),e.jsxs("span",{className:"border border-border bg-secondary px-2.5 py-1 text-[11px]",children:[r("workbench.flow.endpointStep")," ",e.jsx("span",{className:"font-mono",children:a})]}),e.jsx(ke,{className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0}),e.jsx("span",{className:"border border-primary bg-primary/5 px-2.5 py-1 text-[11px] font-semibold text-primary",children:r("workbench.flow.matchStep")}),e.jsx(ke,{className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0}),e.jsx("span",{className:"border border-border bg-secondary px-2.5 py-1 font-mono text-[11px]",children:t||r("workbench.flow.fallbackNote")})]})]})}function Is({routing:a,endpoint:t,onRequestDeletePreset:r}){var i,o;const{t:s}=W(),l=a.presetsByEndpoint[t]??[],p=a.presetNameByEndpoint[t]??"",h=a.presetErrorByEndpoint[t],j=a.savingPresetFor===t,g=((i=a.applyingPreset)==null?void 0:i.endpoint)===t?a.applyingPreset.name:null,y=((o=a.deletingPreset)==null?void 0:o.endpoint)===t?a.deletingPreset.name:null,u=a.writingEndpoint===t;return e.jsx(Xe,{"data-testid":"routing-presets-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(Ye,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h3",{className:"text-[13px] font-semibold",children:s("modelManagement.presets.title")}),e.jsx(A,{variant:"outline",size:"sm","data-testid":"save-preset",onClick:()=>void a.handleSavePreset(t),disabled:j||u,children:s(j?"modelManagement.presets.saving":"modelManagement.presets.save")})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:s("modelManagement.presets.description")}),e.jsx(le,{"data-testid":"preset-name-input",value:p,onChange:d=>a.handlePresetNameChange(t,d.target.value),placeholder:s("modelManagement.presets.namePlaceholder"),disabled:j,className:"h-8 text-xs"}),h?e.jsx("p",{className:"text-xs text-destructive",children:h}):null,l.length===0?e.jsx("p",{className:"py-2 text-center text-[11px] text-muted-foreground",children:s("modelManagement.presets.empty")}):e.jsx(Gt,{children:e.jsx("div",{className:"grid grid-cols-1 gap-1.5 sm:grid-cols-2",children:l.map(d=>{const w=g===d.name,m=y===d.name,N=Object.entries(d.modelRoutes??{}),b=N.length;return e.jsxs("div",{"data-testid":"preset-row",className:"flex items-center justify-between gap-2 border border-border bg-secondary/40 px-2.5 py-2",children:[e.jsxs(Kt,{children:[e.jsx(Wt,{asChild:!0,children:e.jsxs("div",{className:"min-w-0 flex-1 cursor-default",children:[e.jsx("span",{className:"block truncate text-[11px] font-medium",children:d.name}),e.jsx(re,{variant:"outline",className:"mt-0.5 text-[10px] font-normal",children:b>0?s("modelManagement.presets.rulesCount",{count:b}):s("modelManagement.presets.noRules")})]})}),b>0?e.jsx(Jt,{side:"bottom",className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1 text-xs",children:[N.slice(0,5).map(([M,L])=>e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"truncate",children:M}),e.jsx(ke,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:L})]},M)),b>5?e.jsxs("div",{className:"text-muted-foreground",children:["…+",b-5]}):null]})}):null]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"apply-preset",className:"text-[11px] font-semibold text-primary hover:underline disabled:opacity-50",onClick:()=>a.setPresetDiffDialog({endpoint:t,preset:d}),disabled:w||m||u,children:s(w?"modelManagement.presets.applying":"modelManagement.presets.apply")}),e.jsx("button",{type:"button","data-testid":"delete-preset",className:"text-[11px] text-muted-foreground hover:text-destructive disabled:opacity-50","aria-label":s("common.delete"),onClick:()=>r(t,d),disabled:m||w||u,children:s(m?"modelManagement.presets.deleting":"modelManagement.presets.delete")})]})]},d.name)})})})]})})}function As({entry:a,index:t,savingRoute:r,options:s,sourceListId:l,onRouteChange:p,onRemoveRoute:h}){const{t:j}=W(),{attributes:g,listeners:y,setNodeRef:u,setActivatorNodeRef:i,transform:o,transition:d,isDragging:w}=St({id:a.id});return e.jsxs("div",{ref:u,"data-testid":"route-rule-row","data-id":a.id,style:{transform:Pt.Transform.toString(o),transition:d},className:je("flex items-center gap-2 border border-border bg-card p-2",w&&"z-10 opacity-60 shadow-[var(--surface-shadow-lg)]"),children:[e.jsx("button",{ref:i,type:"button","data-testid":"route-rule-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",...g,...y,children:e.jsx(Mt,{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:t+1}),e.jsx(le,{"data-testid":"route-rule-source",value:a.source,onChange:m=>p(a.id,"source",m.target.value),placeholder:j("settings.routing.sourcePlaceholder"),list:l,disabled:r,className:"h-8 min-w-0 flex-1 text-xs"}),e.jsx(ke,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground","aria-hidden":!0}),e.jsx("div",{"data-testid":"route-rule-target",className:"min-w-0 flex-[1.15]",children:e.jsx(Ue,{value:a.target,onChange:m=>p(a.id,"target",m),options:s,disabled:r,ariaLabel:j("workbench.routing.targetLabel"),placeholder:j("settings.routing.targetPlaceholder")})}),e.jsx(A,{variant:"ghost",size:"icon","data-testid":"route-rule-delete",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>h(a.id),disabled:r,"aria-label":j("common.delete"),children:e.jsx(ut,{className:"h-3.5 w-3.5","aria-hidden":!0})})]})}function Bs({routing:a,endpoint:t,tabInfo:r}){var m;const{t:s}=W(),l=a.routesByEndpoint[t]||[],p=a.routeError[t],h=a.savingRouteFor===t,j=a.isDirtyByEndpoint[t]??!1,g=a.writingEndpoint===t,y=a.providerModelOptions,u=`route-source-${t}`,i=bt(tt(yt,{activationConstraint:{distance:6}}),tt(jt,{coordinateGetter:vt})),o=N=>{const{active:b,over:M}=N;!M||b.id===M.id||a.handleReorderRules(t,String(b.id),String(M.id))},w=((m=r==null?void 0:r.protocols)==null?void 0:m.includes("anthropic"))??t==="anthropic"?Rt:Tt;return e.jsx(Xe,{"data-testid":"routing-rules-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(Ye,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h3",{className:"flex items-center gap-2 text-[13px] font-semibold",children:[s("workbench.routing.rulesTitle"),e.jsx(re,{variant:"outline",className:"text-[10.5px] font-normal tabular-nums",children:l.length})]}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:s("workbench.routing.rulesSubtitle")})]}),e.jsx(A,{variant:"outline",size:"sm","data-testid":"add-route",onClick:()=>a.handleAddRoute(t),disabled:h,children:s("settings.routing.add")})]}),p?e.jsx("p",{className:"text-xs text-destructive",children:p}):null,l.length===0?e.jsx(ct,{compact:!0,title:s("workbench.routing.emptyTitle"),description:s("workbench.routing.emptyDescription"),action:e.jsx(A,{size:"sm",onClick:()=>a.handleAddRoute(t),disabled:h,children:s("workbench.routing.addFirst")})}):e.jsx(Nt,{sensors:i,collisionDetection:wt,onDragEnd:o,children:e.jsx(kt,{items:l.map(N=>N.id),strategy:Ct,children:e.jsx("div",{className:"flex flex-col gap-1.5",children:l.map((N,b)=>e.jsx(As,{entry:N,index:b,savingRoute:h,options:y,sourceListId:u,onRouteChange:(M,L,U)=>a.handleRouteChange(t,M,L,U),onRemoveRoute:M=>a.handleRemoveRoute(t,M)},N.id))})})}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-t border-border/60 pt-3",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:s(j?"modelManagement.actions.footerDirtyHint":"modelManagement.actions.footerSavedHint")}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(A,{variant:"outline",size:"sm","data-testid":"reset-routes",onClick:()=>a.handleResetRoutes(t),disabled:h||!j,children:s("common.actions.reset")}),e.jsxs(A,{size:"sm","data-testid":"save-routes",onClick:()=>void a.handleSaveRoutes(t),disabled:h||g,className:"relative",children:[s(h?"common.actions.saving":"modelManagement.actions.saveRoutes"),j?e.jsx("span",{className:"absolute -right-1 -top-1 h-2 w-2 rounded-full bg-warning"}):null]})]})]}),e.jsx("datalist",{id:u,children:w.map(N=>e.jsx("option",{value:N},`${u}-${N}`))})]})})}const Hs={simulateRequest(a){return{url:"/api/routing/simulate",method:"POST",data:a}}},$s=350;function zs(a,t){switch(a.kind){case"modelRoute":return{label:a.viaAlias?t("workbench.hitSim.reasonModelRouteAlias"):t("workbench.hitSim.reasonModelRoute"),tone:"hit"};case"directMatch":return{label:t("workbench.hitSim.reasonDirectMatch"),tone:"hit"};case"thinkingDefault":return{label:t("workbench.hitSim.reasonThinkingDefault"),tone:"hit"};case"completionDefault":return{label:t("workbench.hitSim.reasonCompletionDefault"),tone:"hit"};case"longContextDefault":return{label:t("workbench.hitSim.reasonLongContext"),tone:"hit",detail:t("workbench.hitSim.longContextDetail",{estimate:a.tokenEstimate.toLocaleString(),threshold:a.threshold.toLocaleString()})};case"fallback":return{label:t("workbench.hitSim.reasonFallback"),tone:"fallback"}}return{label:t("workbench.hitSim.reasonFallback"),tone:"fallback"}}function _s({tabs:a,endpoint:t,onEndpointChange:r}){var M;const{t:s}=W(),l=a.filter(L=>L.key!=="providers"),[p,h]=v.useState(((M=l[0])==null?void 0:M.key)??"anthropic"),j=t??p,g=L=>{t&&r?r(L):h(L)},[y,u]=v.useState(""),[i,o]=v.useState(!1),[d,w]=v.useState("");v.useEffect(()=>{const L=setTimeout(()=>w(y.trim()),$s);return()=>clearTimeout(L)},[y]);const{data:m,isFetching:N,error:b}=dt(["routing","simulate",j,d,i],Hs.simulateRequest({endpoint:j,model:d||void 0,thinking:i}),{retry:!1,refetchOnWindowFocus:!1,staleTime:1/0});return e.jsxs("section",{"data-testid":"routing-hit-simulator",className:"space-y-3 rounded-lg border border-border bg-card p-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm font-semibold text-foreground",children:s("workbench.hitSim.title")}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:s("workbench.hitSim.subtitle")})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-2",children:[t?null:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:s("workbench.hitSim.endpointLabel")}),e.jsxs(at,{value:j,onValueChange:g,children:[e.jsx(rt,{className:"h-8 w-[168px]",children:e.jsx(nt,{})}),e.jsx(ot,{children:l.map(L=>e.jsx(Ae,{value:L.key,children:L.label},L.key))})]})]}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(lt,{checked:i,onCheckedChange:o,"aria-label":s("workbench.hitSim.thinking")}),s("workbench.hitSim.thinking")]})]}),e.jsx(le,{value:y,onChange:L=>u(L.target.value),placeholder:s("workbench.hitSim.modelPlaceholder"),className:"h-9 text-xs",spellCheck:!1,autoComplete:"off","aria-label":s("workbench.hitSim.modelPlaceholder")}),e.jsx(Us,{result:m,loading:N,errorMessage:(b==null?void 0:b.message)??null,requestedModel:d})]})}function Us({result:a,loading:t,errorMessage:r,requestedModel:s}){var g;const{t:l}=W();if(r)return e.jsxs("p",{className:"text-xs text-muted-foreground",children:[l("workbench.hitSim.errorPrefix"),": ",r]});if(!a)return t?e.jsx("div",{className:"h-[72px] animate-pulse rounded-lg border border-border bg-secondary"}):e.jsx("p",{className:"text-xs text-muted-foreground",children:l("workbench.hitSim.empty")});const p=zs(a.reason,l),h=p.tone==="fallback",j=s||l("workbench.hitSim.anyModel");return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:h?"rounded-lg border border-border bg-secondary px-3 py-2.5":"rounded-lg border border-success bg-success-bg px-3 py-2.5",children:[e.jsx("div",{className:h?"text-[11px] font-semibold text-warning":"text-[11px] font-semibold text-success",children:p.label}),e.jsx("div",{className:"mt-1 text-xs text-foreground",children:j}),e.jsxs("div",{className:"mt-1 text-xs text-muted-foreground",children:["→ ",a.providerLabel,":",a.modelId]}),p.detail?e.jsx("div",{className:"mt-1 text-[11px] text-muted-foreground",children:p.detail}):null]}),(((g=a.candidates)==null?void 0:g.length)??0)>1?e.jsxs("div",{className:"rounded-lg border border-border bg-secondary/50 px-3 py-2.5",children:[e.jsx("div",{className:"text-[11px] font-semibold text-muted-foreground",children:l("providers.aggregate.simulator.candidatesTitle")}),e.jsx("ol",{className:"mt-1.5 space-y-1",children:(a.candidates??[]).map((y,u)=>e.jsxs("li",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"w-4 shrink-0 text-center text-[10.5px] tabular-nums text-muted-foreground",children:u+1}),e.jsxs("span",{className:"min-w-0 truncate font-mono text-foreground",children:[y.providerLabel,":",y.modelId]}),u===0?e.jsx("span",{className:"shrink-0 text-[10px] font-medium text-muted-foreground",children:l("providers.aggregate.simulator.primaryBadge")}):null]},`${y.providerId}:${y.modelId}`))})]}):null,h?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:l("workbench.hitSim.fallbackHint")}):null]})}function qs({routing:a,config:t,customEndpoints:r,selectedEndpointId:s,routeCounts:l,onSelectEndpoint:p,onCreateEndpoint:h,onEditEndpoint:j,onDeleteEndpoint:g,onRequestDeletePreset:y}){var w;W();const u=s??((w=a.endpointTabs[0])==null?void 0:w.key)??"anthropic",i=a.endpointTabs.find(m=>m.key===u),o=a.defaultsByEndpoint[u],d=(()=>{var N;if(u==="anthropic")return"/anthropic";if(u==="openai")return"/openai";const m=r.find(b=>b.id===u);return(N=m==null?void 0:m.paths)!=null&&N.length?m.paths[0].path:m!=null&&m.path?m.path:`/${u}`})();return e.jsxs("div",{"data-testid":"routing-workspace",className:"flex flex-col gap-3.5",children:[e.jsx(Fs,{endpointPath:d,defaultTarget:(o==null?void 0:o.completion)??null}),e.jsxs("div",{className:"grid items-start gap-3.5 lg:grid-cols-[200px_minmax(0,1fr)_288px]",children:[e.jsx(Os,{tabs:a.endpointTabs,customEndpoints:r,routeCounts:l,selectedEndpointId:u,onSelect:p,onCreate:h,onEditEndpoint:j,onDeleteEndpoint:g}),e.jsxs("div",{className:"flex flex-col gap-3.5",children:[e.jsx(Rs,{routing:a,endpoint:u}),e.jsx(Bs,{routing:a,endpoint:u,tabInfo:i}),e.jsx(Is,{routing:a,endpoint:u,onRequestDeletePreset:y})]}),e.jsxs("div",{className:"flex flex-col gap-3.5",children:[e.jsx(_s,{tabs:a.endpointTabs,endpoint:u,onEndpointChange:p}),e.jsx(Ds,{routing:a,endpoint:u,tabInfo:i,config:t,customEndpoints:r})]})]})]})}function Vs({open:a,provider:t,options:r,usePreset:s,preservedExtras:l,onPresetChange:p,onConfirm:h,onClose:j}){const{t:g}=W();return t?e.jsx(qe,{open:a,onOpenChange:y=>!y&&j(),children:e.jsxs(Ve,{className:"max-w-2xl",onInteractOutside:y=>y.preventDefault(),children:[e.jsxs(Qe,{children:[e.jsx(Ge,{children:g("providers.testDialog.title")}),e.jsx(Ke,{children:g("providers.testDialog.subtitle",{name:t.label||t.id})})]}),e.jsxs(We,{className:"space-y-4",children:[e.jsx("div",{className:"rounded-xl bg-accent p-4 text-sm text-primary",children:g("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(ce,{htmlFor:"provider-test-preset",children:g("providers.testDialog.presetLabel")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:g("providers.testDialog.presetDescription")})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(lt,{id:"provider-test-preset",checked:s,onCheckedChange:p})})]}),s?e.jsx("div",{className:"space-y-2",children:e.jsxs("details",{className:"rounded-xl border border-transparent bg-card p-2 text-xs shadow-[var(--surface-shadow)]",children:[e.jsx("summary",{className:"cursor-pointer text-primary hover:underline",children:g("providers.testDialog.presetPreviewSummary")}),e.jsx("div",{className:"mt-2 space-y-1",children:r.map(y=>e.jsxs("code",{className:"block rounded-lg bg-secondary px-2 py-1 text-xs",children:[y.key,": ",y.value]},y.key))})]})}):e.jsx("p",{className:"text-xs text-muted-foreground",children:g("providers.testDialog.presetDescription")})]}),Object.keys(l).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:g("providers.testDialog.preservedInfo")}),Object.entries(l).map(([y,u])=>e.jsxs("code",{className:"block rounded-lg border border-transparent bg-card px-2 py-1 shadow-[var(--surface-shadow)]",children:[y,": ",u]},y))]})]}),e.jsxs(Je,{children:[e.jsx(A,{variant:"outline",onClick:j,children:g("providers.testDialog.cancel")}),e.jsx(A,{onClick:()=>void h(),children:g("providers.testDialog.primary")})]})]})}):null}function ha(){const{t:a}=W(),t=ls(),r=hs(t),s=xs(t,{sanitizeDraftsForProvider:r.sanitizeDraftsForProvider}),[l,p]=zt(),h=l.get("tab"),j=h==="routing"||h==="endpoints"?"routing":"providers";v.useEffect(()=>{h==="endpoints"&&p(E=>{const F=new URLSearchParams(E);return F.set("tab","routing"),F},{replace:!0})},[h,p]);const[g,y]=v.useState(!1),[u,i]=v.useState(void 0),[o,d]=v.useState(null),[w,m]=v.useState(!1),N=l.get("endpoint"),[b,M]=v.useState(N);v.useEffect(()=>{M(N)},[N]);const L=E=>{p(F=>{const V=new URLSearchParams(F);return V.set("tab","routing"),V.set("endpoint",E),V},{replace:!0})},U=()=>{p(E=>{const F=new URLSearchParams(E);return F.delete("endpoint"),F},{replace:!0})};v.useEffect(()=>{b&&(t.customEndpointsQuery.isPending||r.endpointTabs.some(E=>E.key===b)||U())},[b,r.endpointTabs,t.customEndpointsQuery.isPending]);const B=()=>{i(void 0),y(!0)},Y=E=>{i(E),y(!0)},x=E=>{p(F=>{const V=new URLSearchParams(F);return E==="providers"?V.delete("tab"):V.set("tab",E),V},{replace:!0})},P=async()=>{if(o){m(!0);try{o.kind==="provider"?await s.handleDeleteProvider(o.provider):o.kind==="preset"?await r.handleDeletePreset(o.endpoint,o.preset):await r.handleDeleteEndpoint(o.endpoint.id),d(null)}finally{m(!1)}}},C=(o==null?void 0:o.kind)==="provider"?is(t.config,t.customEndpoints,o.provider.id):0,z=(o==null?void 0:o.kind)==="provider"?a("providers.actions.delete"):(o==null?void 0:o.kind)==="preset"?a("modelManagement.presets.delete"):(o==null?void 0:o.kind)==="endpoint"?a("common.delete"):"",G=(o==null?void 0:o.kind)==="provider"?a("providers.confirm.delete",{name:o.provider.label||o.provider.id}):(o==null?void 0:o.kind)==="preset"?a("modelManagement.confirm.deletePreset",{name:o.preset.name}):(o==null?void 0:o.kind)==="endpoint"?a("modelManagement.deleteEndpointConfirm",{label:o.endpoint.label}):"",K=(o==null?void 0:o.kind)==="provider"?o.provider.label||o.provider.id:(o==null?void 0:o.kind)==="preset"?o.preset.name:(o==null?void 0:o.kind)==="endpoint"?o.endpoint.label:"",O=Object.values(r.routesByEndpoint).reduce((E,F)=>E+((F==null?void 0:F.length)??0),0),J=Object.fromEntries(Object.entries(r.routesByEndpoint).map(([E,F])=>[E,(F==null?void 0:F.length)??0])),pe=[{value:"providers",icon:Ht,label:a("workbench.viewSwitch.providers"),description:a("workbench.viewSwitch.providersDesc"),count:s.providerCount},{value:"routing",icon:$t,label:a("workbench.viewSwitch.routing"),description:a("workbench.viewSwitch.routingDesc"),count:O}];return e.jsxs("div",{className:"flex flex-col gap-6",children:[e.jsx(Ut,{actions:j==="providers"?e.jsx(A,{size:"sm",onClick:s.handleOpenCreate,children:a("providers.actions.add")}):e.jsx(A,{size:"sm",onClick:B,children:a("workbench.endpoints.create")})}),e.jsx("div",{role:"tablist","aria-label":a("workbench.viewSwitch.label"),className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:pe.map(E=>{const F=E.icon,V=j===E.value;return e.jsxs("button",{type:"button",role:"tab","aria-selected":V,onClick:()=>x(E.value),className:je("motion-surface flex items-center gap-3 rounded-xl border p-4 text-left",V?"border-primary/40 bg-primary/5":"border-border bg-card hover:bg-muted/40"),children:[e.jsx("span",{className:je("flex h-9 w-9 shrink-0 items-center justify-center rounded-lg",V?"bg-primary/10 text-primary":"bg-secondary text-muted-foreground"),children:e.jsx(F,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:je("text-sm font-semibold",V?"text-foreground":"text-muted-foreground"),children:E.label}),e.jsx(re,{variant:V?"default":"secondary",className:"text-[10px]",children:E.count})]}),e.jsx("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",children:E.description})]})]},E.value)})}),j==="providers"?e.jsx(Es,{configPending:t.configQuery.isPending||!t.config&&t.configQuery.isFetching,testResults:s.testResults,filteredProviders:s.filteredProviders,providerSearch:s.providerSearch,providerTypeFilter:s.providerTypeFilter,providersLength:s.providers.length,defaultLabels:s.defaultLabels,config:t.config,customEndpoints:t.customEndpoints,onTest:E=>s.initiateTestConnection(E),onEdit:E=>s.handleOpenEdit(E),onProviderSearchChange:s.setProviderSearch,onProviderTypeChange:s.setProviderTypeFilter,onResetFilters:()=>{s.setProviderSearch(""),s.setProviderTypeFilter("all")}}):e.jsx(qs,{routing:r,config:t.config,customEndpoints:t.customEndpoints,routeCounts:J,selectedEndpointId:b,onSelectEndpoint:L,onCreateEndpoint:B,onEditEndpoint:Y,onDeleteEndpoint:E=>d({kind:"endpoint",endpoint:E}),onRequestDeletePreset:(E,F)=>d({kind:"preset",endpoint:E,preset:F})}),e.jsx(ks,{open:s.drawerOpen,mode:s.drawerMode,provider:s.drawerMode==="edit"?s.editingProvider:void 0,existingProviderIds:s.providers.map(E=>E.id).filter(E=>s.drawerMode==="edit"&&s.editingProvider?E!==s.editingProvider.id:!0),allProviders:s.providers,testResult:s.editingProvider?s.testResults[s.editingProvider.id]??null:null,testing:s.editingProvider?s.testingProviderId===s.editingProvider.id:!1,onTest:()=>{s.editingProvider&&s.handleTestConnection(s.editingProvider)},onDelete:()=>{s.drawerMode==="edit"&&s.editingProvider&&d({kind:"provider",provider:s.editingProvider})},onClose:()=>{s.setDrawerOpen(!1),s.setEditingProvider(void 0),s.setDrawerMode("create")},onSubmit:s.handleProviderSubmit}),e.jsx(Vs,{open:s.testDialogOpen,provider:s.testDialogProvider,options:s.anthropicTestHeaderOptions,preservedExtras:s.testDialogPreservedExtras,usePreset:s.testDialogUsePreset,onPresetChange:s.setTestDialogUsePreset,onConfirm:s.confirmTestDialog,onClose:s.closeTestDialog}),e.jsx(bs,{open:!!s.noModelDialogProvider,provider:s.noModelDialogProvider,onClose:()=>s.setNoModelDialogProvider(null),onEdit:E=>{s.setNoModelDialogProvider(null),s.handleOpenEdit(E)}}),e.jsx(fs,{open:g,endpoint:u,onClose:()=>{y(!1),i(void 0)},onSuccess:()=>{t.configQuery.refetch()}}),e.jsx(vs,{dialog:r.presetDiffDialog,currentRoutes:r.presetDiffDialog?r.routesByEndpoint[r.presetDiffDialog.endpoint]||[]:[],onConfirm:(E,F)=>{r.setPresetDiffDialog(null),r.handleApplyPreset(E,F)},onClose:()=>r.setPresetDiffDialog(null)}),e.jsx(_t,{open:!!o,onOpenChange:E=>{!E&&!w&&d(null)},title:z,description:G,confirmLabel:a(w?"common.actions.loading":"common.delete"),cancelLabel:a("common.actions.cancel"),loading:w,onConfirm:P,children:K?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:K}),(o==null?void 0:o.kind)==="provider"&&C>0?e.jsx("p",{className:"text-xs text-muted-foreground",children:a("providers.confirm.deleteImpact",{count:C})}):null]}):null})]})}export{ha as default};
|
|
1
|
+
import{r as v,ax as Ft,j as e,ay as It,as as ut,ab as ke,az as bt,aA as tt,aB as vt,aC as jt,aD as yt,aE as Nt,aF as wt,aG as kt,aH as Ct,aI as St,aJ as Mt,aK as Pt,aL as At,aM as Bt,aN as Ht,aO as $t}from"./vendor-D2wC0h2o.js";import{d as zt}from"./router-CUBM_FND.js";import{C as _t}from"./ConfirmDialog-BOe5HI56.js";import{P as Ut}from"./PageToolbar-BnDacS2l.js";import{t as ge,q as Ee,e as _e,B as A,b as qt,s as Vt,a as Qt,c as dt,T as Gt,f as Kt,g as Wt,h as Jt}from"./app-BnQl39hq.js";import{B as re}from"./badge-RZTsODn-.js";import{c as je}from"./global-CJOj9WGx.js";import{d as mt,g as pt,a as ht,b as Xt,c as xt,e as gt,r as Yt,f as ze,m as Be,h as Zt,u as es,p as Et,i as ts,P as Oe,S as ss,B as as,M as rs,j as Dt,k as ns,l as os,C as Rt,O as Tt,n as ls,o as is}from"./useProviderForm-CsPV2Cqr.js";import{a as ds}from"./query-DVc6ZTRQ.js";import{g as Ie}from"./gateway-DxCj_uok.js";import{u as st}from"./useAppMutation-Cix9n50u.js";import{D as qe,A as Ve,a as Qe,b as Ge,c as Ke,d as We,e as Je}from"./DialogShell-BbpG8sot.js";import{L as ce,I as le}from"./label-Da-JMxO2.js";import{S as at,a as rt,b as nt,c as ot,d as Ae}from"./select-BTwqvh0l.js";import{S as lt}from"./switch-CeKtgMDT.js";import{u as W}from"./i18n-Dp-o1LhZ.js";import{D as Lt}from"./disclosure-CJdf1-ap.js";import{P as cs,c as us,b as ms}from"./popover-JpUYyIhi.js";import{C as Xe,a as Ye}from"./card-DhuLMeO9.js";import{a as ct}from"./PageState-U6DpaNu4.js";import{b as ps}from"./types-DYz12j32.js";import"./radix-B9EIjzyN.js";function hs(a){const{t,pushToast:r,config:s,setConfig:l,configQuery:p,customEndpoints:h,tabs:j,ensureConfig:g}=a,y=ds(),[u,i]=v.useState({}),[o,d]=v.useState({}),[w,m]=v.useState(null),[N,b]=v.useState({}),[M,L]=v.useState({}),[U,B]=v.useState({}),[Y,x]=v.useState(null),[P,C]=v.useState(null),[z,G]=v.useState(null),[K,O]=v.useState(!1),[J,pe]=v.useState(null),[E,F]=v.useState({}),[V,Se]=v.useState(null),ue=v.useRef(null),[He,fe]=v.useState(null),ye=n=>{ue.current=n,fe(n)},Ne=()=>{ue.current=null,fe(null)},ne=v.useMemo(()=>j.filter(n=>n.key!=="providers"),[j]);v.useEffect(()=>{if(!p.data)return;const n=p.data;i(f=>{const c=mt(n,h);if(!f||Object.keys(f).length===0)return c;const k={...c};for(const[D,I]of Object.entries(f)){if(!(D in c))continue;const $=pt(n,h,D);if(ht(I,$))k[D]=I;else{const se=new Map(I.map(X=>[X.source,X.id]));k[D]=c[D].map(X=>({...X,id:se.get(X.source)??X.id}))}}return k}),F(f=>{const c=Xt(n,h);if(!f||Object.keys(f).length===0)return c;const k={...c};for(const[D,I]of Object.entries(f)){if(!(D in c))continue;const $=xt(n,h,D);JSON.stringify(I)!==JSON.stringify($)&&(k[D]=I)}return k}),d({}),b(gt(n,h))},[p.data,h]);const Me=(s==null?void 0:s.providers)??[],Pe=v.useMemo(()=>{const n=[],f=new Set;for(const c of Me){const k=c.label&&c.label!==c.id?`${c.label} (${c.id})`:c.id,D=c.models??[];if(D.length>0)for(const $ of D){const se=`${c.id}:${$.id}`;f.has(se)||(f.add(se),n.push({value:se,label:`${k} · ${$.label??$.id}`,providerId:c.id,providerLabel:k,modelId:$.id,modelLabel:$.label??$.id,kind:"model",isDefault:c.defaultModel===$.id}))}else if(c.defaultModel){const $=`${c.id}:${c.defaultModel}`;f.has($)||(f.add($),n.push({value:$,label:`${k} · ${c.defaultModel}`,providerId:c.id,providerLabel:k,modelId:c.defaultModel,modelLabel:c.defaultModel,kind:"model",isDefault:!0}))}const I=`${c.id}:*`;f.has(I)||(f.add(I),n.push({value:I,label:t("settings.routing.providerPassthroughOption",{provider:k}),providerId:c.id,providerLabel:k,modelId:"*",modelLabel:"*",kind:"passthrough"}))}for(const c of Object.values(u).flat()){const k=c.target.trim();k&&!f.has(k)&&(f.add(k),n.push({value:k,label:k,modelId:k,modelLabel:k,kind:"custom"}))}return n},[Me,u,t]),$e=n=>s?pt(s,h,n):{},De=v.useMemo(()=>{const n={};for(const f of ne){const c=u[f.key]||[];n[f.key]=ht(c,$e(f.key))}return n},[s,h,u,ne]),Te=v.useMemo(()=>{const n={};if(!s)return n;for(const f of ne){const c=E[f.key];if(!c){n[f.key]=!1;continue}const k=xt(s,h,f.key);n[f.key]=JSON.stringify(c)!==JSON.stringify(k)}return n},[s,h,E,ne]),Le=(n,f,c)=>{F(k=>({...k,[n]:{...k[n]??{completion:null,reasoning:null,background:null,longContextThreshold:6e4},[f]:c}}))},R=async n=>{var k,D,I,$,se,X,Z,de;if(!g()||ue.current)return;const f=E[n];if(!f)return;const c={completion:(k=f.completion)!=null&&k.trim()?f.completion.trim():null,reasoning:(D=f.reasoning)!=null&&D.trim()?f.reasoning.trim():null,background:(I=f.background)!=null&&I.trim()?f.background.trim():null,longContextThreshold:Number.isFinite(f.longContextThreshold)&&f.longContextThreshold>0?Math.floor(f.longContextThreshold):s.defaults.longContextThreshold};Se(n),ye(n);try{const oe=h.find(ee=>ee.id===n);if(oe){const ee={...oe.routing??{},defaults:c,modelRoutes:(($=oe.routing)==null?void 0:$.modelRoutes)??{}};await _e.update(n,{routing:ee}),l(xe=>{if(!xe)return xe;const et=[...xe.customEndpoints??[]],it=et.findIndex(Ot=>Ot.id===n);return it===-1?xe:(et[it]={...et[it],routing:ee},{...xe,customEndpoints:et})}),await y.invalidateQueries({queryKey:Ee.customEndpoints.all()})}else{const ee=n,xe={...s,endpointRouting:{...s.endpointRouting??{},[ee]:{defaults:c,modelRoutes:((X=(se=s.endpointRouting)==null?void 0:se[ee])==null?void 0:X.modelRoutes)??(ee==="anthropic"?s.modelRoutes??{}:{}),compatibility:(de=(Z=s.endpointRouting)==null?void 0:Z[ee])==null?void 0:de.compatibility}}};await Ie.saveConfig(xe),l(xe)}F(ee=>({...ee,[n]:c})),r({title:t("workbench.defaults.saveSuccess"),variant:"success"}),p.refetch()}catch(oe){r({title:t("workbench.defaults.saveFailure",{message:ge(oe).message}),variant:"error"})}finally{Se(null),Ne()}},q=(n,f)=>{b(c=>({...c,[n]:f})),l(c=>{if(!c)return c;if(n==="anthropic"||n==="openai")return{...c,routingPresets:{...c.routingPresets,[n]:f}};const k=[...c.customEndpoints??[]],D=k.findIndex(I=>I.id===n);return D===-1?c:(k[D]={...k[D],routingPresets:f},{...c,customEndpoints:k})})},Q=(n,f)=>{L(c=>({...c,[n]:f})),f.trim()&&B(c=>({...c,[n]:null}))},T=async n=>{if(!g()||ue.current)return;const f=(M[n]??"").trim();if(!f){B(c=>({...c,[n]:t("modelManagement.validation.presetName")}));return}if((N[n]??[]).some(c=>c.name.toLowerCase()===f.toLowerCase())){B(c=>({...c,[n]:t("modelManagement.validation.presetDuplicate",{name:f})}));return}x(n),ye(n);try{const k=(await Be.savePreset(n,f)).presets??[];q(n,k),L(D=>({...D,[n]:""})),B(D=>({...D,[n]:null})),r({title:t("modelManagement.toast.presetSaved",{name:f}),variant:"success"})}catch(c){r({title:t("modelManagement.toast.presetSaveFailure",{message:ge(c).message}),variant:"error"})}finally{x(null),Ne(),p.refetch()}},ae=async(n,f)=>{if(g()&&!ue.current){C({endpoint:n,name:f.name}),ye(n);try{const k=(await Be.applyPreset(n,f.name)).config;l(k);const D=mt(k,h);i(I=>({...I,[n]:D[n]??[]})),b(gt(k,h)),n!=="anthropic"&&n!=="openai"&&await y.invalidateQueries({queryKey:Ee.customEndpoints.all()}),r({title:t("modelManagement.toast.presetApplySuccess",{name:f.name}),variant:"success"})}catch(c){r({title:t("modelManagement.toast.presetApplyFailure",{message:ge(c).message}),variant:"error"})}finally{C(null),Ne(),p.refetch()}}},be=async(n,f)=>{if(g()&&!ue.current){G({endpoint:n,name:f.name}),ye(n);try{const c=await Be.deletePreset(n,f.name);q(n,c.presets??[]),r({title:t("modelManagement.toast.presetDeleteSuccess",{name:f.name}),variant:"success"})}catch(c){r({title:t("modelManagement.toast.presetDeleteFailure",{message:ge(c).message}),variant:"error"})}finally{G(null),Ne(),p.refetch()}}},we=async n=>{const f=h.find(c=>c.id===n);if(!(!f||f.deletable===!1))try{await _e.delete(n),await y.invalidateQueries({queryKey:Ee.customEndpoints.all()}),l(c=>c&&{...c,customEndpoints:(c.customEndpoints??[]).filter(k=>k.id!==n)}),p.refetch(),r({title:t("modelManagement.deleteEndpointSuccess"),variant:"success"})}catch(c){const k=ge(c);r({title:t("modelManagement.deleteEndpointError",{error:k.message}),variant:"error"})}},S=n=>{i(f=>({...f,[n]:[...f[n]||[],{id:ze(),source:"",target:""}]})),d(f=>({...f,[n]:null}))},_=async(n,f)=>{if(g()&&!ue.current){O(!0),ye(n);try{if(n==="anthropic"||n==="openai"){const c=n,k=s.endpointRouting?{...s.endpointRouting}:{},D=k[c]??{defaults:s.defaults,modelRoutes:(c==="anthropic"?s.modelRoutes:{})??{}},I={defaults:D.defaults??s.defaults,modelRoutes:D.modelRoutes??{}},$={...s,endpointRouting:{...k,[c]:f?{...I,compatibility:{enabled:!0}}:{...I}}};await Ie.saveConfig($),l($)}else{const c=[...s.customEndpoints??[]],k=c.findIndex(se=>se.id===n);if(k===-1)throw new Error(t("modelManagement.toast.endpointNotFound"));const D=c[k],I=D.routing??{defaults:s.defaults,modelRoutes:{}};c[k]={...D,routing:f?{...I,compatibility:{enabled:!0}}:{defaults:I.defaults,modelRoutes:I.modelRoutes}};const $={...s,customEndpoints:c};await Ie.saveConfig($),l($)}r({title:t("modelManagement.toast.compatibilitySaved",{state:t(f?"common.status.enabled":"common.status.disabled")}),variant:"success"}),p.refetch()}catch(c){const k=ge(c);r({title:t("modelManagement.toast.compatibilitySaveFailure",{message:k.message}),variant:"error"})}finally{O(!1),Ne()}}},H=(n,f)=>{i(c=>{const k=c[n]||[];return k.some(D=>D.source.trim()===f.trim())?c:{...c,[n]:[...k,{id:ze(),source:f,target:""}]}}),d(c=>({...c,[n]:null}))},ve=(n,f,c,k)=>{i(D=>({...D,[n]:(D[n]||[]).map(I=>I.id===f?{...I,[c]:k}:I)})),d(D=>({...D,[n]:null}))},Ce=(n,f)=>{i(c=>({...c,[n]:(c[n]||[]).filter(k=>k.id!==f)})),d(c=>({...c,[n]:null}))},me=(n,f,c)=>{f!==c&&(i(k=>{const D=k[n]||[],I=D.findIndex(se=>se.id===f),$=D.findIndex(se=>se.id===c);return I===-1||$===-1?k:{...k,[n]:Ft(D,I,$)}}),d(k=>({...k,[n]:null})))},Ze=n=>{var c;if(!s)return;const f=(s.customEndpoints??h).find(k=>k.id===n);if(f)i(k=>{var D;return{...k,[n]:Object.entries(((D=f.routing)==null?void 0:D.modelRoutes)??{}).map(([I,$])=>({id:ze(),source:I,target:$}))}});else{const k=s.endpointRouting??{},D=n,I=D==="anthropic"?s.modelRoutes??{}:{},$=((c=k[D])==null?void 0:c.modelRoutes)??I;i(se=>({...se,[n]:Object.entries($).map(([X,Z])=>({id:ze(),source:X,target:Z}))}))}d(k=>({...k,[n]:null}))},te=st({mutationFn:async n=>(await Ie.saveConfig(n.nextConfig),n)}),ie=st({mutationFn:async n=>(await _e.update(n.endpoint,{routing:n.routing}),n)});return{endpointTabs:ne,routesByEndpoint:u,setRoutesByEndpoint:i,routeError:o,savingRouteFor:w,presetsByEndpoint:N,presetNameByEndpoint:M,presetErrorByEndpoint:U,savingPresetFor:Y,applyingPreset:P,deletingPreset:z,savingCompatibilityPolicy:K,writingEndpoint:He,presetDiffDialog:J,setPresetDiffDialog:pe,providerModelOptions:Pe,isDirtyByEndpoint:De,defaultsByEndpoint:E,isDefaultsDirtyByEndpoint:Te,savingDefaultsFor:V,handleDefaultsChange:Le,handleSaveDefaults:R,handlePresetNameChange:Q,handleSavePreset:T,handleApplyPreset:ae,handleDeletePreset:be,handleDeleteEndpoint:we,handleAddRoute:S,handleAddSuggestion:H,handleRouteChange:ve,handleRemoveRoute:Ce,handleReorderRules:me,handleResetRoutes:Ze,handleSaveRoutes:async n=>{var k,D,I,$,se;if(!g()||ue.current)return;const f=u[n]||[],c={};for(const X of f){const Z=X.source.trim(),de=X.target.trim();if(!(!Z&&!de)){if(!Z||!de){d(oe=>({...oe,[n]:t("settings.validation.routePair")}));return}if(c[Z]){d(oe=>({...oe,[n]:t("settings.validation.routeDuplicate",{model:Z})}));return}c[Z]=de}}d(X=>({...X,[n]:null})),m(n),ye(n);try{const X=h.find(Z=>Z.id===n);if(X){const Z={...X.routing??{},modelRoutes:c,defaults:((k=X.routing)==null?void 0:k.defaults)||s.defaults};await ie.mutateAsync({endpoint:n,routing:Z}),l(de=>{if(!de)return de;const oe=[...de.customEndpoints??[]],ee=oe.findIndex(xe=>xe.id===n);return ee===-1?de:(oe[ee]={...oe[ee],routing:Z},{...de,customEndpoints:oe})}),await y.invalidateQueries({queryKey:Ee.customEndpoints.all()})}else{const Z={...s,endpointRouting:{...s.endpointRouting??{},[n]:{defaults:((I=(D=s.endpointRouting)==null?void 0:D[n])==null?void 0:I.defaults)??s.defaults,modelRoutes:c,compatibility:(se=($=s.endpointRouting)==null?void 0:$[n])==null?void 0:se.compatibility}},modelRoutes:n==="anthropic"?c:s.modelRoutes??{}};await te.mutateAsync({endpoint:n,nextConfig:Z}),l(Z)}i(Z=>{const de=Z[n]??[],oe=new Map(de.map(ee=>[ee.source.trim(),ee.id]));return{...Z,[n]:Object.entries(c).map(([ee,xe])=>({id:oe.get(ee.trim())??ze(),source:ee,target:xe}))}}),r({title:t("modelManagement.toast.routesSaved"),variant:"success"}),p.refetch()}catch(X){r({title:t("modelManagement.toast.routesSaveFailure",{message:ge(X).message}),variant:"error"})}finally{m(null),Ne()}},handleCompatibilityEnabledChange:_,sanitizeDraftsForProvider:n=>{i(f=>{const c={};for(const[k,D]of Object.entries(f))c[k]=D.filter(I=>!Yt(I.target.trim(),n));return c})}}}function xs(a,t){const{t:r,pushToast:s,config:l,setConfig:p,configQuery:h,customEndpoints:j,ensureConfig:g}=a,{sanitizeDraftsForProvider:y}=t??{},[u,i]=v.useState(""),[o,d]=v.useState("all"),[w,m]=v.useState(!1),[N,b]=v.useState("create"),[M,L]=v.useState(void 0),[U,B]=v.useState(null),[Y,x]=v.useState({}),[P,C]=v.useState(!1),[z,G]=v.useState(null),[K,O]=v.useState(!0),[J,pe]=v.useState({}),[E,F]=v.useState(null),V=(l==null?void 0:l.providers)??[],Se=V.length,ue=v.useMemo(()=>V.filter(R=>{var ae;if(!(o==="all"||(R.type??"custom")===o))return!1;const Q=u.trim().toLowerCase();return Q?[R.id,R.label??"",R.baseUrl??"",R.defaultModel??"",...((ae=R.models)==null?void 0:ae.map(be=>be.id))??[]].join(" ").toLowerCase().includes(Q):!0}),[u,o,V]),He=v.useMemo(()=>{const R=new Map;for(const q of V){if(!q.defaultModel||!q.models)continue;const Q=q.models.find(T=>T.id===q.defaultModel);Q&&R.set(q.id,Zt(Q))}return R},[V]),fe=v.useMemo(()=>[{key:"anthropic-beta",value:"claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14",label:r("providers.testDialog.options.beta.label"),description:r("providers.testDialog.options.beta.description")}],[r]),ye=()=>{g()&&(b("create"),L(void 0),m(!0))},Ne=R=>{g()&&(b("edit"),L(R),m(!0))},ne=async R=>{if(!l)throw new Error(r("settings.toast.missingConfig"));const q=N==="create"?[...V,R]:V.map(T=>M&&T.id===M.id?{...R,id:M.id}:T),Q={...l,providers:q};await Ie.saveConfig(Q),p(Q),h.refetch(),s({title:N==="create"?r("providers.toast.createSuccess",{name:R.label||R.id}):r("providers.toast.updateSuccess",{name:R.label||R.id}),variant:"success"})},Me=(R,q)=>{x(Q=>({...Q,[R]:q}))},Pe=async(R,q)=>{B(R.id);try{const Q=q&&(q.headers||q.query)?{headers:q.headers&&Object.keys(q.headers).length>0?q.headers:void 0,query:q.query&&q.query.trim().length>0?q.query.trim():void 0}:void 0,T=await Be.testProvider(R.id,Q);if(T.ok){Me(R.id,{ok:!0,status:T.status,statusText:T.statusText,durationMs:T.durationMs,testedAt:Date.now()}),s({title:r("providers.toast.testSuccess"),description:r("providers.toast.testSuccessDesc",{status:T.status,duration:T.durationMs?`${T.durationMs} ms`:"—"}),variant:"success"});return}Me(R.id,{ok:!1,status:T.status,statusText:T.statusText,durationMs:T.durationMs,message:`${T.status} ${T.statusText}`,testedAt:Date.now()}),s({title:r("providers.toast.testFailure",{message:`${T.status} ${T.statusText}`}),variant:"error"})}catch(Q){const T=ge(Q),ae=T.status?`${T.status} ${T.message}`:T.message;Me(R.id,{ok:!1,status:T.status,message:ae,testedAt:Date.now()}),s({title:r("providers.toast.testFailure",{message:ae}),variant:"error"})}finally{B(null)}},$e=R=>{var we,S;if(!(!!((we=R.defaultModel)!=null&&we.trim())||!!((S=R.models)!=null&&S.some(_=>_.id.trim().length>0)))){F(R);return}if(R.type!=="anthropic"){Pe(R);return}const Q=R.extraHeaders??{},T=new Map(fe.map(_=>[_.key.toLowerCase(),_])),ae={};let be=!0;for(const _ of fe){const H=Object.entries(Q).find(([me])=>me.toLowerCase()===_.key.toLowerCase());if(!H)continue;const[ve,Ce]=H;String(Ce??"")!==_.value&&(be=!1,ae[ve]=String(Ce??""))}for(const[_,H]of Object.entries(Q))T.has(_.toLowerCase())||(ae[_]=String(H??""));pe(ae),O(be),G(R),C(!0)},De=()=>{C(!1),G(null),O(!0),pe({})};return{providers:V,providerCount:Se,filteredProviders:ue,providerSearch:u,setProviderSearch:i,providerTypeFilter:o,setProviderTypeFilter:d,defaultLabels:He,drawerOpen:w,setDrawerOpen:m,drawerMode:N,setDrawerMode:b,editingProvider:M,setEditingProvider:L,testingProviderId:U,testResults:Y,testDialogOpen:P,testDialogProvider:z,testDialogUsePreset:K,setTestDialogUsePreset:O,testDialogPreservedExtras:J,noModelDialogProvider:E,setNoModelDialogProvider:F,anthropicTestHeaderOptions:fe,handleOpenCreate:ye,handleOpenEdit:Ne,handleProviderSubmit:ne,handleDeleteProvider:async R=>{var _,H,ve,Ce,me,Ze;if(!g())return;const q=V.filter(te=>te.id!==R.id).map(te=>{if(te.type!=="aggregate"||!te.models)return te;const ie=te.models.map(he=>({...he,members:(he.members??[]).filter(n=>n.target.split(":")[0]!==R.id)})).filter(he=>(he.members??[]).length>0),Re=ie.some(he=>he.id===te.defaultModel)?te.defaultModel:void 0;return{...te,models:ie,defaultModel:Re}}),Q=te=>{const ie={};if(!te)return ie;for(const[Re,he]of Object.entries(te)){if(!he)continue;const[n]=he.split(":");n&&n===R.id||he===R.id||(ie[Re]=he)}return ie},T=(l==null?void 0:l.endpointRouting)??{},ae=Q(((_=T.anthropic)==null?void 0:_.modelRoutes)??(l==null?void 0:l.modelRoutes)??{}),be=Q(((H=T.openai)==null?void 0:H.modelRoutes)??{}),we=((l==null?void 0:l.customEndpoints)??j).map(te=>{const ie=te.routing,Re=ie==null?void 0:ie.modelRoutes;return Re?{...te,routing:{...ie,defaults:ie.defaults??l.defaults,modelRoutes:Q(Re)}}:te}),S={...l,providers:q,modelRoutes:ae,customEndpoints:we,endpointRouting:{anthropic:{defaults:((ve=T.anthropic)==null?void 0:ve.defaults)??l.defaults,modelRoutes:ae,compatibility:(Ce=T.anthropic)==null?void 0:Ce.compatibility},openai:{defaults:((me=T.openai)==null?void 0:me.defaults)??l.defaults,modelRoutes:be,compatibility:(Ze=T.openai)==null?void 0:Ze.compatibility}}};try{await Ie.saveConfig(S),p(S),y==null||y(R.id),(M==null?void 0:M.id)===R.id&&(m(!1),L(void 0),b("create")),s({title:r("providers.toast.deleteSuccess",{name:R.label||R.id}),variant:"success"}),h.refetch()}catch(te){s({title:r("providers.toast.deleteFailure",{message:ge(te).message}),variant:"error"})}},handleTestConnection:Pe,initiateTestConnection:$e,closeTestDialog:De,confirmTestDialog:async()=>{if(!z)return;const R={};if(K)for(const T of fe)R[T.key]=T.value;const q=new Map(fe.map(T=>[T.key.toLowerCase(),T]));for(const[T,ae]of Object.entries(J))q.get(T.toLowerCase())&&K||(R[T]=ae);const Q=z;De(),await Pe(Q,{headers:Object.keys(R).length>0?R:void 0})}}}const gs=["anthropic","openai-auto","openai-chat","openai-responses"];function fs({open:a,endpoint:t,onClose:r,onSuccess:s}){const{t:l}=W(),[p,h]=v.useState({id:"",label:"",paths:[{path:"",protocol:"openai-auto"}],enabled:!0});v.useEffect(()=>{if(a){if(t){const m=t.paths&&t.paths.length>0?t.paths:t.path&&t.protocol?[{path:t.path,protocol:t.protocol}]:[{path:"",protocol:"openai-auto"}];h({id:t.id,label:t.label,paths:m,enabled:t.enabled!==!1});return}h({id:"",label:"",paths:[{path:"",protocol:"openai-auto"}],enabled:!0})}},[t,a]);const j=st({mutationFn:_e.create,invalidateKeys:[Ee.customEndpoints.all()],successToast:()=>({title:l("modelManagement.createEndpointSuccess")}),errorToast:m=>({title:l("modelManagement.createEndpointError",{error:m.message})}),onSuccess:async()=>{s(),r()}}),g=st({mutationFn:m=>_e.update(m.id,m.updates),invalidateKeys:[Ee.customEndpoints.all()],successToast:()=>({title:l("modelManagement.updateEndpointSuccess")}),errorToast:m=>({title:l("modelManagement.updateEndpointError",{error:m.message})}),onSuccess:async()=>{s(),r()}}),y=()=>{h(m=>({...m,paths:[...m.paths,{path:"",protocol:"anthropic"}]}))},u=m=>{p.paths.length!==1&&h(N=>({...N,paths:N.paths.filter((b,M)=>M!==m)}))},i=(m,N,b)=>{h(M=>{const L=[...M.paths];return L[m]={...L[m],[N]:b},{...M,paths:L}})},o=m=>{if(m==null||m.preventDefault(),!p.id.trim()||!p.label.trim())return;for(const b of p.paths)if(!b.path.trim())return;const N=p.paths.map(b=>({path:b.path.trim(),protocol:b.protocol}));if(t){g.mutate({id:t.id,updates:{label:p.label.trim(),paths:N,enabled:p.enabled}});return}j.mutate({id:p.id.trim(),label:p.label.trim(),paths:N,enabled:p.enabled})},d=j.isPending||g.isPending,w=p.paths.length===0?l("modelManagement.atLeastOnePath"):!p.id.trim()||!p.label.trim()?l("modelManagement.endpointValidationError"):p.paths.some(m=>!m.path.trim())?l("modelManagement.pathValidationError"):null;return e.jsx(qe,{open:a,onOpenChange:m=>!m&&r(),children:e.jsxs(Ve,{className:"max-w-lg",onInteractOutside:m=>m.preventDefault(),children:[e.jsxs(Qe,{children:[e.jsx(Ge,{children:l(t?"modelManagement.editEndpoint":"modelManagement.createEndpoint")}),e.jsx(Ke,{className:"truncate font-mono text-xs",children:t?t.id:l("modelManagement.endpointRoutingHint")})]}),e.jsx(We,{children:e.jsxs("form",{id:"endpoint-form",onSubmit:o,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ce,{children:[l("modelManagement.endpointId")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(le,{value:p.id,onChange:m=>h(N=>({...N,id:m.target.value})),placeholder:l("modelManagement.endpointIdPlaceholder"),disabled:!!t,required:!0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l("modelManagement.endpointIdHint")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ce,{children:[l("modelManagement.endpointLabel")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(le,{value:p.label,onChange:m=>h(N=>({...N,label:m.target.value})),placeholder:l("modelManagement.endpointLabelPlaceholder"),required:!0})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ce,{children:[l("modelManagement.endpointPaths")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsxs(A,{type:"button",variant:"ghost",size:"sm",onClick:y,children:[e.jsx(It,{className:"mr-1 h-3 w-3"}),l("modelManagement.addPath")]})]}),e.jsx("div",{className:"space-y-3",children:p.paths.map((m,N)=>e.jsxs("div",{className:"space-y-2 rounded-xl border border-transparent bg-card p-3 shadow-[var(--surface-shadow)]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(le,{value:m.path,onChange:b=>i(N,"path",b.target.value),placeholder:l("modelManagement.endpointPathPlaceholder"),required:!0}),e.jsxs(at,{value:m.protocol,onValueChange:b=>i(N,"protocol",b),children:[e.jsx(rt,{children:e.jsx(nt,{})}),e.jsx(ot,{children:gs.map(b=>e.jsx(Ae,{value:b,children:l(b==="anthropic"?"modelManagement.protocolAnthropic":b==="openai-auto"?"modelManagement.protocolOpenAI":b==="openai-chat"?"modelManagement.protocolOpenAIChat":"modelManagement.protocolOpenAIResponses")},b))})]})]}),p.paths.length>1?e.jsx(A,{type:"button",variant:"ghost",size:"sm",onClick:()=>u(N),className:"text-destructive",children:e.jsx(ut,{className:"h-4 w-4"})}):null]}),e.jsxs("div",{className:"space-y-1 text-xs text-muted-foreground",children:[N===0?e.jsx("p",{children:l("modelManagement.endpointPathHint")}):null,e.jsx("p",{children:l(`modelManagement.protocolHints.${m.protocol}`)})]})]},`${m.protocol}-${N}`))}),w?e.jsx("p",{className:"text-xs text-destructive",children:w}):null]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(lt,{id:"endpoint-enabled",checked:p.enabled,onCheckedChange:m=>h(N=>({...N,enabled:m}))}),e.jsx(ce,{htmlFor:"endpoint-enabled",children:l("modelManagement.endpointEnabled")})]}),t?null:e.jsx("div",{className:"rounded-xl bg-accent p-4",children:e.jsx("p",{className:"text-sm text-primary",children:l("modelManagement.endpointRoutingHint")})})]})}),e.jsxs(Je,{children:[e.jsx(A,{variant:"outline",onClick:r,disabled:d,children:l("common.cancel")}),e.jsx(A,{type:"submit",form:"endpoint-form",disabled:d,children:l(d?"common.saving":t?"common.save":"common.create")})]})]})})}function bs({open:a,provider:t,onClose:r,onEdit:s}){const{t:l}=W();return t?e.jsx(qe,{open:a,onOpenChange:p=>!p&&r(),children:e.jsxs(Ve,{className:"max-w-md",children:[e.jsxs(Qe,{children:[e.jsx(Ge,{children:l("providers.noModelDialog.title")}),e.jsx(Ke,{children:l("providers.noModelDialog.subtitle",{name:t.label||t.id})})]}),e.jsxs(We,{className:"space-y-4",children:[e.jsx("div",{className:"rounded-xl bg-accent p-4 text-sm text-primary",children:l("providers.noModelDialog.description")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l("providers.noModelDialog.hint")})]}),e.jsxs(Je,{children:[e.jsx(A,{variant:"outline",onClick:r,children:l("common.actions.close")}),e.jsx(A,{onClick:()=>s(t),children:l("providers.noModelDialog.primary")})]})]})}):null}function vs({dialog:a,currentRoutes:t,onConfirm:r,onClose:s}){const{t:l}=W();if(!a)return null;const{endpoint:p,preset:h}=a,j=h.modelRoutes??{},g={};for(const w of t){const m=w.source.trim(),N=w.target.trim();m&&N&&(g[m]=N)}const y=new Set([...Object.keys(g),...Object.keys(j)]),u=[],i=[],o=[];for(const w of y){const m=w in g,N=w in j;N&&!m?u.push([w,j[w]]):m&&!N?i.push([w,g[w]]):m&&N&&g[w]!==j[w]&&o.push([w,g[w],j[w]])}const d=u.length>0||i.length>0||o.length>0;return e.jsx(qe,{open:!0,onOpenChange:w=>!w&&s(),children:e.jsxs(Ve,{className:"max-w-2xl",children:[e.jsxs(Qe,{children:[e.jsx(Ge,{children:l("modelManagement.presets.diffTitle")}),e.jsx(Ke,{children:l("modelManagement.presets.diffDescription",{name:h.name})})]}),e.jsx(We,{children:d?e.jsxs("div",{className:"max-h-80 space-y-2 rounded-xl bg-secondary/50 p-3 text-sm",children:[u.map(([w,m])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-success-bg px-2 py-1.5 text-success",children:[e.jsx(re,{variant:"outline",className:"border-success/30 text-xs",children:l("modelManagement.presets.diffAdded")}),e.jsx("span",{className:"truncate",children:w}),e.jsx(ke,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:m})]},`add-${w}`)),i.map(([w,m])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-error-bg px-2 py-1.5 text-error",children:[e.jsx(re,{variant:"outline",className:"border-error/30 text-xs",children:l("modelManagement.presets.diffRemoved")}),e.jsx("span",{className:"truncate",children:w}),e.jsx(ke,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:m})]},`rm-${w}`)),o.map(([w,m,N])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-warning-bg px-2 py-1.5 text-warning",children:[e.jsx(re,{variant:"outline",className:"border-warning/30 text-xs",children:l("modelManagement.presets.diffChanged")}),e.jsx("span",{className:"truncate",children:w}),e.jsx(ke,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate line-through opacity-60",children:m}),e.jsx(ke,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:N})]},`chg-${w}`))]}):e.jsx("p",{className:"rounded-xl bg-secondary/50 py-8 text-center text-sm text-muted-foreground",children:l("modelManagement.presets.diffEmpty")})}),e.jsxs(Je,{children:[e.jsx(A,{variant:"outline",onClick:s,children:l("common.cancel")}),e.jsx(A,{onClick:()=>r(p,h),disabled:!d,children:l("modelManagement.presets.diffConfirm")})]})]})})}const ft=6;function Ue({value:a,onChange:t,options:r,disabled:s,placeholder:l,ariaLabel:p}){const{t:h}=W(),j=v.useId(),[g,y]=v.useState(!1),[u,i]=v.useState(""),o=v.useRef(null),d=v.useRef(!1),[w,m]=qt(Vt.modelManagement.recentRouteTargets,[]),N=v.useMemo(()=>{const x=new Map;for(const P of r)x.set(P.value,P);return x},[r]),b=(x,P)=>P?[x.label,x.value,x.providerId??"",x.providerLabel??"",x.modelId??"",x.modelLabel??""].join(" ").toLowerCase().includes(P):!0,M=v.useMemo(()=>{const x=u.trim().toLowerCase(),P=r.filter(O=>b(O,x)),C=w.map(O=>N.get(O)??(x?void 0:{value:O,label:O,kind:"custom"})).filter(O=>!!O).filter(O=>b(O,x)).slice(0,ft),z=[];C.length>0&&z.push({key:"recent",label:h("modelManagement.targetPicker.recent"),options:C});const G=new Map,K=[];for(const O of P){if(O.kind==="custom"||!O.providerId){K.push(O);continue}const J=`provider:${O.providerId}`,pe=G.get(J);pe?pe.options.push(O):G.set(J,{key:J,label:O.providerLabel??O.providerId,options:[O]})}return z.push(...G.values()),K.length>0&&z.push({key:"custom",label:h("modelManagement.targetPicker.custom"),options:K,muted:!0}),z},[N,r,w,u,h]),L=M.reduce((x,P)=>x+P.options.length,0),U=x=>{t(x),m(P=>[x,...P.filter(C=>C!==x)].slice(0,ft)),i(""),d.current=!0,typeof document<"u"&&document.activeElement instanceof HTMLElement&&document.activeElement.blur(),y(!1),typeof window<"u"?window.requestAnimationFrame(()=>{d.current=!1}):d.current=!1},B=x=>x.kind==="passthrough"?h("modelManagement.targetPicker.passthrough"):x.kind==="custom"?h("modelManagement.targetPicker.customValue"):h("modelManagement.targetPicker.model"),Y=x=>x.kind==="passthrough"||x.kind==="custom"?x.label:x.modelLabel??x.label;return e.jsxs(cs,{open:g,onOpenChange:x=>{x&&d.current||(y(x),x&&i(""))},children:[e.jsx(us,{asChild:!0,children:e.jsx(le,{value:a,onChange:x=>{t(x.target.value),i(x.target.value),g||y(!0)},onFocus:()=>{i(""),y(!0)},onClick:()=>{g||y(!0)},placeholder:l,disabled:s,autoComplete:"off",role:"combobox","aria-label":p,"aria-expanded":g,"aria-controls":j,"aria-autocomplete":"list"})}),e.jsxs(ms,{className:"flex max-h-[min(28rem,var(--radix-popover-content-available-height))] flex-col overflow-hidden rounded-xl border border-[color:var(--surface-border)] bg-popover p-0 shadow-[var(--surface-shadow-lg)]",style:{width:"max(var(--radix-popover-trigger-width), 360px)"},align:"start",onOpenAutoFocus:x=>{var P;x.preventDefault(),(P=o.current)==null||P.focus()},onCloseAutoFocus:x=>{x.preventDefault()},children:[e.jsxs("div",{className:"space-y-2 border-b border-border px-3 py-3",children:[e.jsx(le,{ref:o,value:u,onChange:x=>i(x.target.value),placeholder:h("modelManagement.targetPicker.searchPlaceholder"),className:"h-9",autoComplete:"off"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:u.trim()?h("modelManagement.targetPicker.matchCount",{count:L}):h("modelManagement.targetPicker.helper")})]}),L===0?e.jsx("div",{className:"px-3 py-4 text-center text-xs text-muted-foreground",children:h("common.noMatches")}):e.jsx("div",{id:j,role:"listbox",className:"min-h-0 flex-1 overflow-y-auto p-1.5",children:M.map(x=>e.jsxs("div",{className:"py-1",children:[e.jsxs("div",{className:je("sticky top-0 z-10 flex items-center justify-between bg-popover px-2 py-1 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",x.muted&&"opacity-80"),children:[e.jsx("span",{className:"truncate",children:x.label}),e.jsx("span",{children:x.options.length})]}),e.jsx("div",{className:"space-y-1",children:x.options.map(P=>e.jsxs("button",{type:"button",role:"option","aria-selected":P.value===a.trim(),className:je("flex w-full min-w-0 items-center gap-2 rounded-lg px-3 py-2 text-left text-sm transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",P.value===a.trim()&&"bg-accent text-accent-foreground"),onMouseDown:C=>{C.preventDefault()},onClick:()=>U(P.value),children:[e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate font-medium",children:Y(P)}),e.jsx("span",{className:"block truncate text-xs text-muted-foreground",children:P.value})]}),e.jsxs("span",{className:"flex shrink-0 items-center gap-1",children:[P.isDefault?e.jsx(re,{variant:"secondary",className:"text-[10px]",children:h("modelManagement.targetPicker.default")}):null,e.jsx(re,{variant:P.kind==="passthrough"?"outline":"secondary",className:"text-[10px]",children:B(P)})]})]},`${x.key}-${P.value}`))})]},x.key))})]})]})}function js(a){const{t}=W(),{form:r,errors:s,onModelIdChange:l,onAddModel:p,onRemoveModel:h,onAddMember:j,onRemoveMember:g,onMemberTargetChange:y,onReorderMembers:u,onModelFailoverChange:i,memberOptions:o}=a;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(A,{type:"button",variant:"outline",size:"sm",onClick:p,className:"bg-card text-xs",children:t("providers.drawer.fields.addModel")})]}),s.models?e.jsx("p",{className:"text-xs text-destructive",children:s.models}):null,e.jsxs("div",{className:"space-y-4",children:[r.models.map((d,w)=>{var m,N;return e.jsxs("div",{"data-testid":"aggregate-model-card",className:"rounded-xl border border-transparent bg-card p-4 shadow-[var(--surface-shadow)]",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(ce,{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(le,{value:d.id,onChange:b=>l(w,b.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(ys,{modelKey:d._key,members:d.members,options:o,error:(m=s.members)==null?void 0:m[d._key],onAddMember:j,onRemoveMember:g,onMemberTargetChange:y,onReorderMembers:u}),e.jsxs(Lt,{summary:t("providers.aggregate.drawer.failoverTitle"),className:"mt-4 rounded-xl 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(ce,{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(le,{type:"number",min:1,value:d.failover.consecutiveFailures,onChange:b=>i(d._key,{consecutiveFailures:b.target.value}),placeholder:t("providers.aggregate.drawer.consecutiveFailuresHint")})]}),e.jsxs(ce,{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(le,{type:"number",min:1,max:86400,value:d.failover.cooldownSeconds,onChange:b=>i(d._key,{cooldownSeconds:b.target.value}),placeholder:t("providers.aggregate.drawer.cooldownSecondsHint")})]}),e.jsxs(ce,{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(le,{type:"number",min:1,value:d.failover.failureWindowSeconds,onChange:b=>i(d._key,{failureWindowSeconds:b.target.value}),placeholder:t("providers.aggregate.drawer.failureWindowSecondsHint")})]})]}),e.jsxs(ce,{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(le,{value:d.failover.triggerStatusCodes,onChange:b=>i(d._key,{triggerStatusCodes:b.target.value}),placeholder:t("providers.aggregate.drawer.triggerStatusCodesHint"),className:"font-mono text-xs",spellCheck:!1})]}),(N=s.failover)!=null&&N[d._key]?e.jsx("p",{className:"text-xs text-destructive",children:s.failover[d._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(A,{type:"button",variant:"ghost",size:"sm",className:"h-auto px-2 text-destructive",onClick:()=>h(w),children:t("providers.drawer.fields.removeModel")})})]},d._key)}),r.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 ys({modelKey:a,members:t,options:r,error:s,onAddMember:l,onRemoveMember:p,onMemberTargetChange:h,onReorderMembers:j}){const{t:g}=W(),y=bt(tt(yt,{activationConstraint:{distance:6}}),tt(jt,{coordinateGetter:vt})),u=i=>{const{active:o,over:d}=i;!d||o.id===d.id||j(a,String(o.id),String(d.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:g("providers.aggregate.drawer.membersTitle")}),e.jsx(A,{type:"button",variant:"outline",size:"sm","data-testid":"aggregate-add-member",onClick:()=>l(a),className:"h-7 bg-card px-2.5 text-[11px]",children:g("providers.aggregate.drawer.addMember")})]}),s?e.jsx("p",{className:"text-xs text-destructive",children:s}):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:g("providers.aggregate.drawer.memberEmptyHint")}):e.jsx(Nt,{sensors:y,collisionDetection:wt,onDragEnd:u,children:e.jsx(kt,{items:t.map(i=>i._key),strategy:Ct,children:e.jsx("div",{className:"flex flex-col gap-1.5",children:t.map((i,o)=>e.jsx(Ns,{modelKey:a,member:i,index:o,options:r,onRemoveMember:p,onMemberTargetChange:h},i._key))})})}),e.jsx("p",{className:"text-[11px] leading-relaxed text-muted-foreground",children:g("providers.aggregate.drawer.memberHint")})]})}function Ns({modelKey:a,member:t,index:r,options:s,onRemoveMember:l,onMemberTargetChange:p}){const{t:h}=W(),{attributes:j,listeners:g,setNodeRef:y,setActivatorNodeRef:u,transform:i,transition:o,isDragging:d}=St({id:t._key});return e.jsxs("div",{ref:y,"data-testid":"aggregate-member-row",style:{transform:Pt.Transform.toString(i),transition:o},className:je("flex items-center gap-2 border border-border bg-card p-2",d&&"z-10 opacity-60 shadow-[var(--surface-shadow-lg)]"),children:[e.jsx("button",{ref:u,type:"button","data-testid":"aggregate-member-grip","aria-label":h("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",...j,...g,children:e.jsx(Mt,{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:r+1}),r===0?e.jsx(re,{variant:"outline",className:"shrink-0 px-1.5 text-[10px] font-normal text-muted-foreground",children:h("providers.aggregate.drawer.primaryBadge")}):null,e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(Ue,{value:t.target,onChange:w=>p(a,t._key,w),options:s,placeholder:h("providers.aggregate.drawer.memberPlaceholder"),ariaLabel:h("providers.aggregate.drawer.memberTarget")})}),e.jsx(A,{variant:"ghost",size:"icon","data-testid":"aggregate-member-delete",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>l(a,t._key),"aria-label":h("common.delete"),children:e.jsx(ut,{className:"h-3.5 w-3.5","aria-hidden":!0})})]})}function ws({open:a,providerId:t,providerName:r,existingModelIds:s,draft:l,onImport:p,onClose:h}){const{t:j}=W(),{pushToast:g}=Qt(),[y,u]=v.useState({phase:"loading"}),[i,o]=v.useState(""),[d,w]=v.useState(new Set),m=v.useRef(l);m.current=l,v.useEffect(()=>{if(!a)return;u({phase:"loading"}),o(""),w(new Set);let x=!1;return Be.probeModels(t,m.current).then(P=>{var C;x||(P.ok&&P.models?u({phase:"ready",models:P.models}):u({phase:"error",message:((C=P.statusText)==null?void 0:C.trim())||j("providers.drawer.probe.failedFallback"),status:P.status>0?P.status:void 0}))}).catch(P=>{x||u({phase:"error",message:ge(P).message})}),()=>{x=!0}},[a,t,j]);const N=v.useMemo(()=>new Set(s),[s]),b=v.useMemo(()=>{if(y.phase!=="ready")return[];const x=i.trim().toLowerCase();return x?y.models.filter(P=>P.id.toLowerCase().includes(x)||(P.label??"").toLowerCase().includes(x)):y.models},[y,i]),M=v.useMemo(()=>b.map(x=>x.id).filter(x=>!N.has(x)),[b,N]),L=x=>{w(P=>{const C=new Set(P);return C.has(x)?C.delete(x):C.add(x),C})},U=()=>{w(x=>new Set([...x,...M]))},B=()=>{w(new Set)},Y=()=>{if(y.phase!=="ready"||d.size===0)return;const x=y.models.filter(P=>d.has(P.id));p(x),g({title:j("providers.drawer.probe.importSuccess",{count:x.length}),variant:"success"}),h()};return e.jsx(qe,{open:a,onOpenChange:x=>!x&&h(),children:e.jsxs(Ve,{className:"max-w-2xl",children:[e.jsxs(Qe,{children:[e.jsx(Ge,{children:j("providers.drawer.probe.title")}),e.jsx(Ke,{children:j("providers.drawer.probe.subtitle",{name:r})})]}),e.jsxs(We,{className:"space-y-4",children:[y.phase==="loading"?e.jsx("p",{className:"rounded-xl bg-secondary/50 px-4 py-6 text-center text-sm text-muted-foreground",children:j("providers.drawer.probe.loading")}):null,y.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:j("providers.drawer.probe.failedTitle")}),y.status?e.jsxs(re,{variant:"warning",className:"shrink-0",children:["HTTP ",y.status]}):null]}),e.jsx("p",{className:"break-words text-xs leading-relaxed text-warning",children:y.message}),e.jsx("p",{className:"text-xs text-muted-foreground",children:j("providers.drawer.probe.failedHint")})]}):null,y.phase==="ready"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(le,{value:i,onChange:x=>o(x.target.value),placeholder:j("providers.drawer.probe.searchPlaceholder"),className:"h-9"}),e.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:j("providers.drawer.probe.totalCount",{count:y.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(A,{type:"button",variant:"outline",size:"sm",className:"h-auto bg-card px-2 py-1 text-xs",onClick:U,disabled:M.length===0,children:j("providers.drawer.probe.selectAll")}),e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"h-auto bg-card px-2 py-1 text-xs",onClick:B,disabled:d.size===0,children:j("providers.drawer.probe.clearSelection")})]}),e.jsx("span",{className:"text-muted-foreground",children:j("providers.drawer.probe.selectedCount",{count:d.size})})]}),b.length===0?e.jsx("p",{className:"rounded-xl bg-secondary/50 px-4 py-6 text-center text-sm text-muted-foreground",children:j("providers.drawer.probe.emptyResult")}):e.jsx("div",{className:"grid max-h-80 gap-1 overflow-y-auto",children:b.map(x=>{const P=N.has(x.id),C=d.has(x.id);return e.jsxs("label",{className:je("flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2.5 transition-colors",P?"cursor-not-allowed opacity-60":"cursor-pointer hover:border-primary/20 hover:bg-accent/50",C&&"border-primary/30 bg-primary/10"),children:[e.jsx("input",{type:"checkbox",className:"h-4 w-4 shrink-0 rounded border-input accent-primary",checked:C,disabled:P,onChange:()=>L(x.id)}),e.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-xs",children:x.id}),x.label?e.jsx("span",{className:"shrink-0 truncate text-xs text-muted-foreground",children:x.label}):null,P?e.jsx(re,{variant:"secondary",className:"shrink-0",children:j("providers.drawer.probe.imported")}):null]},x.id)})})]}):null]}),e.jsxs(Je,{children:[e.jsx(A,{variant:"outline",onClick:h,children:j("common.actions.cancel")}),e.jsx(A,{onClick:Y,disabled:y.phase!=="ready"||d.size===0,children:j("providers.drawer.probe.importAction",{count:d.size})})]})]})})}function ks({open:a,mode:t,provider:r,existingProviderIds:s,allProviders:l,onClose:p,onSubmit:h,testResult:j,testing:g,onTest:y,onDelete:u}){const{t:i}=W(),o=es({mode:t,provider:r,existingProviderIds:s,providers:l}),{form:d,errors:w,advancedOpen:m,providerIdRef:N}=o,[b,M]=v.useState(!1),[L,U]=v.useState(null),[B,Y]=v.useState("basics"),[x,P]=v.useState(!1),[C,z]=v.useState(!1),[G,K]=v.useState(null),O=v.useRef(null),J=v.useRef(null);v.useEffect(()=>{a&&(o.resetForm(),U(null),M(!1),Y("basics"),P(!1),z(!1),K(null))},[a,r,t,o.resetForm]);const pe=v.useRef(p);pe.current=p,v.useEffect(()=>{if(!a)return;const S=_=>{_.key==="Escape"&&(document.querySelector('[role="dialog"][data-state="open"], [role="listbox"][data-state="open"], [data-radix-popper-content-wrapper]')||pe.current())};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[a]),v.useEffect(()=>{if(a){if(t==="create"&&N.current){N.current.focus();return}J.current&&J.current.focus()}},[a,t]);const E=t==="create",F=d.type==="aggregate",V=v.useMemo(()=>d.models.filter(S=>S.id.trim().length>0),[d.models]),Se=v.useMemo(()=>Et(d.type,i),[d.type,i]),ue=v.useMemo(()=>d.models.reduce((S,_)=>S+_.members.filter(H=>H.target.trim().length>0).length,0),[d.models]),He=d.label.trim()||d.id.trim()||i("providers.drawer.summary.untitled"),fe=v.useMemo(()=>F?[{label:i("providers.drawer.summary.type"),value:Se},{label:i("providers.drawer.summary.models"),value:V.length.toLocaleString()},{label:i("providers.aggregate.drawer.summaryMembers"),value:ue.toLocaleString()}]:[{label:i("providers.drawer.summary.type"),value:Se},{label:i("providers.drawer.summary.auth"),value:ts(d.type,d.authMode,i)},{label:i("providers.drawer.summary.models"),value:V.length.toLocaleString()}],[F,V.length,ue,d.authMode,d.type,Se,i]),ye=v.useMemo(()=>{var _;const S=[];for(const H of l){if(H.type==="aggregate")continue;const ve=H.label&&H.label!==H.id?`${H.label} (${H.id})`:H.id,Ce=(_=H.models)!=null&&_.length?H.models:H.defaultModel?[{id:H.defaultModel}]:[];for(const me of Ce)S.push({value:`${H.id}:${me.id}`,label:`${ve} · ${me.label??me.id}`,providerId:H.id,providerLabel:ve,modelId:me.id,modelLabel:me.label??me.id,kind:"model"})}return S},[l]),Ne=async()=>{U(null);const S=o.validateErrors();if(Object.keys(S).length>0){S.baseUrl||S.id||S.extraHeaders?(Y("basics"),S.extraHeaders&&o.setAdvancedOpen(!0)):(S.models||S.members||S.failover)&&Y("models");return}M(!0);try{const _=o.serialize();await h(_)}catch(_){U(i("providers.drawer.toast.saveFailure",{message:ge(_).message})),M(!1);return}M(!1),p()};if(!a)return null;const ne=Oe.findIndex(S=>S.id===B),Me=ne===Oe.length-1,Pe=d.id.trim(),$e=Pe.length>0&&(t==="edit"||!s.includes(Pe)),De=d.baseUrl.trim();let Te=F||De.length>0;if(Te&&!F)try{new URL(De)}catch{Te=!1}let Le=!d.defaultModel||d.models.some(S=>S.id===d.defaultModel);if(Le){const S=new Set;Le=!d.models.some(_=>{const H=_.id.trim();return H.length===0||S.has(H)?!0:(S.add(H),!1)})}const R={basics:$e&&Te,models:Le},q=Oe.map((S,_)=>{let H;_===ne?H="current":_<ne?H=R[S.id]?"complete":"error":H="upcoming";const ve=F&&S.id==="models"?"providers.drawer.steps.aggregateModels":S.labelKey;return{id:S.id,label:i(ve),status:H}}),Q=S=>{Y(S)},T=async()=>{z(!0),K(null);try{const S=await Be.testProvider(d.id.trim()||"draft",{provider:o.serialize()});K({ok:S.ok,status:S.status,statusText:S.statusText,durationMs:S.durationMs,message:S.ok?void 0:S.statusText,testedAt:Date.now()})}catch(S){K({ok:!1,message:ge(S).message,testedAt:Date.now()})}finally{z(!1)}},ae=()=>{ne<Oe.length-1&&Y(Oe[ne+1].id)},be=()=>{ne>0&&Y(Oe[ne-1].id)},we={form:d,errors:w,isCreate:E,advancedOpen:m,onAdvancedOpenChange:o.setAdvancedOpen,idInputRef:N,onProviderIdChange:o.handleProviderIdChange,onFieldChange:o.handleFieldChange,onTypeChange:o.handleTypeChange,onAuthModeChange:o.handleAuthModeChange,onNonStreamViaStreamChange:o.handleProviderNonStreamViaStreamChange,onUseAbsoluteUrlChange:o.handleUseAbsoluteUrlChange,onStreamUsageChange:o.handleStreamUsageChange,onAddHeader:o.handleAddHeader,onRemoveHeader:o.handleRemoveHeader,onHeaderChange:o.handleHeaderChange,onModelIdChange:o.handleModelIdChange,onModelChange:o.handleModelChange,onAddModel:o.handleAddModel,onRemoveModel:o.handleRemoveModel,onModelNonStreamViaStreamChange:o.handleModelNonStreamViaStreamChange,onSetDefaultModel:o.handleSetDefaultModel,memberOptions:ye,onAddMember:o.handleAddMember,onRemoveMember:o.handleRemoveMember,onMemberTargetChange:o.handleMemberTargetChange,onReorderMembers:o.handleReorderMembers,onModelFailoverChange:o.handleModelFailoverChange,testVerification:F?void 0:t==="edit"?y?{available:!0,testing:g??!1,result:j??null,onTest:y}:void 0:{available:!0,testing:C,result:G,onTest:()=>void T()},probeModels:F?void 0:{available:d.baseUrl.trim().length>0,onProbe:()=>P(!0)}};return e.jsxs("div",{className:"fixed inset-0 z-50 flex",children:[e.jsx("div",{className:"flex-1 bg-background/95","aria-hidden":"true"}),e.jsxs("aside",{ref:O,role:"dialog","aria-modal":"true","aria-labelledby":"provider-drawer-title","aria-describedby":"provider-drawer-desc",className:"flex h-full min-h-0 w-full max-w-5xl flex-col border-l border-border bg-background shadow-[var(--surface-shadow-lg)]",children:[e.jsxs("header",{className:"border-b border-border bg-secondary px-6 py-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"inline-flex rounded-full border border-primary/20 bg-primary/10 px-3 py-1 text-[11px] font-medium uppercase tracking-[0.18em] text-primary",children:i(E?"providers.drawer.quickStart":"providers.drawer.editTitle")}),e.jsxs("div",{children:[e.jsx("h2",{id:"provider-drawer-title",className:"text-lg font-semibold tracking-[-0.02em]",children:i(E?"providers.drawer.createTitle":"providers.drawer.editTitle")}),e.jsx("p",{id:"provider-drawer-desc",className:"text-sm text-muted-foreground",children:i("providers.drawer.description")})]})]}),e.jsx(A,{type:"button",ref:J,variant:"outline",onClick:p,className:"bg-card",children:i("common.actions.close")})]}),e.jsx("div",{className:"mt-4 grid gap-3 md:grid-cols-3",children:fe.map(S=>e.jsxs("div",{className:"rounded-xl border border-transparent bg-card px-4 py-3 shadow-[var(--surface-shadow)]",children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground",children:S.label}),e.jsx("p",{className:"mt-2 text-sm font-semibold text-foreground",children:S.value})]},S.label))})]}),e.jsxs("div",{className:"grid min-h-0 flex-1 overflow-hidden xl:grid-cols-[minmax(0,1fr)_280px]",children:[e.jsxs("div",{className:"min-h-0 overflow-y-auto px-6 py-5 pb-10",children:[e.jsx(ss,{steps:q,current:B,onSelect:Q,className:"mb-6"}),B==="basics"?e.jsx(as,{...we}):null,B==="models"?F?e.jsx(js,{...we}):e.jsx(rs,{...we}):null]}),e.jsx("aside",{className:"hidden min-h-0 overflow-y-auto border-l border-border/45 bg-secondary/40 px-5 py-5 xl:block",children:e.jsxs("div",{className:"sticky top-0 space-y-5",children:[e.jsxs("div",{className:"rounded-xl border border-transparent bg-card p-4 shadow-[var(--surface-shadow)]",children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground",children:i("providers.drawer.formSummary")}),e.jsx("p",{className:"mt-2 text-base font-semibold",children:He}),e.jsx("div",{className:"mt-4 space-y-3 text-sm",children:fe.map(S=>e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("span",{className:"text-muted-foreground",children:S.label}),e.jsx("span",{className:"text-right font-medium",children:S.value})]},S.label))})]}),e.jsxs("div",{className:"rounded-xl border border-transparent bg-card p-4 shadow-[var(--surface-shadow)]",children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground",children:i("providers.drawer.sections.checklist")}),e.jsx("ul",{className:"mt-3 space-y-2 text-sm text-muted-foreground",children:F?e.jsxs(e.Fragment,{children:[e.jsx("li",{children:i("providers.aggregate.drawer.checkMembers")}),e.jsx("li",{children:i("providers.aggregate.drawer.checkPriority")}),e.jsx("li",{children:i("providers.aggregate.drawer.checkFailover")})]}):e.jsxs(e.Fragment,{children:[e.jsx("li",{children:i("providers.drawer.hints.checkUrl")}),e.jsx("li",{children:i("providers.drawer.hints.checkAuth")}),e.jsx("li",{children:i("providers.drawer.hints.checkModels")})]})})]}),m&&e.jsxs("div",{className:"rounded-xl bg-accent p-4 text-sm text-foreground",children:[e.jsx("p",{className:"font-medium text-primary",children:i("providers.drawer.hints.advancedTitle")}),e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:i("providers.drawer.hints.advancedBody")})]})]})})]}),e.jsxs("footer",{className:"flex items-center justify-between gap-3 border-t border-border bg-secondary px-6 py-4 text-sm",children:[e.jsxs("div",{className:"flex flex-col gap-1 text-xs",children:[!E&&u?e.jsx("button",{type:"button",onClick:u,disabled:b,className:"text-muted-foreground underline-offset-2 hover:text-destructive hover:underline disabled:opacity-50",children:i("providers.actions.delete")}):null,L?e.jsx("span",{className:"text-destructive","aria-live":"polite",children:L}):null]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(A,{type:"button",variant:"outline",onClick:p,disabled:b,className:"bg-card",children:i("common.actions.cancel")}),e.jsx(A,{type:"button",variant:"outline",onClick:be,disabled:b||ne===0,className:"bg-card",children:i("common.actions.previous")}),Me?null:e.jsx(A,{type:"button",onClick:ae,disabled:b,children:i("common.actions.next")}),e.jsx(A,{type:"button",onClick:Ne,disabled:b,children:i(b?"common.actions.saving":"common.actions.save")})]})]})]}),e.jsx(ws,{open:x,providerId:(r==null?void 0:r.id)??(d.id.trim()||"draft"),providerName:(r==null?void 0:r.label)||d.label.trim()||d.id.trim()||i("providers.drawer.summary.untitled"),existingModelIds:d.models.map(S=>S.id.trim()).filter(Boolean),draft:o.serialize(),onImport:o.handleImportModels,onClose:()=>P(!1)})]})}function Cs({provider:a,defaultModel:t,modelCount:r,requests24h:s,avgLatencyMs:l,routeCount:p,testResult:h,backendsHealth:j,onTest:g,onEdit:y}){var L;const{t:u}=W(),i=a.label||a.id,o=i.slice(0,1).toUpperCase()||"?",d=a.type==="aggregate",w=d?Et(a.type,u):((L=Dt.find(U=>U.value===(a.type??"custom")))==null?void 0:L.label)??a.type??"custom",m=h?h.ok?"ok":"fail":"untested",N=a.models??[],b=N.reduce((U,B)=>{var Y;return U+(((Y=B.members)==null?void 0:Y.length)??0)},0),M=d?N.flatMap(U=>(U.members??[]).map(B=>({target:B.target,entry:j==null?void 0:j.get(B.target)})).filter(B=>!!(B.entry&&B.entry.state!=="healthy"))):[];return e.jsxs("div",{"data-testid":"provider-card",className:"flex flex-col rounded-lg border border-border bg-card p-4 transition-colors hover:border-primary/40",children:[e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-secondary text-sm font-semibold text-muted-foreground",children:o}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"truncate text-[13px] font-semibold text-foreground",title:i,children:i}),e.jsx(re,{variant:d?"default":"outline",className:"shrink-0 rounded-full px-2 py-0 text-[10px] font-normal",children:w})]}),d?e.jsx("code",{className:"mt-0.5 block truncate font-mono text-[10.5px] text-muted-foreground",children:N.length>0?N.map(U=>`${U.id} → ${(U.members??[]).map(B=>B.target).join(" › ")}`).join(" ; "):u("providers.aggregate.card.noMembers")}):e.jsx("code",{className:"mt-0.5 block truncate font-mono text-[10.5px] text-muted-foreground",title:a.baseUrl,children:a.baseUrl})]}),d?null:e.jsx(Ms,{state:m})]}),e.jsx("div",{className:"mt-3 grid grid-cols-3 gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(Fe,{label:u("providers.aggregate.card.statAggregateModels"),value:r>0?String(r):"—"}),e.jsx(Fe,{label:u("providers.aggregate.card.statMembers"),value:b>0?String(b):"—"}),e.jsx(Fe,{label:u("providers.card.statRequests24h"),value:s!=null?s.toLocaleString():"—"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Fe,{label:u("providers.card.statModels"),value:r>0?String(r):"—"}),e.jsx(Fe,{label:u("providers.card.statRequests24h"),value:s!=null?s.toLocaleString():"—"}),e.jsx(Fe,{label:u("providers.card.statAvgLatency"),value:ps(l,u("common.units.ms"),{maximumFractionDigits:0})})]})}),d?e.jsx("div",{className:"mt-2.5 flex flex-wrap items-center gap-1.5 text-[11px]",children:M.length>0?M.slice(0,3).map(U=>e.jsx(Ss,{target:U.target,entry:U.entry},U.target)):b>0?e.jsx("span",{className:"text-success",children:u("providers.aggregate.card.allHealthy")}):null}):e.jsxs("div",{className:"mt-2.5 flex items-center gap-1.5 text-[11px] text-muted-foreground",children:[e.jsx("span",{className:"shrink-0",children:u("providers.card.defaultModelLabel")}),t?e.jsx("code",{className:"min-w-0 truncate rounded bg-secondary px-1.5 py-0.5 font-mono text-[10.5px] text-foreground",title:t,children:t}):e.jsx("span",{children:"—"})]}),e.jsxs("div",{className:"mt-3 flex items-center gap-1.5 border-t border-border pt-2.5 text-[10.5px] text-muted-foreground",children:[e.jsx("span",{className:"truncate",children:u("providers.card.routeCount",{count:p})}),e.jsxs("div",{className:"ml-auto flex shrink-0 gap-1.5",children:[d?null:e.jsx(A,{variant:"outline",size:"sm",className:"h-7 px-2.5 text-[11px]",onClick:g,children:u("providers.actions.test")}),e.jsx(A,{variant:"outline",size:"sm",className:"h-7 px-2.5 text-[11px]",onClick:y,children:u("providers.actions.edit")})]})]})]})}function Ss({target:a,entry:t}){const{t:r}=W();if(t.state==="cooling"){const s=Math.max(1,Math.ceil((t.cooldownRemainingSeconds??0)/60));return e.jsxs(re,{variant:"destructive",className:"rounded-full px-1.5 py-0 text-[10px] font-normal",title:a,children:[a," · ",r("providers.aggregate.card.coolingBadge",{minutes:s})]})}return e.jsxs(re,{variant:"warning",className:"rounded-full px-1.5 py-0 text-[10px] font-normal",title:a,children:[a," · ",r("providers.aggregate.card.degradedBadge",{count:t.consecutiveFailures})]})}function Fe({label:a,value:t}){return e.jsxs("div",{className:"rounded bg-secondary/60 px-2.5 py-2",children:[e.jsx("div",{className:"text-[10px] text-muted-foreground",children:a}),e.jsx("div",{className:"metric-number mt-0.5 truncate text-[13px] font-semibold text-foreground",children:t})]})}function Ms({state:a}){const{t}=W();return a==="ok"?e.jsx(re,{variant:"success",className:"shrink-0 rounded-full px-1.5 py-0 text-[10px]",children:t("providers.card.health.ok")}):a==="fail"?e.jsx(re,{variant:"destructive",className:"shrink-0 rounded-full px-1.5 py-0 text-[10px]",children:t("providers.card.health.fail")}):e.jsx(re,{variant:"secondary",className:"shrink-0 rounded-full px-1.5 py-0 text-[10px]",children:t("providers.card.health.untested")})}const Ps=1e4;function Es({providersLength:a,filteredProviders:t,testResults:r,providerSearch:s,providerTypeFilter:l,configPending:p,defaultLabels:h,config:j,customEndpoints:g,onTest:y,onEdit:u,onProviderSearchChange:i,onProviderTypeChange:o,onResetFilters:d}){const{t:w}=W(),[m,N]=v.useState("usage"),b=dt(Ee.stats.model(1,50),{url:"/api/stats/model",method:"GET",params:{days:1,limit:50}},{retry:!1}),M=t.some(C=>C.type==="aggregate"),L=dt(Ee.providers.backendsHealth(),{url:"/api/providers/backends/health",method:"GET"},{retry:!1,refetchInterval:Ps,enabled:M}),U=v.useMemo(()=>{var z;const C=new Map;for(const G of((z=L.data)==null?void 0:z.backends)??[])C.set(G.key,G);return C},[L.data]),{requestsByProvider:B,latencyByProvider:Y}=v.useMemo(()=>{const C=new Map,z=new Map,G=new Map;for(const O of b.data??[]){const J=O.provider;C.set(J,(C.get(J)??0)+O.requests),O.avgLatencyMs>0&&(z.set(J,(z.get(J)??0)+O.avgLatencyMs*O.requests),G.set(J,(G.get(J)??0)+O.requests))}const K=new Map;for(const O of C.keys()){const J=G.get(O)??0;K.set(O,J>0?(z.get(O)??0)/J:null)}return{requestsByProvider:C,latencyByProvider:K}},[b.data]),x=v.useMemo(()=>{const C=new Map;for(const z of t)C.set(z.id,ns(j,g,z.id).length);return C},[j,g,t]),P=v.useMemo(()=>{const C=[...t],z=(G,K)=>(G.label||G.id).localeCompare(K.label||K.id);return m==="usage"&&b.isSuccess?C.sort((G,K)=>(B.get(K.id)??0)-(B.get(G.id)??0)||z(G,K)):C.sort(z),C},[t,m,b.isSuccess,B]);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(Xe,{className:"overflow-hidden",children:e.jsx(Ye,{className:"p-0",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2 bg-secondary/50 px-4 py-3",children:[e.jsx(le,{value:s,onChange:C=>i(C.target.value),placeholder:w("providers.filters.searchPlaceholder"),className:"h-9 w-full sm:w-64"}),e.jsxs(at,{value:l,onValueChange:o,children:[e.jsx(rt,{className:"h-9 w-[130px] text-xs",children:e.jsx(nt,{})}),e.jsxs(ot,{children:[e.jsx(Ae,{value:"all",children:w("providers.filters.typeAll")}),Dt.map(C=>e.jsx(Ae,{value:C.value??"custom",children:C.label},C.value??"custom"))]})]}),e.jsxs(at,{value:m,onValueChange:C=>N(C),children:[e.jsx(rt,{className:"h-9 w-[104px] text-xs","aria-label":w("providers.list.sortLabel"),children:e.jsx(nt,{})}),e.jsxs(ot,{children:[e.jsx(Ae,{value:"usage",children:w("providers.list.sortUsage")}),e.jsx(Ae,{value:"name",children:w("providers.list.sortName")})]})]}),e.jsx(re,{variant:"secondary",className:"shrink-0 rounded-full px-2.5 py-1 text-[11px]",children:t.length}),e.jsx(A,{variant:"ghost",size:"sm",onClick:d,disabled:!s.trim()&&l==="all",className:"h-9 shrink-0 rounded-full px-2.5 text-xs",children:w("common.actions.reset")})]})})}),p?e.jsx("div",{className:"flex min-h-[160px] items-center justify-center text-sm text-muted-foreground",children:w("common.loading")}):a===0?e.jsx(ct,{compact:!0,title:w("providers.emptyState"),description:e.jsxs(e.Fragment,{children:[e.jsx("p",{children:w("providers.emptyStateSub")}),e.jsx("p",{className:"mt-1",children:w("workbench.list.emptyHint")})]})}):t.length===0?e.jsx(ct,{compact:!0,title:w("providers.emptyFiltered")}):e.jsx("div",{className:"grid gap-3.5 sm:grid-cols-2 xl:grid-cols-3",children:P.map(C=>{var z;return e.jsx(Cs,{provider:C,defaultModel:h.get(C.id),modelCount:((z=C.models)==null?void 0:z.length)??0,requests24h:b.isSuccess?B.get(C.id)??0:null,avgLatencyMs:b.isSuccess?Y.get(C.id)??null:null,routeCount:x.get(C.id)??0,testResult:r[C.id]??null,backendsHealth:U,onTest:()=>y(C),onEdit:()=>u(C)},C.id)})})]})}function Ds({routing:a,endpoint:t,tabInfo:r,config:s,customEndpoints:l}){var N,b;const{t:p}=W(),h=a.routesByEndpoint[t]||[],j=a.savingRouteFor===t,g=a.savingCompatibilityPolicy,y=a.writingEndpoint===t,u=((N=r==null?void 0:r.protocols)==null?void 0:N.some(M=>M.startsWith("openai")))??t==="openai",i=os(t,s,l),o=u?(i==null?void 0:i.enabled)??!1:!1,w=((b=r==null?void 0:r.protocols)==null?void 0:b.includes("anthropic"))??t==="anthropic"?Rt:Tt,m=new Set(h.map(M=>M.source.trim()).filter(Boolean));return e.jsx(Xe,{"data-testid":"endpoint-config-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(Ye,{className:"space-y-3 p-4",children:[e.jsx("h3",{className:"text-[12.5px] font-semibold",children:p("workbench.endpointConfig.title")}),u?e.jsxs("div",{className:"flex items-center justify-between gap-2 border border-border/60 bg-secondary/30 px-2.5 py-2",children:[e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsx(ce,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:p("modelManagement.openaiCompatibility.toggleLabel")}),e.jsx("p",{className:"text-[10.5px] text-muted-foreground",children:p(o?"modelManagement.openaiCompatibility.enabledHint":"modelManagement.openaiCompatibility.disabledHint")})]}),e.jsx(lt,{"data-testid":"compatibility-toggle",checked:o,onCheckedChange:M=>void a.handleCompatibilityEnabledChange(t,M),disabled:g||y,"aria-label":p("modelManagement.openaiCompatibility.toggleLabel")})]}):null,e.jsxs("div",{children:[e.jsx("p",{className:"mb-1.5 text-[11px] text-muted-foreground",children:p("settings.routing.suggested")}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:w.map(M=>{const L=m.has(M);return e.jsx("button",{"data-testid":"suggestion-chip",type:"button",onClick:()=>a.handleAddSuggestion(t,M),disabled:j||L,className:je("h-6 border px-2 text-[10.5px] transition-colors",L?"border-border bg-secondary/40 text-muted-foreground/50":"border-border bg-card hover:border-primary hover:text-primary"),children:M},`${t}-${M}`)})})]})]})})}function Rs({routing:a,endpoint:t}){const{t:r}=W(),s=a.defaultsByEndpoint[t]??null,l=a.isDefaultsDirtyByEndpoint[t]??!1,p=a.savingDefaultsFor===t,h=a.writingEndpoint===t,j=a.providerModelOptions;return e.jsx(Xe,{"data-testid":"routing-defaults-card",className:"border-primary/40 bg-primary/5 shadow-none",children:e.jsxs(Ye,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-[13px] font-semibold text-primary",children:r("workbench.defaults.title")}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:r("workbench.defaults.cardSubtitle")})]}),e.jsxs(Lt,{summary:e.jsx("span",{className:"text-[11px] font-medium text-muted-foreground",children:r("workbench.defaults.moreLabel")}),summaryClassName:"px-2 py-1",contentClassName:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:r("workbench.defaults.reasoningLabel")}),e.jsx(Ue,{value:(s==null?void 0:s.reasoning)??"",onChange:g=>a.handleDefaultsChange(t,"reasoning",g),options:j,disabled:p,ariaLabel:r("workbench.defaults.reasoningLabel"),placeholder:r("workbench.defaults.targetPlaceholder")})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:r("workbench.defaults.backgroundLabel")}),e.jsx(Ue,{value:(s==null?void 0:s.background)??"",onChange:g=>a.handleDefaultsChange(t,"background",g),options:j,disabled:p,ariaLabel:r("workbench.defaults.backgroundLabel"),placeholder:r("workbench.defaults.targetPlaceholder")})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ce,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:r("workbench.defaults.thresholdLabel")}),e.jsx(le,{type:"number",min:1,value:(s==null?void 0:s.longContextThreshold)||"",onChange:g=>{const y=Number.parseInt(g.target.value,10);a.handleDefaultsChange(t,"longContextThreshold",Number.isFinite(y)?y:0)},disabled:p,className:"md:w-56"})]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"border border-border bg-card px-2.5 py-2 font-mono text-xs",children:"*"}),e.jsx(ke,{className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground","aria-hidden":!0}),e.jsx("div",{"data-testid":"default-target",className:"min-w-[180px] flex-1",children:e.jsx(Ue,{value:(s==null?void 0:s.completion)??"",onChange:g=>a.handleDefaultsChange(t,"completion",g),options:j,disabled:p,ariaLabel:r("workbench.defaults.completionLabel"),placeholder:r("workbench.defaults.targetPlaceholder")})}),e.jsxs(A,{size:"sm","data-testid":"save-defaults",onClick:()=>void a.handleSaveDefaults(t),disabled:p||!l||h,className:"relative",children:[r(p?"common.actions.saving":"workbench.defaults.save"),l?e.jsx("span",{className:"absolute -right-1 -top-1 h-2 w-2 rounded-full bg-warning"}):null]})]})]})})}const Ts={anthropic:"/anthropic",openai:"/openai"};function Ls(a){var t;return(t=a.paths)!=null&&t.length?a.paths[0].path:a.path?a.path:`/${a.id}`}function Os({tabs:a,customEndpoints:t,routeCounts:r,selectedEndpointId:s,onSelect:l,onCreate:p,onEditEndpoint:h,onDeleteEndpoint:j}){const{t:g}=W(),y=a.map(u=>{const i=t.find(d=>d.id===u.key);if(!i)return{key:u.key,label:u.label,path:Ts[u.key]??`/${u.key}`,protocols:u.protocols??[],enabled:!0};const o=i.paths??(i.path?[{path:i.path,protocol:i.protocol??"anthropic"}]:[]);return{key:u.key,label:i.label||i.id,path:Ls(i),protocols:[...new Set(o.map(d=>d.protocol))],enabled:i.enabled!==!1,custom:i}});return e.jsxs("section",{"data-testid":"endpoint-rail",className:"flex gap-2 overflow-x-auto border border-border bg-card shadow-[var(--surface-shadow)] lg:h-full lg:flex-col lg:overflow-visible",children:[e.jsxs("div",{className:"hidden shrink-0 border-b border-border/60 px-3 py-2.5 lg:block",children:[e.jsx("h2",{className:"text-[12.5px] font-semibold",children:g("workbench.endpointRail.title")}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:g("workbench.endpointRail.subtitle")})]}),e.jsxs("div",{className:"flex gap-1.5 p-2 lg:flex-col lg:gap-1",children:[y.map(u=>{const i=u.key===s,o=r[u.key]??0,d=!u.enabled;return e.jsxs("div",{"data-testid":"endpoint-row",className:je("flex shrink-0 items-stretch border transition-colors lg:shrink",i?"border-primary/40 bg-primary/5":"border-border bg-card hover:bg-accent",d?"opacity-60":""),children:[e.jsxs("button",{type:"button",onClick:()=>l(u.key),className:"flex min-w-0 flex-1 items-center gap-2 px-2.5 py-2 text-left",children:[e.jsx("span",{className:je("h-1.5 w-1.5 shrink-0 rounded-full",i?"bg-primary":"bg-muted-foreground/40"),"aria-hidden":!0}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-[11.5px] font-medium",title:u.label,children:u.label}),e.jsxs("span",{className:"mt-0.5 flex items-center gap-1.5 text-[10px] text-muted-foreground",children:[e.jsx("span",{className:"truncate font-mono",children:u.path}),e.jsx("span",{"aria-hidden":!0,children:"·"}),e.jsx("span",{className:"shrink-0 tabular-nums",children:g("workbench.endpointRail.ruleCount",{count:o})})]})]})]}),u.custom?e.jsxs("div",{className:"flex items-center gap-0.5 pr-1",children:[e.jsx("button",{type:"button",onClick:()=>h(u.custom),className:"flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-foreground",title:g("common.edit"),"aria-label":g("common.edit"),children:e.jsx(At,{className:"h-3 w-3","aria-hidden":!0})}),u.custom.deletable!==!1?e.jsx("button",{type:"button",onClick:()=>j(u.custom),className:"flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-destructive",title:g("common.delete"),"aria-label":g("common.delete"),children:e.jsx(Bt,{className:"h-3 w-3","aria-hidden":!0})}):null]}):null]},u.key)}),e.jsxs("button",{type:"button","data-testid":"create-endpoint",onClick:p,className:"flex shrink-0 items-center justify-center border border-dashed border-border px-3 py-2 text-[11.5px] text-muted-foreground transition-colors hover:border-primary hover:text-primary lg:shrink",children:["+ ",g("workbench.endpointRail.add")]})]})]})}function Fs({endpointPath:a,defaultTarget:t}){const{t:r}=W();return e.jsxs("section",{"data-testid":"routing-flow-banner",className:"flex flex-wrap items-center gap-x-3 gap-y-2 border border-border bg-card px-4 py-3 shadow-[var(--surface-shadow)]",children:[e.jsx("span",{className:"text-[10.5px] font-semibold uppercase tracking-[0.06em] text-muted-foreground",children:r("workbench.flow.title")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[e.jsx("span",{className:"border border-border bg-secondary px-2.5 py-1 font-mono text-[11px]",children:r("workbench.flow.clientStep")}),e.jsx(ke,{className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0}),e.jsxs("span",{className:"border border-border bg-secondary px-2.5 py-1 text-[11px]",children:[r("workbench.flow.endpointStep")," ",e.jsx("span",{className:"font-mono",children:a})]}),e.jsx(ke,{className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0}),e.jsx("span",{className:"border border-primary bg-primary/5 px-2.5 py-1 text-[11px] font-semibold text-primary",children:r("workbench.flow.matchStep")}),e.jsx(ke,{className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0}),e.jsx("span",{className:"border border-border bg-secondary px-2.5 py-1 font-mono text-[11px]",children:t||r("workbench.flow.fallbackNote")})]})]})}function Is({routing:a,endpoint:t,onRequestDeletePreset:r}){var i,o;const{t:s}=W(),l=a.presetsByEndpoint[t]??[],p=a.presetNameByEndpoint[t]??"",h=a.presetErrorByEndpoint[t],j=a.savingPresetFor===t,g=((i=a.applyingPreset)==null?void 0:i.endpoint)===t?a.applyingPreset.name:null,y=((o=a.deletingPreset)==null?void 0:o.endpoint)===t?a.deletingPreset.name:null,u=a.writingEndpoint===t;return e.jsx(Xe,{"data-testid":"routing-presets-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(Ye,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h3",{className:"text-[13px] font-semibold",children:s("modelManagement.presets.title")}),e.jsx(A,{variant:"outline",size:"sm","data-testid":"save-preset",onClick:()=>void a.handleSavePreset(t),disabled:j||u,children:s(j?"modelManagement.presets.saving":"modelManagement.presets.save")})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:s("modelManagement.presets.description")}),e.jsx(le,{"data-testid":"preset-name-input",value:p,onChange:d=>a.handlePresetNameChange(t,d.target.value),placeholder:s("modelManagement.presets.namePlaceholder"),disabled:j,className:"h-8 text-xs"}),h?e.jsx("p",{className:"text-xs text-destructive",children:h}):null,l.length===0?e.jsx("p",{className:"py-2 text-center text-[11px] text-muted-foreground",children:s("modelManagement.presets.empty")}):e.jsx(Gt,{children:e.jsx("div",{className:"grid grid-cols-1 gap-1.5 sm:grid-cols-2",children:l.map(d=>{const w=g===d.name,m=y===d.name,N=Object.entries(d.modelRoutes??{}),b=N.length;return e.jsxs("div",{"data-testid":"preset-row",className:"flex items-center justify-between gap-2 border border-border bg-secondary/40 px-2.5 py-2",children:[e.jsxs(Kt,{children:[e.jsx(Wt,{asChild:!0,children:e.jsxs("div",{className:"min-w-0 flex-1 cursor-default",children:[e.jsx("span",{className:"block truncate text-[11px] font-medium",children:d.name}),e.jsx(re,{variant:"outline",className:"mt-0.5 text-[10px] font-normal",children:b>0?s("modelManagement.presets.rulesCount",{count:b}):s("modelManagement.presets.noRules")})]})}),b>0?e.jsx(Jt,{side:"bottom",className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1 text-xs",children:[N.slice(0,5).map(([M,L])=>e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"truncate",children:M}),e.jsx(ke,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:L})]},M)),b>5?e.jsxs("div",{className:"text-muted-foreground",children:["…+",b-5]}):null]})}):null]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"apply-preset",className:"text-[11px] font-semibold text-primary hover:underline disabled:opacity-50",onClick:()=>a.setPresetDiffDialog({endpoint:t,preset:d}),disabled:w||m||u,children:s(w?"modelManagement.presets.applying":"modelManagement.presets.apply")}),e.jsx("button",{type:"button","data-testid":"delete-preset",className:"text-[11px] text-muted-foreground hover:text-destructive disabled:opacity-50","aria-label":s("common.delete"),onClick:()=>r(t,d),disabled:m||w||u,children:s(m?"modelManagement.presets.deleting":"modelManagement.presets.delete")})]})]},d.name)})})})]})})}function As({entry:a,index:t,savingRoute:r,options:s,sourceListId:l,onRouteChange:p,onRemoveRoute:h}){const{t:j}=W(),{attributes:g,listeners:y,setNodeRef:u,setActivatorNodeRef:i,transform:o,transition:d,isDragging:w}=St({id:a.id});return e.jsxs("div",{ref:u,"data-testid":"route-rule-row","data-id":a.id,style:{transform:Pt.Transform.toString(o),transition:d},className:je("flex items-center gap-2 border border-border bg-card p-2",w&&"z-10 opacity-60 shadow-[var(--surface-shadow-lg)]"),children:[e.jsx("button",{ref:i,type:"button","data-testid":"route-rule-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",...g,...y,children:e.jsx(Mt,{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:t+1}),e.jsx(le,{"data-testid":"route-rule-source",value:a.source,onChange:m=>p(a.id,"source",m.target.value),placeholder:j("settings.routing.sourcePlaceholder"),list:l,disabled:r,className:"h-8 min-w-0 flex-1 text-xs"}),e.jsx(ke,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground","aria-hidden":!0}),e.jsx("div",{"data-testid":"route-rule-target",className:"min-w-0 flex-[1.15]",children:e.jsx(Ue,{value:a.target,onChange:m=>p(a.id,"target",m),options:s,disabled:r,ariaLabel:j("workbench.routing.targetLabel"),placeholder:j("settings.routing.targetPlaceholder")})}),e.jsx(A,{variant:"ghost",size:"icon","data-testid":"route-rule-delete",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>h(a.id),disabled:r,"aria-label":j("common.delete"),children:e.jsx(ut,{className:"h-3.5 w-3.5","aria-hidden":!0})})]})}function Bs({routing:a,endpoint:t,tabInfo:r}){var m;const{t:s}=W(),l=a.routesByEndpoint[t]||[],p=a.routeError[t],h=a.savingRouteFor===t,j=a.isDirtyByEndpoint[t]??!1,g=a.writingEndpoint===t,y=a.providerModelOptions,u=`route-source-${t}`,i=bt(tt(yt,{activationConstraint:{distance:6}}),tt(jt,{coordinateGetter:vt})),o=N=>{const{active:b,over:M}=N;!M||b.id===M.id||a.handleReorderRules(t,String(b.id),String(M.id))},w=((m=r==null?void 0:r.protocols)==null?void 0:m.includes("anthropic"))??t==="anthropic"?Rt:Tt;return e.jsx(Xe,{"data-testid":"routing-rules-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(Ye,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h3",{className:"flex items-center gap-2 text-[13px] font-semibold",children:[s("workbench.routing.rulesTitle"),e.jsx(re,{variant:"outline",className:"text-[10.5px] font-normal tabular-nums",children:l.length})]}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:s("workbench.routing.rulesSubtitle")})]}),e.jsx(A,{variant:"outline",size:"sm","data-testid":"add-route",onClick:()=>a.handleAddRoute(t),disabled:h,children:s("settings.routing.add")})]}),p?e.jsx("p",{className:"text-xs text-destructive",children:p}):null,l.length===0?e.jsx(ct,{compact:!0,title:s("workbench.routing.emptyTitle"),description:s("workbench.routing.emptyDescription"),action:e.jsx(A,{size:"sm",onClick:()=>a.handleAddRoute(t),disabled:h,children:s("workbench.routing.addFirst")})}):e.jsx(Nt,{sensors:i,collisionDetection:wt,onDragEnd:o,children:e.jsx(kt,{items:l.map(N=>N.id),strategy:Ct,children:e.jsx("div",{className:"flex flex-col gap-1.5",children:l.map((N,b)=>e.jsx(As,{entry:N,index:b,savingRoute:h,options:y,sourceListId:u,onRouteChange:(M,L,U)=>a.handleRouteChange(t,M,L,U),onRemoveRoute:M=>a.handleRemoveRoute(t,M)},N.id))})})}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-t border-border/60 pt-3",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:s(j?"modelManagement.actions.footerDirtyHint":"modelManagement.actions.footerSavedHint")}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(A,{variant:"outline",size:"sm","data-testid":"reset-routes",onClick:()=>a.handleResetRoutes(t),disabled:h||!j,children:s("common.actions.reset")}),e.jsxs(A,{size:"sm","data-testid":"save-routes",onClick:()=>void a.handleSaveRoutes(t),disabled:h||g,className:"relative",children:[s(h?"common.actions.saving":"modelManagement.actions.saveRoutes"),j?e.jsx("span",{className:"absolute -right-1 -top-1 h-2 w-2 rounded-full bg-warning"}):null]})]})]}),e.jsx("datalist",{id:u,children:w.map(N=>e.jsx("option",{value:N},`${u}-${N}`))})]})})}const Hs={simulateRequest(a){return{url:"/api/routing/simulate",method:"POST",data:a}}},$s=350;function zs(a,t){switch(a.kind){case"modelRoute":return{label:a.viaAlias?t("workbench.hitSim.reasonModelRouteAlias"):t("workbench.hitSim.reasonModelRoute"),tone:"hit"};case"directMatch":return{label:t("workbench.hitSim.reasonDirectMatch"),tone:"hit"};case"thinkingDefault":return{label:t("workbench.hitSim.reasonThinkingDefault"),tone:"hit"};case"completionDefault":return{label:t("workbench.hitSim.reasonCompletionDefault"),tone:"hit"};case"longContextDefault":return{label:t("workbench.hitSim.reasonLongContext"),tone:"hit",detail:t("workbench.hitSim.longContextDetail",{estimate:a.tokenEstimate.toLocaleString(),threshold:a.threshold.toLocaleString()})};case"fallback":return{label:t("workbench.hitSim.reasonFallback"),tone:"fallback"}}return{label:t("workbench.hitSim.reasonFallback"),tone:"fallback"}}function _s({tabs:a,endpoint:t,onEndpointChange:r}){var M;const{t:s}=W(),l=a.filter(L=>L.key!=="providers"),[p,h]=v.useState(((M=l[0])==null?void 0:M.key)??"anthropic"),j=t??p,g=L=>{t&&r?r(L):h(L)},[y,u]=v.useState(""),[i,o]=v.useState(!1),[d,w]=v.useState("");v.useEffect(()=>{const L=setTimeout(()=>w(y.trim()),$s);return()=>clearTimeout(L)},[y]);const{data:m,isFetching:N,error:b}=dt(["routing","simulate",j,d,i],Hs.simulateRequest({endpoint:j,model:d||void 0,thinking:i}),{retry:!1,refetchOnWindowFocus:!1,staleTime:1/0});return e.jsxs("section",{"data-testid":"routing-hit-simulator",className:"space-y-3 rounded-lg border border-border bg-card p-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm font-semibold text-foreground",children:s("workbench.hitSim.title")}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:s("workbench.hitSim.subtitle")})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-2",children:[t?null:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:s("workbench.hitSim.endpointLabel")}),e.jsxs(at,{value:j,onValueChange:g,children:[e.jsx(rt,{className:"h-8 w-[168px]",children:e.jsx(nt,{})}),e.jsx(ot,{children:l.map(L=>e.jsx(Ae,{value:L.key,children:L.label},L.key))})]})]}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(lt,{checked:i,onCheckedChange:o,"aria-label":s("workbench.hitSim.thinking")}),s("workbench.hitSim.thinking")]})]}),e.jsx(le,{value:y,onChange:L=>u(L.target.value),placeholder:s("workbench.hitSim.modelPlaceholder"),className:"h-9 text-xs",spellCheck:!1,autoComplete:"off","aria-label":s("workbench.hitSim.modelPlaceholder")}),e.jsx(Us,{result:m,loading:N,errorMessage:(b==null?void 0:b.message)??null,requestedModel:d})]})}function Us({result:a,loading:t,errorMessage:r,requestedModel:s}){var g;const{t:l}=W();if(r)return e.jsxs("p",{className:"text-xs text-muted-foreground",children:[l("workbench.hitSim.errorPrefix"),": ",r]});if(!a)return t?e.jsx("div",{className:"h-[72px] animate-pulse rounded-lg border border-border bg-secondary"}):e.jsx("p",{className:"text-xs text-muted-foreground",children:l("workbench.hitSim.empty")});const p=zs(a.reason,l),h=p.tone==="fallback",j=s||l("workbench.hitSim.anyModel");return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:h?"rounded-lg border border-border bg-secondary px-3 py-2.5":"rounded-lg border border-success bg-success-bg px-3 py-2.5",children:[e.jsx("div",{className:h?"text-[11px] font-semibold text-warning":"text-[11px] font-semibold text-success",children:p.label}),e.jsx("div",{className:"mt-1 text-xs text-foreground",children:j}),e.jsxs("div",{className:"mt-1 text-xs text-muted-foreground",children:["→ ",a.providerLabel,":",a.modelId]}),p.detail?e.jsx("div",{className:"mt-1 text-[11px] text-muted-foreground",children:p.detail}):null]}),(((g=a.candidates)==null?void 0:g.length)??0)>1?e.jsxs("div",{className:"rounded-lg border border-border bg-secondary/50 px-3 py-2.5",children:[e.jsx("div",{className:"text-[11px] font-semibold text-muted-foreground",children:l("providers.aggregate.simulator.candidatesTitle")}),e.jsx("ol",{className:"mt-1.5 space-y-1",children:(a.candidates??[]).map((y,u)=>e.jsxs("li",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"w-4 shrink-0 text-center text-[10.5px] tabular-nums text-muted-foreground",children:u+1}),e.jsxs("span",{className:"min-w-0 truncate font-mono text-foreground",children:[y.providerLabel,":",y.modelId]}),u===0?e.jsx("span",{className:"shrink-0 text-[10px] font-medium text-muted-foreground",children:l("providers.aggregate.simulator.primaryBadge")}):null]},`${y.providerId}:${y.modelId}`))})]}):null,h?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:l("workbench.hitSim.fallbackHint")}):null]})}function qs({routing:a,config:t,customEndpoints:r,selectedEndpointId:s,routeCounts:l,onSelectEndpoint:p,onCreateEndpoint:h,onEditEndpoint:j,onDeleteEndpoint:g,onRequestDeletePreset:y}){var w;W();const u=s??((w=a.endpointTabs[0])==null?void 0:w.key)??"anthropic",i=a.endpointTabs.find(m=>m.key===u),o=a.defaultsByEndpoint[u],d=(()=>{var N;if(u==="anthropic")return"/anthropic";if(u==="openai")return"/openai";const m=r.find(b=>b.id===u);return(N=m==null?void 0:m.paths)!=null&&N.length?m.paths[0].path:m!=null&&m.path?m.path:`/${u}`})();return e.jsxs("div",{"data-testid":"routing-workspace",className:"flex flex-col gap-3.5",children:[e.jsx(Fs,{endpointPath:d,defaultTarget:(o==null?void 0:o.completion)??null}),e.jsxs("div",{className:"grid items-start gap-3.5 lg:grid-cols-[200px_minmax(0,1fr)_288px]",children:[e.jsx(Os,{tabs:a.endpointTabs,customEndpoints:r,routeCounts:l,selectedEndpointId:u,onSelect:p,onCreate:h,onEditEndpoint:j,onDeleteEndpoint:g}),e.jsxs("div",{className:"flex flex-col gap-3.5",children:[e.jsx(Rs,{routing:a,endpoint:u}),e.jsx(Bs,{routing:a,endpoint:u,tabInfo:i}),e.jsx(Is,{routing:a,endpoint:u,onRequestDeletePreset:y})]}),e.jsxs("div",{className:"flex flex-col gap-3.5",children:[e.jsx(_s,{tabs:a.endpointTabs,endpoint:u,onEndpointChange:p}),e.jsx(Ds,{routing:a,endpoint:u,tabInfo:i,config:t,customEndpoints:r})]})]})]})}function Vs({open:a,provider:t,options:r,usePreset:s,preservedExtras:l,onPresetChange:p,onConfirm:h,onClose:j}){const{t:g}=W();return t?e.jsx(qe,{open:a,onOpenChange:y=>!y&&j(),children:e.jsxs(Ve,{className:"max-w-2xl",onInteractOutside:y=>y.preventDefault(),children:[e.jsxs(Qe,{children:[e.jsx(Ge,{children:g("providers.testDialog.title")}),e.jsx(Ke,{children:g("providers.testDialog.subtitle",{name:t.label||t.id})})]}),e.jsxs(We,{className:"space-y-4",children:[e.jsx("div",{className:"rounded-xl bg-accent p-4 text-sm text-primary",children:g("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(ce,{htmlFor:"provider-test-preset",children:g("providers.testDialog.presetLabel")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:g("providers.testDialog.presetDescription")})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(lt,{id:"provider-test-preset",checked:s,onCheckedChange:p})})]}),s?e.jsx("div",{className:"space-y-2",children:e.jsxs("details",{className:"rounded-xl border border-transparent bg-card p-2 text-xs shadow-[var(--surface-shadow)]",children:[e.jsx("summary",{className:"cursor-pointer text-primary hover:underline",children:g("providers.testDialog.presetPreviewSummary")}),e.jsx("div",{className:"mt-2 space-y-1",children:r.map(y=>e.jsxs("code",{className:"block rounded-lg bg-secondary px-2 py-1 text-xs",children:[y.key,": ",y.value]},y.key))})]})}):e.jsx("p",{className:"text-xs text-muted-foreground",children:g("providers.testDialog.presetDescription")})]}),Object.keys(l).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:g("providers.testDialog.preservedInfo")}),Object.entries(l).map(([y,u])=>e.jsxs("code",{className:"block rounded-lg border border-transparent bg-card px-2 py-1 shadow-[var(--surface-shadow)]",children:[y,": ",u]},y))]})]}),e.jsxs(Je,{children:[e.jsx(A,{variant:"outline",onClick:j,children:g("providers.testDialog.cancel")}),e.jsx(A,{onClick:()=>void h(),children:g("providers.testDialog.primary")})]})]})}):null}function ha(){const{t:a}=W(),t=ls(),r=hs(t),s=xs(t,{sanitizeDraftsForProvider:r.sanitizeDraftsForProvider}),[l,p]=zt(),h=l.get("tab"),j=h==="routing"||h==="endpoints"?"routing":"providers";v.useEffect(()=>{h==="endpoints"&&p(E=>{const F=new URLSearchParams(E);return F.set("tab","routing"),F},{replace:!0})},[h,p]);const[g,y]=v.useState(!1),[u,i]=v.useState(void 0),[o,d]=v.useState(null),[w,m]=v.useState(!1),N=l.get("endpoint"),[b,M]=v.useState(N);v.useEffect(()=>{M(N)},[N]);const L=E=>{p(F=>{const V=new URLSearchParams(F);return V.set("tab","routing"),V.set("endpoint",E),V},{replace:!0})},U=()=>{p(E=>{const F=new URLSearchParams(E);return F.delete("endpoint"),F},{replace:!0})};v.useEffect(()=>{b&&(t.customEndpointsQuery.isPending||r.endpointTabs.some(E=>E.key===b)||U())},[b,r.endpointTabs,t.customEndpointsQuery.isPending]);const B=()=>{i(void 0),y(!0)},Y=E=>{i(E),y(!0)},x=E=>{p(F=>{const V=new URLSearchParams(F);return E==="providers"?V.delete("tab"):V.set("tab",E),V},{replace:!0})},P=async()=>{if(o){m(!0);try{o.kind==="provider"?await s.handleDeleteProvider(o.provider):o.kind==="preset"?await r.handleDeletePreset(o.endpoint,o.preset):await r.handleDeleteEndpoint(o.endpoint.id),d(null)}finally{m(!1)}}},C=(o==null?void 0:o.kind)==="provider"?is(t.config,t.customEndpoints,o.provider.id):0,z=(o==null?void 0:o.kind)==="provider"?a("providers.actions.delete"):(o==null?void 0:o.kind)==="preset"?a("modelManagement.presets.delete"):(o==null?void 0:o.kind)==="endpoint"?a("common.delete"):"",G=(o==null?void 0:o.kind)==="provider"?a("providers.confirm.delete",{name:o.provider.label||o.provider.id}):(o==null?void 0:o.kind)==="preset"?a("modelManagement.confirm.deletePreset",{name:o.preset.name}):(o==null?void 0:o.kind)==="endpoint"?a("modelManagement.deleteEndpointConfirm",{label:o.endpoint.label}):"",K=(o==null?void 0:o.kind)==="provider"?o.provider.label||o.provider.id:(o==null?void 0:o.kind)==="preset"?o.preset.name:(o==null?void 0:o.kind)==="endpoint"?o.endpoint.label:"",O=Object.values(r.routesByEndpoint).reduce((E,F)=>E+((F==null?void 0:F.length)??0),0),J=Object.fromEntries(Object.entries(r.routesByEndpoint).map(([E,F])=>[E,(F==null?void 0:F.length)??0])),pe=[{value:"providers",icon:Ht,label:a("workbench.viewSwitch.providers"),description:a("workbench.viewSwitch.providersDesc"),count:s.providerCount},{value:"routing",icon:$t,label:a("workbench.viewSwitch.routing"),description:a("workbench.viewSwitch.routingDesc"),count:O}];return e.jsxs("div",{className:"flex flex-col gap-6",children:[e.jsx(Ut,{actions:j==="providers"?e.jsx(A,{size:"sm",onClick:s.handleOpenCreate,children:a("providers.actions.add")}):e.jsx(A,{size:"sm",onClick:B,children:a("workbench.endpoints.create")})}),e.jsx("div",{role:"tablist","aria-label":a("workbench.viewSwitch.label"),className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:pe.map(E=>{const F=E.icon,V=j===E.value;return e.jsxs("button",{type:"button",role:"tab","aria-selected":V,onClick:()=>x(E.value),className:je("motion-surface flex items-center gap-3 rounded-xl border p-4 text-left",V?"border-primary/40 bg-primary/5":"border-border bg-card hover:bg-muted/40"),children:[e.jsx("span",{className:je("flex h-9 w-9 shrink-0 items-center justify-center rounded-lg",V?"bg-primary/10 text-primary":"bg-secondary text-muted-foreground"),children:e.jsx(F,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:je("text-sm font-semibold",V?"text-foreground":"text-muted-foreground"),children:E.label}),e.jsx(re,{variant:V?"default":"secondary",className:"text-[10px]",children:E.count})]}),e.jsx("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",children:E.description})]})]},E.value)})}),j==="providers"?e.jsx(Es,{configPending:t.configQuery.isPending||!t.config&&t.configQuery.isFetching,testResults:s.testResults,filteredProviders:s.filteredProviders,providerSearch:s.providerSearch,providerTypeFilter:s.providerTypeFilter,providersLength:s.providers.length,defaultLabels:s.defaultLabels,config:t.config,customEndpoints:t.customEndpoints,onTest:E=>s.initiateTestConnection(E),onEdit:E=>s.handleOpenEdit(E),onProviderSearchChange:s.setProviderSearch,onProviderTypeChange:s.setProviderTypeFilter,onResetFilters:()=>{s.setProviderSearch(""),s.setProviderTypeFilter("all")}}):e.jsx(qs,{routing:r,config:t.config,customEndpoints:t.customEndpoints,routeCounts:J,selectedEndpointId:b,onSelectEndpoint:L,onCreateEndpoint:B,onEditEndpoint:Y,onDeleteEndpoint:E=>d({kind:"endpoint",endpoint:E}),onRequestDeletePreset:(E,F)=>d({kind:"preset",endpoint:E,preset:F})}),e.jsx(ks,{open:s.drawerOpen,mode:s.drawerMode,provider:s.drawerMode==="edit"?s.editingProvider:void 0,existingProviderIds:s.providers.map(E=>E.id).filter(E=>s.drawerMode==="edit"&&s.editingProvider?E!==s.editingProvider.id:!0),allProviders:s.providers,testResult:s.editingProvider?s.testResults[s.editingProvider.id]??null:null,testing:s.editingProvider?s.testingProviderId===s.editingProvider.id:!1,onTest:()=>{s.editingProvider&&s.handleTestConnection(s.editingProvider)},onDelete:()=>{s.drawerMode==="edit"&&s.editingProvider&&d({kind:"provider",provider:s.editingProvider})},onClose:()=>{s.setDrawerOpen(!1),s.setEditingProvider(void 0),s.setDrawerMode("create")},onSubmit:s.handleProviderSubmit}),e.jsx(Vs,{open:s.testDialogOpen,provider:s.testDialogProvider,options:s.anthropicTestHeaderOptions,preservedExtras:s.testDialogPreservedExtras,usePreset:s.testDialogUsePreset,onPresetChange:s.setTestDialogUsePreset,onConfirm:s.confirmTestDialog,onClose:s.closeTestDialog}),e.jsx(bs,{open:!!s.noModelDialogProvider,provider:s.noModelDialogProvider,onClose:()=>s.setNoModelDialogProvider(null),onEdit:E=>{s.setNoModelDialogProvider(null),s.handleOpenEdit(E)}}),e.jsx(fs,{open:g,endpoint:u,onClose:()=>{y(!1),i(void 0)},onSuccess:()=>{t.configQuery.refetch()}}),e.jsx(vs,{dialog:r.presetDiffDialog,currentRoutes:r.presetDiffDialog?r.routesByEndpoint[r.presetDiffDialog.endpoint]||[]:[],onConfirm:(E,F)=>{r.setPresetDiffDialog(null),r.handleApplyPreset(E,F)},onClose:()=>r.setPresetDiffDialog(null)}),e.jsx(_t,{open:!!o,onOpenChange:E=>{!E&&!w&&d(null)},title:z,description:G,confirmLabel:a(w?"common.actions.loading":"common.delete"),cancelLabel:a("common.actions.cancel"),loading:w,onConfirm:P,children:K?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:K}),(o==null?void 0:o.kind)==="provider"&&C>0?e.jsx("p",{className:"text-xs text-muted-foreground",children:a("providers.confirm.deleteImpact",{count:C})}):null]}):null})]})}export{ha as default};
|