@chenpu17/cc-gw 0.10.2 → 0.10.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (23) hide show
  1. package/package.json +5 -5
  2. package/src/web/dist/assets/{About-CcTMpvYw.js → About-DVONGhC8.js} +1 -1
  3. package/src/web/dist/assets/{ApiKeys-Dbteu5ri.js → ApiKeys-C3UcR3Xt.js} +1 -1
  4. package/src/web/dist/assets/{ConfirmDialog-Cc9UQTDU.js → ConfirmDialog-Ci29hhDD.js} +1 -1
  5. package/src/web/dist/assets/{Dashboard-B5QF-lmL.js → Dashboard-C5pBcbjh.js} +1 -1
  6. package/src/web/dist/assets/{Events-BFIgKbWf.js → Events-DXuVlVli.js} +1 -1
  7. package/src/web/dist/assets/{Help-C8IpZL_I.js → Help-DoBQVllq.js} +1 -1
  8. package/src/web/dist/assets/{Login-hQw0WqP_.js → Login-BKBhBrF_.js} +1 -1
  9. package/src/web/dist/assets/{Logs-Cq3T-TNv.js → Logs-Cl14ySgm.js} +1 -1
  10. package/src/web/dist/assets/{ProvidersWorkbench-D4h3nYno.js → ProvidersWorkbench-CMXcjnjA.js} +1 -1
  11. package/src/web/dist/assets/{Settings-CQ6tvunu.js → Settings-BxtiQXA0.js} +1 -1
  12. package/src/web/dist/assets/{Setup-BpNWz4e5.js → Setup-r8hTQIkT.js} +1 -1
  13. package/src/web/dist/assets/{apiKeys-Dvp0S9i6.js → apiKeys-C7NN8p2H.js} +1 -1
  14. package/src/web/dist/assets/{app-DmrDy3E3.js → app-WMvqYU5W.js} +4 -4
  15. package/src/web/dist/assets/{gateway-DypmM2yK.js → gateway-T6-6vX59.js} +1 -1
  16. package/src/web/dist/assets/{landing-CXkPmDBs.js → landing-CQeQu2bM.js} +1 -1
  17. package/src/web/dist/assets/package-B6sWB4v8.js +1 -0
  18. package/src/web/dist/assets/{shared-BzlaTM1w.js → shared-lc9s0nIr.js} +1 -1
  19. package/src/web/dist/assets/{useAppMutation-CErBrMAz.js → useAppMutation-aXncU1Ie.js} +1 -1
  20. package/src/web/dist/assets/{useProviderForm-DruDgLK_.js → useProviderForm-BRhWbili.js} +1 -1
  21. package/src/web/dist/index.html +1 -1
  22. package/src/web/dist/landing.html +2 -2
  23. package/src/web/dist/assets/package-CKunvygM.js +0 -1
@@ -1 +1 @@
1
- import{r as f,ax as Nt,j as e,ay as wt,as as ft,ab as be,az as kt,aA as Ct,aB as St,aC as Mt,aD as Pt,aE as Et,aF as ct,aG as Dt,aH as Rt,aI as Tt,aJ as Ot,aK as Lt,aL as Ft,aM as It,aN as At,aO as Bt}from"./vendor-CITafuNQ.js";import{d as zt}from"./router-BoBrmro7.js";import{C as $t}from"./ConfirmDialog-Cc9UQTDU.js";import{P as Ht}from"./PageToolbar-xVyzEX46.js";import{t as ce,q as Se,e as ze,B,a as Ut,c as bt,b as qt,s as Vt,T as _t,f as Kt,g as Qt,h as Gt}from"./app-DmrDy3E3.js";import{B as te}from"./badge-DMgopDMC.js";import{c as ve}from"./global-D5dyWHqO.js";import{d as ut,g as mt,a as pt,b as Wt,c as ht,e as xt,r as Jt,f as Be,m as Le,h as Xt,u as Yt,P as dt,i as Zt,j as Re,S as es,B as ts,M as ss,k as as,l as rs,C as vt,O as jt,n as ns,o as os}from"./useProviderForm-DruDgLK_.js";import{a as is}from"./query-DZF7K6hv.js";import{g as Te}from"./gateway-DypmM2yK.js";import{u as et}from"./useAppMutation-CErBrMAz.js";import{D as $e,A as He,a as Ue,b as qe,c as Ve,d as _e,e as Ke}from"./DialogShell-iCyqEFRA.js";import{L as Ne,I as pe}from"./label-Dg8bOG83.js";import{S as tt,a as st,b as at,c as rt,d as Oe}from"./select-BMTHg2Ox.js";import{S as nt}from"./switch-BjJJ5nhB.js";import{u as W}from"./i18n-PeX9kBVO.js";import{C as Qe,a as Ge}from"./card-kh1_vqEo.js";import{a as lt}from"./PageState-BzdQq00f.js";import{b as ls}from"./types-DYz12j32.js";import{D as ds}from"./disclosure-Dpus5Sms.js";import{P as cs,c as us,b as ms}from"./popover-BPqySDlA.js";import"./radix-Bux_1C5J.js";function ps(a){const{t,pushToast:n,config:s,setConfig:o,configQuery:h,customEndpoints:x,tabs:j,ensureConfig:y}=a,b=is(),[d,m]=f.useState({}),[l,C]=f.useState({}),[N,u]=f.useState(null),[w,k]=f.useState({}),[M,R]=f.useState({}),[X,_]=f.useState({}),[T,c]=f.useState(null),[S,L]=f.useState(null),[V,q]=f.useState(null),[se,A]=f.useState(!1),[ne,ae]=f.useState(null),[E,I]=f.useState({}),[U,we]=f.useState(null),oe=f.useRef(null),[ie,he]=f.useState(null),ue=r=>{oe.current=r,he(r)},xe=()=>{oe.current=null,he(null)},ge=f.useMemo(()=>j.filter(r=>r.key!=="providers"),[j]);f.useEffect(()=>{if(!h.data)return;const r=h.data;m(g=>{const i=ut(r,x);if(!g||Object.keys(g).length===0)return i;const v={...i};for(const[P,O]of Object.entries(g)){if(!(P in i))continue;const F=mt(r,x,P);if(pt(O,F))v[P]=O;else{const J=new Map(O.map(K=>[K.source,K.id]));v[P]=i[P].map(K=>({...K,id:J.get(K.source)??K.id}))}}return v}),I(g=>{const i=Wt(r,x);if(!g||Object.keys(g).length===0)return i;const v={...i};for(const[P,O]of Object.entries(g)){if(!(P in i))continue;const F=ht(r,x,P);JSON.stringify(O)!==JSON.stringify(F)&&(v[P]=O)}return v}),C({}),k(xt(r,x))},[h.data,x]);const fe=(s==null?void 0:s.providers)??[],je=f.useMemo(()=>{const r=[],g=new Set;for(const i of fe){const v=i.label&&i.label!==i.id?`${i.label} (${i.id})`:i.id,P=i.models??[];if(P.length>0)for(const F of P){const J=`${i.id}:${F.id}`;g.has(J)||(g.add(J),r.push({value:J,label:`${v} · ${F.label??F.id}`,providerId:i.id,providerLabel:v,modelId:F.id,modelLabel:F.label??F.id,kind:"model",isDefault:i.defaultModel===F.id}))}else if(i.defaultModel){const F=`${i.id}:${i.defaultModel}`;g.has(F)||(g.add(F),r.push({value:F,label:`${v} · ${i.defaultModel}`,providerId:i.id,providerLabel:v,modelId:i.defaultModel,modelLabel:i.defaultModel,kind:"model",isDefault:!0}))}const O=`${i.id}:*`;g.has(O)||(g.add(O),r.push({value:O,label:t("settings.routing.providerPassthroughOption",{provider:v}),providerId:i.id,providerLabel:v,modelId:"*",modelLabel:"*",kind:"passthrough"}))}for(const i of Object.values(d).flat()){const v=i.target.trim();v&&!g.has(v)&&(g.add(v),r.push({value:v,label:v,modelId:v,modelLabel:v,kind:"custom"}))}return r},[fe,d,t]),Fe=r=>s?mt(s,x,r):{},Me=f.useMemo(()=>{const r={};for(const g of ge){const i=d[g.key]||[];r[g.key]=pt(i,Fe(g.key))}return r},[s,x,d,ge]),We=f.useMemo(()=>{const r={};if(!s)return r;for(const g of ge){const i=E[g.key];if(!i){r[g.key]=!1;continue}const v=ht(s,x,g.key);r[g.key]=JSON.stringify(i)!==JSON.stringify(v)}return r},[s,x,E,ge]),Je=(r,g,i)=>{I(v=>({...v,[r]:{...v[r]??{completion:null,reasoning:null,background:null,longContextThreshold:6e4},[g]:i}}))},D=async r=>{var v,P,O,F,J,K,Q,re;if(!y()||oe.current)return;const g=E[r];if(!g)return;const i={completion:(v=g.completion)!=null&&v.trim()?g.completion.trim():null,reasoning:(P=g.reasoning)!=null&&P.trim()?g.reasoning.trim():null,background:(O=g.background)!=null&&O.trim()?g.background.trim():null,longContextThreshold:Number.isFinite(g.longContextThreshold)&&g.longContextThreshold>0?Math.floor(g.longContextThreshold):s.defaults.longContextThreshold};we(r),ue(r);try{const Z=x.find(G=>G.id===r);if(Z){const G={...Z.routing??{},defaults:i,modelRoutes:((F=Z.routing)==null?void 0:F.modelRoutes)??{}};await ze.update(r,{routing:G}),o(de=>{if(!de)return de;const Ye=[...de.customEndpoints??[]],ot=Ye.findIndex(yt=>yt.id===r);return ot===-1?de:(Ye[ot]={...Ye[ot],routing:G},{...de,customEndpoints:Ye})}),await b.invalidateQueries({queryKey:Se.customEndpoints.all()})}else{const G=r,de={...s,endpointRouting:{...s.endpointRouting??{},[G]:{defaults:i,modelRoutes:((K=(J=s.endpointRouting)==null?void 0:J[G])==null?void 0:K.modelRoutes)??(G==="anthropic"?s.modelRoutes??{}:{}),compatibility:(re=(Q=s.endpointRouting)==null?void 0:Q[G])==null?void 0:re.compatibility}}};await Te.saveConfig(de),o(de)}I(G=>({...G,[r]:i})),n({title:t("workbench.defaults.saveSuccess"),variant:"success"}),h.refetch()}catch(Z){n({title:t("workbench.defaults.saveFailure",{message:ce(Z).message}),variant:"error"})}finally{we(null),xe()}},z=(r,g)=>{k(i=>({...i,[r]:g})),o(i=>{if(!i)return i;if(r==="anthropic"||r==="openai")return{...i,routingPresets:{...i.routingPresets,[r]:g}};const v=[...i.customEndpoints??[]],P=v.findIndex(O=>O.id===r);return P===-1?i:(v[P]={...v[P],routingPresets:g},{...i,customEndpoints:v})})},H=(r,g)=>{R(i=>({...i,[r]:g})),g.trim()&&_(i=>({...i,[r]:null}))},p=async r=>{if(!y()||oe.current)return;const g=(M[r]??"").trim();if(!g){_(i=>({...i,[r]:t("modelManagement.validation.presetName")}));return}if((w[r]??[]).some(i=>i.name.toLowerCase()===g.toLowerCase())){_(i=>({...i,[r]:t("modelManagement.validation.presetDuplicate",{name:g})}));return}c(r),ue(r);try{const v=(await Le.savePreset(r,g)).presets??[];z(r,v),R(P=>({...P,[r]:""})),_(P=>({...P,[r]:null})),n({title:t("modelManagement.toast.presetSaved",{name:g}),variant:"success"})}catch(i){n({title:t("modelManagement.toast.presetSaveFailure",{message:ce(i).message}),variant:"error"})}finally{c(null),xe(),h.refetch()}},$=async(r,g)=>{if(y()&&!oe.current){L({endpoint:r,name:g.name}),ue(r);try{const v=(await Le.applyPreset(r,g.name)).config;o(v);const P=ut(v,x);m(O=>({...O,[r]:P[r]??[]})),k(xt(v,x)),r!=="anthropic"&&r!=="openai"&&await b.invalidateQueries({queryKey:Se.customEndpoints.all()}),n({title:t("modelManagement.toast.presetApplySuccess",{name:g.name}),variant:"success"})}catch(i){n({title:t("modelManagement.toast.presetApplyFailure",{message:ce(i).message}),variant:"error"})}finally{L(null),xe(),h.refetch()}}},Y=async(r,g)=>{if(y()&&!oe.current){q({endpoint:r,name:g.name}),ue(r);try{const i=await Le.deletePreset(r,g.name);z(r,i.presets??[]),n({title:t("modelManagement.toast.presetDeleteSuccess",{name:g.name}),variant:"success"})}catch(i){n({title:t("modelManagement.toast.presetDeleteFailure",{message:ce(i).message}),variant:"error"})}finally{q(null),xe(),h.refetch()}}},Pe=async r=>{const g=x.find(i=>i.id===r);if(!(!g||g.deletable===!1))try{await ze.delete(r),await b.invalidateQueries({queryKey:Se.customEndpoints.all()}),o(i=>i&&{...i,customEndpoints:(i.customEndpoints??[]).filter(v=>v.id!==r)}),h.refetch(),n({title:t("modelManagement.deleteEndpointSuccess"),variant:"success"})}catch(i){const v=ce(i);n({title:t("modelManagement.deleteEndpointError",{error:v.message}),variant:"error"})}},ke=r=>{m(g=>({...g,[r]:[...g[r]||[],{id:Be(),source:"",target:""}]})),C(g=>({...g,[r]:null}))},ee=async(r,g)=>{if(y()&&!oe.current){A(!0),ue(r);try{if(r==="anthropic"||r==="openai"){const i=r,v=s.endpointRouting?{...s.endpointRouting}:{},P=v[i]??{defaults:s.defaults,modelRoutes:(i==="anthropic"?s.modelRoutes:{})??{}},O={defaults:P.defaults??s.defaults,modelRoutes:P.modelRoutes??{}},F={...s,endpointRouting:{...v,[i]:g?{...O,compatibility:{enabled:!0}}:{...O}}};await Te.saveConfig(F),o(F)}else{const i=[...s.customEndpoints??[]],v=i.findIndex(J=>J.id===r);if(v===-1)throw new Error(t("modelManagement.toast.endpointNotFound"));const P=i[v],O=P.routing??{defaults:s.defaults,modelRoutes:{}};i[v]={...P,routing:g?{...O,compatibility:{enabled:!0}}:{defaults:O.defaults,modelRoutes:O.modelRoutes}};const F={...s,customEndpoints:i};await Te.saveConfig(F),o(F)}n({title:t("modelManagement.toast.compatibilitySaved",{state:t(g?"common.status.enabled":"common.status.disabled")}),variant:"success"}),h.refetch()}catch(i){const v=ce(i);n({title:t("modelManagement.toast.compatibilitySaveFailure",{message:v.message}),variant:"error"})}finally{A(!1),xe()}}},ye=(r,g)=>{m(i=>{const v=i[r]||[];return v.some(P=>P.source.trim()===g.trim())?i:{...i,[r]:[...v,{id:Be(),source:g,target:""}]}}),C(i=>({...i,[r]:null}))},Ee=(r,g,i,v)=>{m(P=>({...P,[r]:(P[r]||[]).map(O=>O.id===g?{...O,[i]:v}:O)})),C(P=>({...P,[r]:null}))},Ce=(r,g)=>{m(i=>({...i,[r]:(i[r]||[]).filter(v=>v.id!==g)})),C(i=>({...i,[r]:null}))},De=(r,g,i)=>{g!==i&&(m(v=>{const P=v[r]||[],O=P.findIndex(J=>J.id===g),F=P.findIndex(J=>J.id===i);return O===-1||F===-1?v:{...v,[r]:Nt(P,O,F)}}),C(v=>({...v,[r]:null})))},Xe=r=>{var i;if(!s)return;const g=(s.customEndpoints??x).find(v=>v.id===r);if(g)m(v=>{var P;return{...v,[r]:Object.entries(((P=g.routing)==null?void 0:P.modelRoutes)??{}).map(([O,F])=>({id:Be(),source:O,target:F}))}});else{const v=s.endpointRouting??{},P=r,O=P==="anthropic"?s.modelRoutes??{}:{},F=((i=v[P])==null?void 0:i.modelRoutes)??O;m(J=>({...J,[r]:Object.entries(F).map(([K,Q])=>({id:Be(),source:K,target:Q}))}))}C(v=>({...v,[r]:null}))},le=et({mutationFn:async r=>(await Te.saveConfig(r.nextConfig),r)}),me=et({mutationFn:async r=>(await ze.update(r.endpoint,{routing:r.routing}),r)});return{endpointTabs:ge,routesByEndpoint:d,setRoutesByEndpoint:m,routeError:l,savingRouteFor:N,presetsByEndpoint:w,presetNameByEndpoint:M,presetErrorByEndpoint:X,savingPresetFor:T,applyingPreset:S,deletingPreset:V,savingCompatibilityPolicy:se,writingEndpoint:ie,presetDiffDialog:ne,setPresetDiffDialog:ae,providerModelOptions:je,isDirtyByEndpoint:Me,defaultsByEndpoint:E,isDefaultsDirtyByEndpoint:We,savingDefaultsFor:U,handleDefaultsChange:Je,handleSaveDefaults:D,handlePresetNameChange:H,handleSavePreset:p,handleApplyPreset:$,handleDeletePreset:Y,handleDeleteEndpoint:Pe,handleAddRoute:ke,handleAddSuggestion:ye,handleRouteChange:Ee,handleRemoveRoute:Ce,handleReorderRules:De,handleResetRoutes:Xe,handleSaveRoutes:async r=>{var v,P,O,F,J;if(!y()||oe.current)return;const g=d[r]||[],i={};for(const K of g){const Q=K.source.trim(),re=K.target.trim();if(!(!Q&&!re)){if(!Q||!re){C(Z=>({...Z,[r]:t("settings.validation.routePair")}));return}if(i[Q]){C(Z=>({...Z,[r]:t("settings.validation.routeDuplicate",{model:Q})}));return}i[Q]=re}}C(K=>({...K,[r]:null})),u(r),ue(r);try{const K=x.find(Q=>Q.id===r);if(K){const Q={...K.routing??{},modelRoutes:i,defaults:((v=K.routing)==null?void 0:v.defaults)||s.defaults};await me.mutateAsync({endpoint:r,routing:Q}),o(re=>{if(!re)return re;const Z=[...re.customEndpoints??[]],G=Z.findIndex(de=>de.id===r);return G===-1?re:(Z[G]={...Z[G],routing:Q},{...re,customEndpoints:Z})}),await b.invalidateQueries({queryKey:Se.customEndpoints.all()})}else{const Q={...s,endpointRouting:{...s.endpointRouting??{},[r]:{defaults:((O=(P=s.endpointRouting)==null?void 0:P[r])==null?void 0:O.defaults)??s.defaults,modelRoutes:i,compatibility:(J=(F=s.endpointRouting)==null?void 0:F[r])==null?void 0:J.compatibility}},modelRoutes:r==="anthropic"?i:s.modelRoutes??{}};await le.mutateAsync({endpoint:r,nextConfig:Q}),o(Q)}m(Q=>{const re=Q[r]??[],Z=new Map(re.map(G=>[G.source.trim(),G.id]));return{...Q,[r]:Object.entries(i).map(([G,de])=>({id:Z.get(G.trim())??Be(),source:G,target:de}))}}),n({title:t("modelManagement.toast.routesSaved"),variant:"success"}),h.refetch()}catch(K){n({title:t("modelManagement.toast.routesSaveFailure",{message:ce(K).message}),variant:"error"})}finally{u(null),xe()}},handleCompatibilityEnabledChange:ee,sanitizeDraftsForProvider:r=>{m(g=>{const i={};for(const[v,P]of Object.entries(g))i[v]=P.filter(O=>!Jt(O.target.trim(),r));return i})}}}function hs(a,t){const{t:n,pushToast:s,config:o,setConfig:h,configQuery:x,customEndpoints:j,ensureConfig:y}=a,{sanitizeDraftsForProvider:b}=t??{},[d,m]=f.useState(""),[l,C]=f.useState("all"),[N,u]=f.useState(!1),[w,k]=f.useState("create"),[M,R]=f.useState(void 0),[X,_]=f.useState(null),[T,c]=f.useState({}),[S,L]=f.useState(!1),[V,q]=f.useState(null),[se,A]=f.useState(!0),[ne,ae]=f.useState({}),[E,I]=f.useState(null),U=(o==null?void 0:o.providers)??[],we=U.length,oe=f.useMemo(()=>U.filter(D=>{var $;if(!(l==="all"||(D.type??"custom")===l))return!1;const H=d.trim().toLowerCase();return H?[D.id,D.label??"",D.baseUrl,D.defaultModel??"",...(($=D.models)==null?void 0:$.map(Y=>Y.id))??[]].join(" ").toLowerCase().includes(H):!0}),[d,l,U]),ie=f.useMemo(()=>{const D=new Map;for(const z of U){if(!z.defaultModel||!z.models)continue;const H=z.models.find(p=>p.id===z.defaultModel);H&&D.set(z.id,Xt(H))}return D},[U]),he=f.useMemo(()=>[{key:"anthropic-beta",value:"claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14",label:n("providers.testDialog.options.beta.label"),description:n("providers.testDialog.options.beta.description")}],[n]),ue=()=>{y()&&(k("create"),R(void 0),u(!0))},xe=D=>{y()&&(k("edit"),R(D),u(!0))},ge=async D=>{if(!o)throw new Error(n("settings.toast.missingConfig"));const z=w==="create"?[...U,D]:U.map(p=>M&&p.id===M.id?{...D,id:M.id}:p),H={...o,providers:z};await Te.saveConfig(H),h(H),x.refetch(),s({title:w==="create"?n("providers.toast.createSuccess",{name:D.label||D.id}):n("providers.toast.updateSuccess",{name:D.label||D.id}),variant:"success"})},fe=(D,z)=>{c(H=>({...H,[D]:z}))},je=async(D,z)=>{_(D.id);try{const H=z&&(z.headers||z.query)?{headers:z.headers&&Object.keys(z.headers).length>0?z.headers:void 0,query:z.query&&z.query.trim().length>0?z.query.trim():void 0}:void 0,p=await Le.testProvider(D.id,H);if(p.ok){fe(D.id,{ok:!0,status:p.status,statusText:p.statusText,durationMs:p.durationMs,testedAt:Date.now()}),s({title:n("providers.toast.testSuccess"),description:n("providers.toast.testSuccessDesc",{status:p.status,duration:p.durationMs?`${p.durationMs} ms`:"—"}),variant:"success"});return}fe(D.id,{ok:!1,status:p.status,statusText:p.statusText,durationMs:p.durationMs,message:`${p.status} ${p.statusText}`,testedAt:Date.now()}),s({title:n("providers.toast.testFailure",{message:`${p.status} ${p.statusText}`}),variant:"error"})}catch(H){const p=ce(H),$=p.status?`${p.status} ${p.message}`:p.message;fe(D.id,{ok:!1,status:p.status,message:$,testedAt:Date.now()}),s({title:n("providers.toast.testFailure",{message:$}),variant:"error"})}finally{_(null)}},Fe=D=>{var Pe,ke;if(!(!!((Pe=D.defaultModel)!=null&&Pe.trim())||!!((ke=D.models)!=null&&ke.some(ee=>ee.id.trim().length>0)))){I(D);return}if(D.type!=="anthropic"){je(D);return}const H=D.extraHeaders??{},p=new Map(he.map(ee=>[ee.key.toLowerCase(),ee])),$={};let Y=!0;for(const ee of he){const ye=Object.entries(H).find(([De])=>De.toLowerCase()===ee.key.toLowerCase());if(!ye)continue;const[Ee,Ce]=ye;String(Ce??"")!==ee.value&&(Y=!1,$[Ee]=String(Ce??""))}for(const[ee,ye]of Object.entries(H))p.has(ee.toLowerCase())||($[ee]=String(ye??""));ae($),A(Y),q(D),L(!0)},Me=()=>{L(!1),q(null),A(!0),ae({})};return{providers:U,providerCount:we,filteredProviders:oe,providerSearch:d,setProviderSearch:m,providerTypeFilter:l,setProviderTypeFilter:C,defaultLabels:ie,drawerOpen:N,setDrawerOpen:u,drawerMode:w,setDrawerMode:k,editingProvider:M,setEditingProvider:R,testingProviderId:X,testResults:T,testDialogOpen:S,testDialogProvider:V,testDialogUsePreset:se,setTestDialogUsePreset:A,testDialogPreservedExtras:ne,noModelDialogProvider:E,setNoModelDialogProvider:I,anthropicTestHeaderOptions:he,handleOpenCreate:ue,handleOpenEdit:xe,handleProviderSubmit:ge,handleDeleteProvider:async D=>{var ee,ye,Ee,Ce,De,Xe;if(!y())return;const z=U.filter(le=>le.id!==D.id),H=le=>{const me={};if(!le)return me;for(const[Ie,Ae]of Object.entries(le)){if(!Ae)continue;const[r]=Ae.split(":");r&&r===D.id||Ae===D.id||(me[Ie]=Ae)}return me},p=(o==null?void 0:o.endpointRouting)??{},$=H(((ee=p.anthropic)==null?void 0:ee.modelRoutes)??(o==null?void 0:o.modelRoutes)??{}),Y=H(((ye=p.openai)==null?void 0:ye.modelRoutes)??{}),Pe=((o==null?void 0:o.customEndpoints)??j).map(le=>{const me=le.routing,Ie=me==null?void 0:me.modelRoutes;return Ie?{...le,routing:{...me,defaults:me.defaults??o.defaults,modelRoutes:H(Ie)}}:le}),ke={...o,providers:z,modelRoutes:$,customEndpoints:Pe,endpointRouting:{anthropic:{defaults:((Ee=p.anthropic)==null?void 0:Ee.defaults)??o.defaults,modelRoutes:$,compatibility:(Ce=p.anthropic)==null?void 0:Ce.compatibility},openai:{defaults:((De=p.openai)==null?void 0:De.defaults)??o.defaults,modelRoutes:Y,compatibility:(Xe=p.openai)==null?void 0:Xe.compatibility}}};try{await Te.saveConfig(ke),h(ke),b==null||b(D.id),(M==null?void 0:M.id)===D.id&&(u(!1),R(void 0),k("create")),s({title:n("providers.toast.deleteSuccess",{name:D.label||D.id}),variant:"success"}),x.refetch()}catch(le){s({title:n("providers.toast.deleteFailure",{message:ce(le).message}),variant:"error"})}},handleTestConnection:je,initiateTestConnection:Fe,closeTestDialog:Me,confirmTestDialog:async()=>{if(!V)return;const D={};if(se)for(const p of he)D[p.key]=p.value;const z=new Map(he.map(p=>[p.key.toLowerCase(),p]));for(const[p,$]of Object.entries(ne))z.get(p.toLowerCase())&&se||(D[p]=$);const H=V;Me(),await je(H,{headers:Object.keys(D).length>0?D:void 0})}}}const xs=["anthropic","openai-auto","openai-chat","openai-responses"];function gs({open:a,endpoint:t,onClose:n,onSuccess:s}){const{t:o}=W(),[h,x]=f.useState({id:"",label:"",paths:[{path:"",protocol:"openai-auto"}],enabled:!0});f.useEffect(()=>{if(a){if(t){const u=t.paths&&t.paths.length>0?t.paths:t.path&&t.protocol?[{path:t.path,protocol:t.protocol}]:[{path:"",protocol:"openai-auto"}];x({id:t.id,label:t.label,paths:u,enabled:t.enabled!==!1});return}x({id:"",label:"",paths:[{path:"",protocol:"openai-auto"}],enabled:!0})}},[t,a]);const j=et({mutationFn:ze.create,invalidateKeys:[Se.customEndpoints.all()],successToast:()=>({title:o("modelManagement.createEndpointSuccess")}),errorToast:u=>({title:o("modelManagement.createEndpointError",{error:u.message})}),onSuccess:async()=>{s(),n()}}),y=et({mutationFn:u=>ze.update(u.id,u.updates),invalidateKeys:[Se.customEndpoints.all()],successToast:()=>({title:o("modelManagement.updateEndpointSuccess")}),errorToast:u=>({title:o("modelManagement.updateEndpointError",{error:u.message})}),onSuccess:async()=>{s(),n()}}),b=()=>{x(u=>({...u,paths:[...u.paths,{path:"",protocol:"anthropic"}]}))},d=u=>{h.paths.length!==1&&x(w=>({...w,paths:w.paths.filter((k,M)=>M!==u)}))},m=(u,w,k)=>{x(M=>{const R=[...M.paths];return R[u]={...R[u],[w]:k},{...M,paths:R}})},l=u=>{if(u==null||u.preventDefault(),!h.id.trim()||!h.label.trim())return;for(const k of h.paths)if(!k.path.trim())return;const w=h.paths.map(k=>({path:k.path.trim(),protocol:k.protocol}));if(t){y.mutate({id:t.id,updates:{label:h.label.trim(),paths:w,enabled:h.enabled}});return}j.mutate({id:h.id.trim(),label:h.label.trim(),paths:w,enabled:h.enabled})},C=j.isPending||y.isPending,N=h.paths.length===0?o("modelManagement.atLeastOnePath"):!h.id.trim()||!h.label.trim()?o("modelManagement.endpointValidationError"):h.paths.some(u=>!u.path.trim())?o("modelManagement.pathValidationError"):null;return e.jsx($e,{open:a,onOpenChange:u=>!u&&n(),children:e.jsxs(He,{className:"max-w-lg",onInteractOutside:u=>u.preventDefault(),children:[e.jsxs(Ue,{children:[e.jsx(qe,{children:o(t?"modelManagement.editEndpoint":"modelManagement.createEndpoint")}),e.jsx(Ve,{className:"truncate font-mono text-xs",children:t?t.id:o("modelManagement.endpointRoutingHint")})]}),e.jsx(_e,{children:e.jsxs("form",{id:"endpoint-form",onSubmit:l,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Ne,{children:[o("modelManagement.endpointId")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(pe,{value:h.id,onChange:u=>x(w=>({...w,id:u.target.value})),placeholder:o("modelManagement.endpointIdPlaceholder"),disabled:!!t,required:!0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o("modelManagement.endpointIdHint")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Ne,{children:[o("modelManagement.endpointLabel")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(pe,{value:h.label,onChange:u=>x(w=>({...w,label:u.target.value})),placeholder:o("modelManagement.endpointLabelPlaceholder"),required:!0})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Ne,{children:[o("modelManagement.endpointPaths")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsxs(B,{type:"button",variant:"ghost",size:"sm",onClick:b,children:[e.jsx(wt,{className:"mr-1 h-3 w-3"}),o("modelManagement.addPath")]})]}),e.jsx("div",{className:"space-y-3",children:h.paths.map((u,w)=>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(pe,{value:u.path,onChange:k=>m(w,"path",k.target.value),placeholder:o("modelManagement.endpointPathPlaceholder"),required:!0}),e.jsxs(tt,{value:u.protocol,onValueChange:k=>m(w,"protocol",k),children:[e.jsx(st,{children:e.jsx(at,{})}),e.jsx(rt,{children:xs.map(k=>e.jsx(Oe,{value:k,children:o(k==="anthropic"?"modelManagement.protocolAnthropic":k==="openai-auto"?"modelManagement.protocolOpenAI":k==="openai-chat"?"modelManagement.protocolOpenAIChat":"modelManagement.protocolOpenAIResponses")},k))})]})]}),h.paths.length>1?e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>d(w),className:"text-destructive",children:e.jsx(ft,{className:"h-4 w-4"})}):null]}),e.jsxs("div",{className:"space-y-1 text-xs text-muted-foreground",children:[w===0?e.jsx("p",{children:o("modelManagement.endpointPathHint")}):null,e.jsx("p",{children:o(`modelManagement.protocolHints.${u.protocol}`)})]})]},`${u.protocol}-${w}`))}),N?e.jsx("p",{className:"text-xs text-destructive",children:N}):null]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(nt,{id:"endpoint-enabled",checked:h.enabled,onCheckedChange:u=>x(w=>({...w,enabled:u}))}),e.jsx(Ne,{htmlFor:"endpoint-enabled",children:o("modelManagement.endpointEnabled")})]}),t?null:e.jsx("div",{className:"rounded-xl bg-accent p-4",children:e.jsx("p",{className:"text-sm text-primary",children:o("modelManagement.endpointRoutingHint")})})]})}),e.jsxs(Ke,{children:[e.jsx(B,{variant:"outline",onClick:n,disabled:C,children:o("common.cancel")}),e.jsx(B,{type:"submit",form:"endpoint-form",disabled:C,children:o(C?"common.saving":t?"common.save":"common.create")})]})]})})}function fs({open:a,provider:t,onClose:n,onEdit:s}){const{t:o}=W();return t?e.jsx($e,{open:a,onOpenChange:h=>!h&&n(),children:e.jsxs(He,{className:"max-w-md",children:[e.jsxs(Ue,{children:[e.jsx(qe,{children:o("providers.noModelDialog.title")}),e.jsx(Ve,{children:o("providers.noModelDialog.subtitle",{name:t.label||t.id})})]}),e.jsxs(_e,{className:"space-y-4",children:[e.jsx("div",{className:"rounded-xl bg-accent p-4 text-sm text-primary",children:o("providers.noModelDialog.description")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:o("providers.noModelDialog.hint")})]}),e.jsxs(Ke,{children:[e.jsx(B,{variant:"outline",onClick:n,children:o("common.actions.close")}),e.jsx(B,{onClick:()=>s(t),children:o("providers.noModelDialog.primary")})]})]})}):null}function bs({dialog:a,currentRoutes:t,onConfirm:n,onClose:s}){const{t:o}=W();if(!a)return null;const{endpoint:h,preset:x}=a,j=x.modelRoutes??{},y={};for(const N of t){const u=N.source.trim(),w=N.target.trim();u&&w&&(y[u]=w)}const b=new Set([...Object.keys(y),...Object.keys(j)]),d=[],m=[],l=[];for(const N of b){const u=N in y,w=N in j;w&&!u?d.push([N,j[N]]):u&&!w?m.push([N,y[N]]):u&&w&&y[N]!==j[N]&&l.push([N,y[N],j[N]])}const C=d.length>0||m.length>0||l.length>0;return e.jsx($e,{open:!0,onOpenChange:N=>!N&&s(),children:e.jsxs(He,{className:"max-w-2xl",children:[e.jsxs(Ue,{children:[e.jsx(qe,{children:o("modelManagement.presets.diffTitle")}),e.jsx(Ve,{children:o("modelManagement.presets.diffDescription",{name:x.name})})]}),e.jsx(_e,{children:C?e.jsxs("div",{className:"max-h-80 space-y-2 rounded-xl bg-secondary/50 p-3 text-sm",children:[d.map(([N,u])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-success-bg px-2 py-1.5 text-success",children:[e.jsx(te,{variant:"outline",className:"border-success/30 text-xs",children:o("modelManagement.presets.diffAdded")}),e.jsx("span",{className:"truncate",children:N}),e.jsx(be,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:u})]},`add-${N}`)),m.map(([N,u])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-error-bg px-2 py-1.5 text-error",children:[e.jsx(te,{variant:"outline",className:"border-error/30 text-xs",children:o("modelManagement.presets.diffRemoved")}),e.jsx("span",{className:"truncate",children:N}),e.jsx(be,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:u})]},`rm-${N}`)),l.map(([N,u,w])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-warning-bg px-2 py-1.5 text-warning",children:[e.jsx(te,{variant:"outline",className:"border-warning/30 text-xs",children:o("modelManagement.presets.diffChanged")}),e.jsx("span",{className:"truncate",children:N}),e.jsx(be,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate line-through opacity-60",children:u}),e.jsx(be,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:w})]},`chg-${N}`))]}):e.jsx("p",{className:"rounded-xl bg-secondary/50 py-8 text-center text-sm text-muted-foreground",children:o("modelManagement.presets.diffEmpty")})}),e.jsxs(Ke,{children:[e.jsx(B,{variant:"outline",onClick:s,children:o("common.cancel")}),e.jsx(B,{onClick:()=>n(h,x),disabled:!C,children:o("modelManagement.presets.diffConfirm")})]})]})})}function vs({open:a,providerId:t,providerName:n,existingModelIds:s,draft:o,onImport:h,onClose:x}){const{t:j}=W(),{pushToast:y}=Ut(),[b,d]=f.useState({phase:"loading"}),[m,l]=f.useState(""),[C,N]=f.useState(new Set),u=f.useRef(o);u.current=o,f.useEffect(()=>{if(!a)return;d({phase:"loading"}),l(""),N(new Set);let c=!1;return Le.probeModels(t,u.current).then(S=>{var L;c||(S.ok&&S.models?d({phase:"ready",models:S.models}):d({phase:"error",message:((L=S.statusText)==null?void 0:L.trim())||j("providers.drawer.probe.failedFallback"),status:S.status>0?S.status:void 0}))}).catch(S=>{c||d({phase:"error",message:ce(S).message})}),()=>{c=!0}},[a,t,j]);const w=f.useMemo(()=>new Set(s),[s]),k=f.useMemo(()=>{if(b.phase!=="ready")return[];const c=m.trim().toLowerCase();return c?b.models.filter(S=>S.id.toLowerCase().includes(c)||(S.label??"").toLowerCase().includes(c)):b.models},[b,m]),M=f.useMemo(()=>k.map(c=>c.id).filter(c=>!w.has(c)),[k,w]),R=c=>{N(S=>{const L=new Set(S);return L.has(c)?L.delete(c):L.add(c),L})},X=()=>{N(c=>new Set([...c,...M]))},_=()=>{N(new Set)},T=()=>{if(b.phase!=="ready"||C.size===0)return;const c=b.models.filter(S=>C.has(S.id));h(c),y({title:j("providers.drawer.probe.importSuccess",{count:c.length}),variant:"success"}),x()};return e.jsx($e,{open:a,onOpenChange:c=>!c&&x(),children:e.jsxs(He,{className:"max-w-2xl",children:[e.jsxs(Ue,{children:[e.jsx(qe,{children:j("providers.drawer.probe.title")}),e.jsx(Ve,{children:j("providers.drawer.probe.subtitle",{name:n})})]}),e.jsxs(_e,{className:"space-y-4",children:[b.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,b.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")}),b.status?e.jsxs(te,{variant:"warning",className:"shrink-0",children:["HTTP ",b.status]}):null]}),e.jsx("p",{className:"break-words text-xs leading-relaxed text-warning",children:b.message}),e.jsx("p",{className:"text-xs text-muted-foreground",children:j("providers.drawer.probe.failedHint")})]}):null,b.phase==="ready"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(pe,{value:m,onChange:c=>l(c.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:b.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(B,{type:"button",variant:"outline",size:"sm",className:"h-auto bg-card px-2 py-1 text-xs",onClick:X,disabled:M.length===0,children:j("providers.drawer.probe.selectAll")}),e.jsx(B,{type:"button",variant:"outline",size:"sm",className:"h-auto bg-card px-2 py-1 text-xs",onClick:_,disabled:C.size===0,children:j("providers.drawer.probe.clearSelection")})]}),e.jsx("span",{className:"text-muted-foreground",children:j("providers.drawer.probe.selectedCount",{count:C.size})})]}),k.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:k.map(c=>{const S=w.has(c.id),L=C.has(c.id);return e.jsxs("label",{className:ve("flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2.5 transition-colors",S?"cursor-not-allowed opacity-60":"cursor-pointer hover:border-primary/20 hover:bg-accent/50",L&&"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:L,disabled:S,onChange:()=>R(c.id)}),e.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-xs",children:c.id}),c.label?e.jsx("span",{className:"shrink-0 truncate text-xs text-muted-foreground",children:c.label}):null,S?e.jsx(te,{variant:"secondary",className:"shrink-0",children:j("providers.drawer.probe.imported")}):null]},c.id)})})]}):null]}),e.jsxs(Ke,{children:[e.jsx(B,{variant:"outline",onClick:x,children:j("common.actions.cancel")}),e.jsx(B,{onClick:T,disabled:b.phase!=="ready"||C.size===0,children:j("providers.drawer.probe.importAction",{count:C.size})})]})]})})}function js({open:a,mode:t,provider:n,existingProviderIds:s,onClose:o,onSubmit:h,testResult:x,testing:j,onTest:y,onDelete:b}){const{t:d}=W(),m=Yt({mode:t,provider:n,existingProviderIds:s}),{form:l,errors:C,advancedOpen:N,providerIdRef:u}=m,[w,k]=f.useState(!1),[M,R]=f.useState(null),[X,_]=f.useState("basics"),[T,c]=f.useState(!1),[S,L]=f.useState(!1),[V,q]=f.useState(null),se=f.useRef(null),A=f.useRef(null);f.useEffect(()=>{a&&(m.resetForm(),R(null),k(!1),_("basics"),c(!1),L(!1),q(null))},[a,n,t,m.resetForm]);const ne=f.useRef(o);ne.current=o,f.useEffect(()=>{if(!a)return;const p=$=>{$.key==="Escape"&&(document.querySelector('[role="dialog"][data-state="open"], [role="listbox"][data-state="open"], [data-radix-popper-content-wrapper]')||ne.current())};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[a]),f.useEffect(()=>{if(a){if(t==="create"&&u.current){u.current.focus();return}A.current&&A.current.focus()}},[a,t]);const ae=t==="create",E=f.useMemo(()=>l.models.filter(p=>p.id.trim().length>0),[l.models]),I=f.useMemo(()=>{var p;return((p=dt.find($=>$.value===l.type))==null?void 0:p.label)??"Custom"},[l.type]),U=l.label.trim()||l.id.trim()||d("providers.drawer.summary.untitled"),we=f.useMemo(()=>[{label:d("providers.drawer.summary.type"),value:I},{label:d("providers.drawer.summary.auth"),value:Zt(l.type,l.authMode,d)},{label:d("providers.drawer.summary.models"),value:E.length.toLocaleString()}],[E.length,l.authMode,l.type,I,d]),oe=async()=>{R(null);const p=m.validateErrors();if(Object.keys(p).length>0){p.baseUrl||p.id||p.extraHeaders?(_("basics"),p.extraHeaders&&m.setAdvancedOpen(!0)):p.models&&_("models");return}k(!0);try{const $=m.serialize();await h($)}catch($){R(d("providers.drawer.toast.saveFailure",{message:ce($).message})),k(!1);return}k(!1),o()};if(!a)return null;const ie=Re.findIndex(p=>p.id===X),he=ie===Re.length-1,ue=l.id.trim(),xe=ue.length>0&&(t==="edit"||!s.includes(ue)),ge=l.baseUrl.trim();let fe=ge.length>0;if(fe)try{new URL(ge)}catch{fe=!1}let je=!l.defaultModel||l.models.some(p=>p.id===l.defaultModel);if(je){const p=new Set;je=!l.models.some($=>{const Y=$.id.trim();return Y.length===0||p.has(Y)?!0:(p.add(Y),!1)})}const Fe={basics:xe&&fe,models:je},Me=Re.map((p,$)=>{let Y;return $===ie?Y="current":$<ie?Y=Fe[p.id]?"complete":"error":Y="upcoming",{id:p.id,label:d(p.labelKey),status:Y}}),We=p=>{_(p)},Je=async()=>{L(!0),q(null);try{const p=await Le.testProvider(l.id.trim()||"draft",{provider:m.serialize()});q({ok:p.ok,status:p.status,statusText:p.statusText,durationMs:p.durationMs,message:p.ok?void 0:p.statusText,testedAt:Date.now()})}catch(p){q({ok:!1,message:ce(p).message,testedAt:Date.now()})}finally{L(!1)}},D=()=>{ie<Re.length-1&&_(Re[ie+1].id)},z=()=>{ie>0&&_(Re[ie-1].id)},H={form:l,errors:C,isCreate:ae,advancedOpen:N,onAdvancedOpenChange:m.setAdvancedOpen,idInputRef:u,onProviderIdChange:m.handleProviderIdChange,onFieldChange:m.handleFieldChange,onTypeChange:m.handleTypeChange,onAuthModeChange:m.handleAuthModeChange,onNonStreamViaStreamChange:m.handleProviderNonStreamViaStreamChange,onUseAbsoluteUrlChange:m.handleUseAbsoluteUrlChange,onStreamUsageChange:m.handleStreamUsageChange,onAddHeader:m.handleAddHeader,onRemoveHeader:m.handleRemoveHeader,onHeaderChange:m.handleHeaderChange,onModelIdChange:m.handleModelIdChange,onModelChange:m.handleModelChange,onAddModel:m.handleAddModel,onRemoveModel:m.handleRemoveModel,onModelNonStreamViaStreamChange:m.handleModelNonStreamViaStreamChange,onSetDefaultModel:m.handleSetDefaultModel,testVerification:t==="edit"?y?{available:!0,testing:j??!1,result:x??null,onTest:y}:void 0:{available:!0,testing:S,result:V,onTest:()=>void Je()},probeModels:{available:l.baseUrl.trim().length>0,onProbe:()=>c(!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:se,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:d(ae?"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:d(ae?"providers.drawer.createTitle":"providers.drawer.editTitle")}),e.jsx("p",{id:"provider-drawer-desc",className:"text-sm text-muted-foreground",children:d("providers.drawer.description")})]})]}),e.jsx(B,{type:"button",ref:A,variant:"outline",onClick:o,className:"bg-card",children:d("common.actions.close")})]}),e.jsx("div",{className:"mt-4 grid gap-3 md:grid-cols-3",children:we.map(p=>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:p.label}),e.jsx("p",{className:"mt-2 text-sm font-semibold text-foreground",children:p.value})]},p.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(es,{steps:Me,current:X,onSelect:We,className:"mb-6"}),X==="basics"?e.jsx(ts,{...H}):null,X==="models"?e.jsx(ss,{...H}):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:d("providers.drawer.formSummary")}),e.jsx("p",{className:"mt-2 text-base font-semibold",children:U}),e.jsx("div",{className:"mt-4 space-y-3 text-sm",children:we.map(p=>e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("span",{className:"text-muted-foreground",children:p.label}),e.jsx("span",{className:"text-right font-medium",children:p.value})]},p.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:d("providers.drawer.sections.checklist")}),e.jsxs("ul",{className:"mt-3 space-y-2 text-sm text-muted-foreground",children:[e.jsx("li",{children:d("providers.drawer.hints.checkUrl")}),e.jsx("li",{children:d("providers.drawer.hints.checkAuth")}),e.jsx("li",{children:d("providers.drawer.hints.checkModels")})]})]}),N&&e.jsxs("div",{className:"rounded-xl bg-accent p-4 text-sm text-foreground",children:[e.jsx("p",{className:"font-medium text-primary",children:d("providers.drawer.hints.advancedTitle")}),e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:d("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:[!ae&&b?e.jsx("button",{type:"button",onClick:b,disabled:w,className:"text-muted-foreground underline-offset-2 hover:text-destructive hover:underline disabled:opacity-50",children:d("providers.actions.delete")}):null,M?e.jsx("span",{className:"text-destructive","aria-live":"polite",children:M}):null]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{type:"button",variant:"outline",onClick:o,disabled:w,className:"bg-card",children:d("common.actions.cancel")}),e.jsx(B,{type:"button",variant:"outline",onClick:z,disabled:w||ie===0,className:"bg-card",children:d("common.actions.previous")}),he?null:e.jsx(B,{type:"button",onClick:D,disabled:w,children:d("common.actions.next")}),e.jsx(B,{type:"button",onClick:oe,disabled:w,children:d(w?"common.actions.saving":"common.actions.save")})]})]})]}),e.jsx(vs,{open:T,providerId:(n==null?void 0:n.id)??(l.id.trim()||"draft"),providerName:(n==null?void 0:n.label)||l.label.trim()||l.id.trim()||d("providers.drawer.summary.untitled"),existingModelIds:l.models.map(p=>p.id.trim()).filter(Boolean),draft:m.serialize(),onImport:m.handleImportModels,onClose:()=>c(!1)})]})}function ys({provider:a,defaultModel:t,modelCount:n,requests24h:s,avgLatencyMs:o,routeCount:h,testResult:x,onTest:j,onEdit:y}){var N;const{t:b}=W(),d=a.label||a.id,m=d.slice(0,1).toUpperCase()||"?",l=((N=dt.find(u=>u.value===(a.type??"custom")))==null?void 0:N.label)??a.type??"custom",C=x?x.ok?"ok":"fail":"untested";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:m}),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:d,children:d}),e.jsx(te,{variant:"outline",className:"shrink-0 rounded-full px-2 py-0 text-[10px] font-normal text-muted-foreground",children:l})]}),e.jsx("code",{className:"mt-0.5 block truncate font-mono text-[10.5px] text-muted-foreground",title:a.baseUrl,children:a.baseUrl})]}),e.jsx(Ns,{state:C})]}),e.jsxs("div",{className:"mt-3 grid grid-cols-3 gap-2",children:[e.jsx(it,{label:b("providers.card.statModels"),value:n>0?String(n):"—"}),e.jsx(it,{label:b("providers.card.statRequests24h"),value:s!=null?s.toLocaleString():"—"}),e.jsx(it,{label:b("providers.card.statAvgLatency"),value:ls(o,b("common.units.ms"),{maximumFractionDigits:0})})]}),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:b("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:b("providers.card.routeCount",{count:h})}),e.jsxs("div",{className:"ml-auto flex shrink-0 gap-1.5",children:[e.jsx(B,{variant:"outline",size:"sm",className:"h-7 px-2.5 text-[11px]",onClick:j,children:b("providers.actions.test")}),e.jsx(B,{variant:"outline",size:"sm",className:"h-7 px-2.5 text-[11px]",onClick:y,children:b("providers.actions.edit")})]})]})]})}function it({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 Ns({state:a}){const{t}=W();return a==="ok"?e.jsx(te,{variant:"success",className:"shrink-0 rounded-full px-1.5 py-0 text-[10px]",children:t("providers.card.health.ok")}):a==="fail"?e.jsx(te,{variant:"destructive",className:"shrink-0 rounded-full px-1.5 py-0 text-[10px]",children:t("providers.card.health.fail")}):e.jsx(te,{variant:"secondary",className:"shrink-0 rounded-full px-1.5 py-0 text-[10px]",children:t("providers.card.health.untested")})}function ws({providersLength:a,filteredProviders:t,testResults:n,providerSearch:s,providerTypeFilter:o,configPending:h,defaultLabels:x,config:j,customEndpoints:y,onTest:b,onEdit:d,onProviderSearchChange:m,onProviderTypeChange:l,onResetFilters:C}){const{t:N}=W(),[u,w]=f.useState("usage"),k=bt(Se.stats.model(1,50),{url:"/api/stats/model",method:"GET",params:{days:1,limit:50}},{retry:!1}),{requestsByProvider:M,latencyByProvider:R}=f.useMemo(()=>{const T=new Map,c=new Map,S=new Map;for(const V of k.data??[]){const q=V.provider;T.set(q,(T.get(q)??0)+V.requests),V.avgLatencyMs>0&&(c.set(q,(c.get(q)??0)+V.avgLatencyMs*V.requests),S.set(q,(S.get(q)??0)+V.requests))}const L=new Map;for(const V of T.keys()){const q=S.get(V)??0;L.set(V,q>0?(c.get(V)??0)/q:null)}return{requestsByProvider:T,latencyByProvider:L}},[k.data]),X=f.useMemo(()=>{const T=new Map;for(const c of t)T.set(c.id,as(j,y,c.id).length);return T},[j,y,t]),_=f.useMemo(()=>{const T=[...t],c=(S,L)=>(S.label||S.id).localeCompare(L.label||L.id);return u==="usage"&&k.isSuccess?T.sort((S,L)=>(M.get(L.id)??0)-(M.get(S.id)??0)||c(S,L)):T.sort(c),T},[t,u,k.isSuccess,M]);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(Qe,{className:"overflow-hidden",children:e.jsx(Ge,{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(pe,{value:s,onChange:T=>m(T.target.value),placeholder:N("providers.filters.searchPlaceholder"),className:"h-9 w-full sm:w-64"}),e.jsxs(tt,{value:o,onValueChange:l,children:[e.jsx(st,{className:"h-9 w-[130px] text-xs",children:e.jsx(at,{})}),e.jsxs(rt,{children:[e.jsx(Oe,{value:"all",children:N("providers.filters.typeAll")}),dt.map(T=>e.jsx(Oe,{value:T.value??"custom",children:T.label},T.value??"custom"))]})]}),e.jsxs(tt,{value:u,onValueChange:T=>w(T),children:[e.jsx(st,{className:"h-9 w-[104px] text-xs","aria-label":N("providers.list.sortLabel"),children:e.jsx(at,{})}),e.jsxs(rt,{children:[e.jsx(Oe,{value:"usage",children:N("providers.list.sortUsage")}),e.jsx(Oe,{value:"name",children:N("providers.list.sortName")})]})]}),e.jsx(te,{variant:"secondary",className:"shrink-0 rounded-full px-2.5 py-1 text-[11px]",children:t.length}),e.jsx(B,{variant:"ghost",size:"sm",onClick:C,disabled:!s.trim()&&o==="all",className:"h-9 shrink-0 rounded-full px-2.5 text-xs",children:N("common.actions.reset")})]})})}),h?e.jsx("div",{className:"flex min-h-[160px] items-center justify-center text-sm text-muted-foreground",children:N("common.loading")}):a===0?e.jsx(lt,{compact:!0,title:N("providers.emptyState"),description:e.jsxs(e.Fragment,{children:[e.jsx("p",{children:N("providers.emptyStateSub")}),e.jsx("p",{className:"mt-1",children:N("workbench.list.emptyHint")})]})}):t.length===0?e.jsx(lt,{compact:!0,title:N("providers.emptyFiltered")}):e.jsx("div",{className:"grid gap-3.5 sm:grid-cols-2 xl:grid-cols-3",children:_.map(T=>{var c;return e.jsx(ys,{provider:T,defaultModel:x.get(T.id),modelCount:((c=T.models)==null?void 0:c.length)??0,requests24h:k.isSuccess?M.get(T.id)??0:null,avgLatencyMs:k.isSuccess?R.get(T.id)??null:null,routeCount:X.get(T.id)??0,testResult:n[T.id]??null,onTest:()=>b(T),onEdit:()=>d(T)},T.id)})})]})}function ks({routing:a,endpoint:t,tabInfo:n,config:s,customEndpoints:o}){var w,k;const{t:h}=W(),x=a.routesByEndpoint[t]||[],j=a.savingRouteFor===t,y=a.savingCompatibilityPolicy,b=a.writingEndpoint===t,d=((w=n==null?void 0:n.protocols)==null?void 0:w.some(M=>M.startsWith("openai")))??t==="openai",m=rs(t,s,o),l=d?(m==null?void 0:m.enabled)??!1:!1,N=((k=n==null?void 0:n.protocols)==null?void 0:k.includes("anthropic"))??t==="anthropic"?vt:jt,u=new Set(x.map(M=>M.source.trim()).filter(Boolean));return e.jsx(Qe,{"data-testid":"endpoint-config-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(Ge,{className:"space-y-3 p-4",children:[e.jsx("h3",{className:"text-[12.5px] font-semibold",children:h("workbench.endpointConfig.title")}),d?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(Ne,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:h("modelManagement.openaiCompatibility.toggleLabel")}),e.jsx("p",{className:"text-[10.5px] text-muted-foreground",children:h(l?"modelManagement.openaiCompatibility.enabledHint":"modelManagement.openaiCompatibility.disabledHint")})]}),e.jsx(nt,{"data-testid":"compatibility-toggle",checked:l,onCheckedChange:M=>void a.handleCompatibilityEnabledChange(t,M),disabled:y||b,"aria-label":h("modelManagement.openaiCompatibility.toggleLabel")})]}):null,e.jsxs("div",{children:[e.jsx("p",{className:"mb-1.5 text-[11px] text-muted-foreground",children:h("settings.routing.suggested")}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:N.map(M=>{const R=u.has(M);return e.jsx("button",{"data-testid":"suggestion-chip",type:"button",onClick:()=>a.handleAddSuggestion(t,M),disabled:j||R,className:ve("h-6 border px-2 text-[10.5px] transition-colors",R?"border-border bg-secondary/40 text-muted-foreground/50":"border-border bg-card hover:border-primary hover:text-primary"),children:M},`${t}-${M}`)})})]})]})})}const gt=6;function Ze({value:a,onChange:t,options:n,disabled:s,placeholder:o,ariaLabel:h}){const{t:x}=W(),j=f.useId(),[y,b]=f.useState(!1),[d,m]=f.useState(""),l=f.useRef(null),C=f.useRef(!1),[N,u]=qt(Vt.modelManagement.recentRouteTargets,[]),w=f.useMemo(()=>{const c=new Map;for(const S of n)c.set(S.value,S);return c},[n]),k=(c,S)=>S?[c.label,c.value,c.providerId??"",c.providerLabel??"",c.modelId??"",c.modelLabel??""].join(" ").toLowerCase().includes(S):!0,M=f.useMemo(()=>{const c=d.trim().toLowerCase(),S=n.filter(A=>k(A,c)),L=N.map(A=>w.get(A)??(c?void 0:{value:A,label:A,kind:"custom"})).filter(A=>!!A).filter(A=>k(A,c)).slice(0,gt),V=[];L.length>0&&V.push({key:"recent",label:x("modelManagement.targetPicker.recent"),options:L});const q=new Map,se=[];for(const A of S){if(A.kind==="custom"||!A.providerId){se.push(A);continue}const ne=`provider:${A.providerId}`,ae=q.get(ne);ae?ae.options.push(A):q.set(ne,{key:ne,label:A.providerLabel??A.providerId,options:[A]})}return V.push(...q.values()),se.length>0&&V.push({key:"custom",label:x("modelManagement.targetPicker.custom"),options:se,muted:!0}),V},[w,n,N,d,x]),R=M.reduce((c,S)=>c+S.options.length,0),X=c=>{t(c),u(S=>[c,...S.filter(L=>L!==c)].slice(0,gt)),m(""),C.current=!0,typeof document<"u"&&document.activeElement instanceof HTMLElement&&document.activeElement.blur(),b(!1),typeof window<"u"?window.requestAnimationFrame(()=>{C.current=!1}):C.current=!1},_=c=>c.kind==="passthrough"?x("modelManagement.targetPicker.passthrough"):c.kind==="custom"?x("modelManagement.targetPicker.customValue"):x("modelManagement.targetPicker.model"),T=c=>c.kind==="passthrough"||c.kind==="custom"?c.label:c.modelLabel??c.label;return e.jsxs(cs,{open:y,onOpenChange:c=>{c&&C.current||(b(c),c&&m(""))},children:[e.jsx(us,{asChild:!0,children:e.jsx(pe,{value:a,onChange:c=>{t(c.target.value),m(c.target.value),y||b(!0)},onFocus:()=>{m(""),b(!0)},onClick:()=>{y||b(!0)},placeholder:o,disabled:s,autoComplete:"off",role:"combobox","aria-label":h,"aria-expanded":y,"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:c=>{var S;c.preventDefault(),(S=l.current)==null||S.focus()},onCloseAutoFocus:c=>{c.preventDefault()},children:[e.jsxs("div",{className:"space-y-2 border-b border-border px-3 py-3",children:[e.jsx(pe,{ref:l,value:d,onChange:c=>m(c.target.value),placeholder:x("modelManagement.targetPicker.searchPlaceholder"),className:"h-9",autoComplete:"off"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:d.trim()?x("modelManagement.targetPicker.matchCount",{count:R}):x("modelManagement.targetPicker.helper")})]}),R===0?e.jsx("div",{className:"px-3 py-4 text-center text-xs text-muted-foreground",children:x("common.noMatches")}):e.jsx("div",{id:j,role:"listbox",className:"min-h-0 flex-1 overflow-y-auto p-1.5",children:M.map(c=>e.jsxs("div",{className:"py-1",children:[e.jsxs("div",{className:ve("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",c.muted&&"opacity-80"),children:[e.jsx("span",{className:"truncate",children:c.label}),e.jsx("span",{children:c.options.length})]}),e.jsx("div",{className:"space-y-1",children:c.options.map(S=>e.jsxs("button",{type:"button",role:"option","aria-selected":S.value===a.trim(),className:ve("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",S.value===a.trim()&&"bg-accent text-accent-foreground"),onMouseDown:L=>{L.preventDefault()},onClick:()=>X(S.value),children:[e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate font-medium",children:T(S)}),e.jsx("span",{className:"block truncate text-xs text-muted-foreground",children:S.value})]}),e.jsxs("span",{className:"flex shrink-0 items-center gap-1",children:[S.isDefault?e.jsx(te,{variant:"secondary",className:"text-[10px]",children:x("modelManagement.targetPicker.default")}):null,e.jsx(te,{variant:S.kind==="passthrough"?"outline":"secondary",className:"text-[10px]",children:_(S)})]})]},`${c.key}-${S.value}`))})]},c.key))})]})]})}function Cs({routing:a,endpoint:t}){const{t:n}=W(),s=a.defaultsByEndpoint[t]??null,o=a.isDefaultsDirtyByEndpoint[t]??!1,h=a.savingDefaultsFor===t,x=a.writingEndpoint===t,j=a.providerModelOptions;return e.jsx(Qe,{"data-testid":"routing-defaults-card",className:"border-primary/40 bg-primary/5 shadow-none",children:e.jsxs(Ge,{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:n("workbench.defaults.title")}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:n("workbench.defaults.cardSubtitle")})]}),e.jsxs(ds,{summary:e.jsx("span",{className:"text-[11px] font-medium text-muted-foreground",children:n("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(Ne,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:n("workbench.defaults.reasoningLabel")}),e.jsx(Ze,{value:(s==null?void 0:s.reasoning)??"",onChange:y=>a.handleDefaultsChange(t,"reasoning",y),options:j,disabled:h,ariaLabel:n("workbench.defaults.reasoningLabel"),placeholder:n("workbench.defaults.targetPlaceholder")})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Ne,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:n("workbench.defaults.backgroundLabel")}),e.jsx(Ze,{value:(s==null?void 0:s.background)??"",onChange:y=>a.handleDefaultsChange(t,"background",y),options:j,disabled:h,ariaLabel:n("workbench.defaults.backgroundLabel"),placeholder:n("workbench.defaults.targetPlaceholder")})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Ne,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:n("workbench.defaults.thresholdLabel")}),e.jsx(pe,{type:"number",min:1,value:(s==null?void 0:s.longContextThreshold)||"",onChange:y=>{const b=Number.parseInt(y.target.value,10);a.handleDefaultsChange(t,"longContextThreshold",Number.isFinite(b)?b:0)},disabled:h,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(be,{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(Ze,{value:(s==null?void 0:s.completion)??"",onChange:y=>a.handleDefaultsChange(t,"completion",y),options:j,disabled:h,ariaLabel:n("workbench.defaults.completionLabel"),placeholder:n("workbench.defaults.targetPlaceholder")})}),e.jsxs(B,{size:"sm","data-testid":"save-defaults",onClick:()=>void a.handleSaveDefaults(t),disabled:h||!o||x,className:"relative",children:[n(h?"common.actions.saving":"workbench.defaults.save"),o?e.jsx("span",{className:"absolute -right-1 -top-1 h-2 w-2 rounded-full bg-warning"}):null]})]})]})})}const Ss={anthropic:"/anthropic",openai:"/openai"};function Ms(a){var t;return(t=a.paths)!=null&&t.length?a.paths[0].path:a.path?a.path:`/${a.id}`}function Ps({tabs:a,customEndpoints:t,routeCounts:n,selectedEndpointId:s,onSelect:o,onCreate:h,onEditEndpoint:x,onDeleteEndpoint:j}){const{t:y}=W(),b=a.map(d=>{const m=t.find(C=>C.id===d.key);if(!m)return{key:d.key,label:d.label,path:Ss[d.key]??`/${d.key}`,protocols:d.protocols??[],enabled:!0};const l=m.paths??(m.path?[{path:m.path,protocol:m.protocol??"anthropic"}]:[]);return{key:d.key,label:m.label||m.id,path:Ms(m),protocols:[...new Set(l.map(C=>C.protocol))],enabled:m.enabled!==!1,custom:m}});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:y("workbench.endpointRail.title")}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:y("workbench.endpointRail.subtitle")})]}),e.jsxs("div",{className:"flex gap-1.5 p-2 lg:flex-col lg:gap-1",children:[b.map(d=>{const m=d.key===s,l=n[d.key]??0,C=!d.enabled;return e.jsxs("div",{"data-testid":"endpoint-row",className:ve("flex shrink-0 items-stretch border transition-colors lg:shrink",m?"border-primary/40 bg-primary/5":"border-border bg-card hover:bg-accent",C?"opacity-60":""),children:[e.jsxs("button",{type:"button",onClick:()=>o(d.key),className:"flex min-w-0 flex-1 items-center gap-2 px-2.5 py-2 text-left",children:[e.jsx("span",{className:ve("h-1.5 w-1.5 shrink-0 rounded-full",m?"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:d.label,children:d.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:d.path}),e.jsx("span",{"aria-hidden":!0,children:"·"}),e.jsx("span",{className:"shrink-0 tabular-nums",children:y("workbench.endpointRail.ruleCount",{count:l})})]})]})]}),d.custom?e.jsxs("div",{className:"flex items-center gap-0.5 pr-1",children:[e.jsx("button",{type:"button",onClick:()=>x(d.custom),className:"flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-foreground",title:y("common.edit"),"aria-label":y("common.edit"),children:e.jsx(kt,{className:"h-3 w-3","aria-hidden":!0})}),d.custom.deletable!==!1?e.jsx("button",{type:"button",onClick:()=>j(d.custom),className:"flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-destructive",title:y("common.delete"),"aria-label":y("common.delete"),children:e.jsx(Ct,{className:"h-3 w-3","aria-hidden":!0})}):null]}):null]},d.key)}),e.jsxs("button",{type:"button","data-testid":"create-endpoint",onClick:h,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:["+ ",y("workbench.endpointRail.add")]})]})]})}function Es({endpointPath:a,defaultTarget:t}){const{t:n}=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:n("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:n("workbench.flow.clientStep")}),e.jsx(be,{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:[n("workbench.flow.endpointStep")," ",e.jsx("span",{className:"font-mono",children:a})]}),e.jsx(be,{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:n("workbench.flow.matchStep")}),e.jsx(be,{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||n("workbench.flow.fallbackNote")})]})]})}function Ds({routing:a,endpoint:t,onRequestDeletePreset:n}){var m,l;const{t:s}=W(),o=a.presetsByEndpoint[t]??[],h=a.presetNameByEndpoint[t]??"",x=a.presetErrorByEndpoint[t],j=a.savingPresetFor===t,y=((m=a.applyingPreset)==null?void 0:m.endpoint)===t?a.applyingPreset.name:null,b=((l=a.deletingPreset)==null?void 0:l.endpoint)===t?a.deletingPreset.name:null,d=a.writingEndpoint===t;return e.jsx(Qe,{"data-testid":"routing-presets-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(Ge,{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(B,{variant:"outline",size:"sm","data-testid":"save-preset",onClick:()=>void a.handleSavePreset(t),disabled:j||d,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(pe,{"data-testid":"preset-name-input",value:h,onChange:C=>a.handlePresetNameChange(t,C.target.value),placeholder:s("modelManagement.presets.namePlaceholder"),disabled:j,className:"h-8 text-xs"}),x?e.jsx("p",{className:"text-xs text-destructive",children:x}):null,o.length===0?e.jsx("p",{className:"py-2 text-center text-[11px] text-muted-foreground",children:s("modelManagement.presets.empty")}):e.jsx(_t,{children:e.jsx("div",{className:"grid grid-cols-1 gap-1.5 sm:grid-cols-2",children:o.map(C=>{const N=y===C.name,u=b===C.name,w=Object.entries(C.modelRoutes??{}),k=w.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(Qt,{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:C.name}),e.jsx(te,{variant:"outline",className:"mt-0.5 text-[10px] font-normal",children:k>0?s("modelManagement.presets.rulesCount",{count:k}):s("modelManagement.presets.noRules")})]})}),k>0?e.jsx(Gt,{side:"bottom",className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1 text-xs",children:[w.slice(0,5).map(([M,R])=>e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"truncate",children:M}),e.jsx(be,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:R})]},M)),k>5?e.jsxs("div",{className:"text-muted-foreground",children:["…+",k-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:C}),disabled:N||u||d,children:s(N?"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:()=>n(t,C),disabled:u||N||d,children:s(u?"modelManagement.presets.deleting":"modelManagement.presets.delete")})]})]},C.name)})})})]})})}function Rs({entry:a,index:t,savingRoute:n,options:s,sourceListId:o,onRouteChange:h,onRemoveRoute:x}){const{t:j}=W(),{attributes:y,listeners:b,setNodeRef:d,setActivatorNodeRef:m,transform:l,transition:C,isDragging:N}=St({id:a.id});return e.jsxs("div",{ref:d,"data-testid":"route-rule-row","data-id":a.id,style:{transform:Pt.Transform.toString(l),transition:C},className:ve("flex items-center gap-2 border border-border bg-card p-2",N&&"z-10 opacity-60 shadow-[var(--surface-shadow-lg)]"),children:[e.jsx("button",{ref:m,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",...y,...b,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(pe,{"data-testid":"route-rule-source",value:a.source,onChange:u=>h(a.id,"source",u.target.value),placeholder:j("settings.routing.sourcePlaceholder"),list:o,disabled:n,className:"h-8 min-w-0 flex-1 text-xs"}),e.jsx(be,{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(Ze,{value:a.target,onChange:u=>h(a.id,"target",u),options:s,disabled:n,ariaLabel:j("workbench.routing.targetLabel"),placeholder:j("settings.routing.targetPlaceholder")})}),e.jsx(B,{variant:"ghost",size:"icon","data-testid":"route-rule-delete",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>x(a.id),disabled:n,"aria-label":j("common.delete"),children:e.jsx(ft,{className:"h-3.5 w-3.5","aria-hidden":!0})})]})}function Ts({routing:a,endpoint:t,tabInfo:n}){var u;const{t:s}=W(),o=a.routesByEndpoint[t]||[],h=a.routeError[t],x=a.savingRouteFor===t,j=a.isDirtyByEndpoint[t]??!1,y=a.writingEndpoint===t,b=a.providerModelOptions,d=`route-source-${t}`,m=Et(ct(It,{activationConstraint:{distance:6}}),ct(Ft,{coordinateGetter:Lt})),l=w=>{const{active:k,over:M}=w;!M||k.id===M.id||a.handleReorderRules(t,String(k.id),String(M.id))},N=((u=n==null?void 0:n.protocols)==null?void 0:u.includes("anthropic"))??t==="anthropic"?vt:jt;return e.jsx(Qe,{"data-testid":"routing-rules-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(Ge,{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(te,{variant:"outline",className:"text-[10.5px] font-normal tabular-nums",children:o.length})]}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:s("workbench.routing.rulesSubtitle")})]}),e.jsx(B,{variant:"outline",size:"sm","data-testid":"add-route",onClick:()=>a.handleAddRoute(t),disabled:x,children:s("settings.routing.add")})]}),h?e.jsx("p",{className:"text-xs text-destructive",children:h}):null,o.length===0?e.jsx(lt,{compact:!0,title:s("workbench.routing.emptyTitle"),description:s("workbench.routing.emptyDescription"),action:e.jsx(B,{size:"sm",onClick:()=>a.handleAddRoute(t),disabled:x,children:s("workbench.routing.addFirst")})}):e.jsx(Dt,{sensors:m,collisionDetection:Rt,onDragEnd:l,children:e.jsx(Tt,{items:o.map(w=>w.id),strategy:Ot,children:e.jsx("div",{className:"flex flex-col gap-1.5",children:o.map((w,k)=>e.jsx(Rs,{entry:w,index:k,savingRoute:x,options:b,sourceListId:d,onRouteChange:(M,R,X)=>a.handleRouteChange(t,M,R,X),onRemoveRoute:M=>a.handleRemoveRoute(t,M)},w.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(B,{variant:"outline",size:"sm","data-testid":"reset-routes",onClick:()=>a.handleResetRoutes(t),disabled:x||!j,children:s("common.actions.reset")}),e.jsxs(B,{size:"sm","data-testid":"save-routes",onClick:()=>void a.handleSaveRoutes(t),disabled:x||y,className:"relative",children:[s(x?"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:d,children:N.map(w=>e.jsx("option",{value:w},`${d}-${w}`))})]})})}const Os={simulateRequest(a){return{url:"/api/routing/simulate",method:"POST",data:a}}},Ls=350;function Fs(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 Is({tabs:a,endpoint:t,onEndpointChange:n}){var M;const{t:s}=W(),o=a.filter(R=>R.key!=="providers"),[h,x]=f.useState(((M=o[0])==null?void 0:M.key)??"anthropic"),j=t??h,y=R=>{t&&n?n(R):x(R)},[b,d]=f.useState(""),[m,l]=f.useState(!1),[C,N]=f.useState("");f.useEffect(()=>{const R=setTimeout(()=>N(b.trim()),Ls);return()=>clearTimeout(R)},[b]);const{data:u,isFetching:w,error:k}=bt(["routing","simulate",j,C,m],Os.simulateRequest({endpoint:j,model:C||void 0,thinking:m}),{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(tt,{value:j,onValueChange:y,children:[e.jsx(st,{className:"h-8 w-[168px]",children:e.jsx(at,{})}),e.jsx(rt,{children:o.map(R=>e.jsx(Oe,{value:R.key,children:R.label},R.key))})]})]}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(nt,{checked:m,onCheckedChange:l,"aria-label":s("workbench.hitSim.thinking")}),s("workbench.hitSim.thinking")]})]}),e.jsx(pe,{value:b,onChange:R=>d(R.target.value),placeholder:s("workbench.hitSim.modelPlaceholder"),className:"h-9 text-xs",spellCheck:!1,autoComplete:"off","aria-label":s("workbench.hitSim.modelPlaceholder")}),e.jsx(As,{result:u,loading:w,errorMessage:(k==null?void 0:k.message)??null,requestedModel:C})]})}function As({result:a,loading:t,errorMessage:n,requestedModel:s}){const{t:o}=W();if(n)return e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o("workbench.hitSim.errorPrefix"),": ",n]});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:o("workbench.hitSim.empty")});const h=Fs(a.reason,o),x=h.tone==="fallback",j=s||o("workbench.hitSim.anyModel");return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:x?"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:x?"text-[11px] font-semibold text-warning":"text-[11px] font-semibold text-success",children:h.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]}),h.detail?e.jsx("div",{className:"mt-1 text-[11px] text-muted-foreground",children:h.detail}):null]}),x?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:o("workbench.hitSim.fallbackHint")}):null]})}function Bs({routing:a,config:t,customEndpoints:n,selectedEndpointId:s,routeCounts:o,onSelectEndpoint:h,onCreateEndpoint:x,onEditEndpoint:j,onDeleteEndpoint:y,onRequestDeletePreset:b}){var N;W();const d=s??((N=a.endpointTabs[0])==null?void 0:N.key)??"anthropic",m=a.endpointTabs.find(u=>u.key===d),l=a.defaultsByEndpoint[d],C=(()=>{var w;if(d==="anthropic")return"/anthropic";if(d==="openai")return"/openai";const u=n.find(k=>k.id===d);return(w=u==null?void 0:u.paths)!=null&&w.length?u.paths[0].path:u!=null&&u.path?u.path:`/${d}`})();return e.jsxs("div",{"data-testid":"routing-workspace",className:"flex flex-col gap-3.5",children:[e.jsx(Es,{endpointPath:C,defaultTarget:(l==null?void 0:l.completion)??null}),e.jsxs("div",{className:"grid items-start gap-3.5 lg:grid-cols-[200px_minmax(0,1fr)_288px]",children:[e.jsx(Ps,{tabs:a.endpointTabs,customEndpoints:n,routeCounts:o,selectedEndpointId:d,onSelect:h,onCreate:x,onEditEndpoint:j,onDeleteEndpoint:y}),e.jsxs("div",{className:"flex flex-col gap-3.5",children:[e.jsx(Cs,{routing:a,endpoint:d}),e.jsx(Ts,{routing:a,endpoint:d,tabInfo:m}),e.jsx(Ds,{routing:a,endpoint:d,onRequestDeletePreset:b})]}),e.jsxs("div",{className:"flex flex-col gap-3.5",children:[e.jsx(Is,{tabs:a.endpointTabs,endpoint:d,onEndpointChange:h}),e.jsx(ks,{routing:a,endpoint:d,tabInfo:m,config:t,customEndpoints:n})]})]})]})}function zs({open:a,provider:t,options:n,usePreset:s,preservedExtras:o,onPresetChange:h,onConfirm:x,onClose:j}){const{t:y}=W();return t?e.jsx($e,{open:a,onOpenChange:b=>!b&&j(),children:e.jsxs(He,{className:"max-w-2xl",onInteractOutside:b=>b.preventDefault(),children:[e.jsxs(Ue,{children:[e.jsx(qe,{children:y("providers.testDialog.title")}),e.jsx(Ve,{children:y("providers.testDialog.subtitle",{name:t.label||t.id})})]}),e.jsxs(_e,{className:"space-y-4",children:[e.jsx("div",{className:"rounded-xl bg-accent p-4 text-sm text-primary",children:y("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(Ne,{htmlFor:"provider-test-preset",children:y("providers.testDialog.presetLabel")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:y("providers.testDialog.presetDescription")})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(nt,{id:"provider-test-preset",checked:s,onCheckedChange:h})})]}),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:y("providers.testDialog.presetPreviewSummary")}),e.jsx("div",{className:"mt-2 space-y-1",children:n.map(b=>e.jsxs("code",{className:"block rounded-lg bg-secondary px-2 py-1 text-xs",children:[b.key,": ",b.value]},b.key))})]})}):e.jsx("p",{className:"text-xs text-muted-foreground",children:y("providers.testDialog.presetDescription")})]}),Object.keys(o).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:y("providers.testDialog.preservedInfo")}),Object.entries(o).map(([b,d])=>e.jsxs("code",{className:"block rounded-lg border border-transparent bg-card px-2 py-1 shadow-[var(--surface-shadow)]",children:[b,": ",d]},b))]})]}),e.jsxs(Ke,{children:[e.jsx(B,{variant:"outline",onClick:j,children:y("providers.testDialog.cancel")}),e.jsx(B,{onClick:()=>void x(),children:y("providers.testDialog.primary")})]})]})}):null}function la(){const{t:a}=W(),t=ns(),n=ps(t),s=hs(t,{sanitizeDraftsForProvider:n.sanitizeDraftsForProvider}),[o,h]=zt(),x=o.get("tab"),j=x==="routing"||x==="endpoints"?"routing":"providers";f.useEffect(()=>{x==="endpoints"&&h(E=>{const I=new URLSearchParams(E);return I.set("tab","routing"),I},{replace:!0})},[x,h]);const[y,b]=f.useState(!1),[d,m]=f.useState(void 0),[l,C]=f.useState(null),[N,u]=f.useState(!1),w=o.get("endpoint"),[k,M]=f.useState(w);f.useEffect(()=>{M(w)},[w]);const R=E=>{h(I=>{const U=new URLSearchParams(I);return U.set("tab","routing"),U.set("endpoint",E),U},{replace:!0})},X=()=>{h(E=>{const I=new URLSearchParams(E);return I.delete("endpoint"),I},{replace:!0})};f.useEffect(()=>{k&&(t.customEndpointsQuery.isPending||n.endpointTabs.some(E=>E.key===k)||X())},[k,n.endpointTabs,t.customEndpointsQuery.isPending]);const _=()=>{m(void 0),b(!0)},T=E=>{m(E),b(!0)},c=E=>{h(I=>{const U=new URLSearchParams(I);return E==="providers"?U.delete("tab"):U.set("tab",E),U},{replace:!0})},S=async()=>{if(l){u(!0);try{l.kind==="provider"?await s.handleDeleteProvider(l.provider):l.kind==="preset"?await n.handleDeletePreset(l.endpoint,l.preset):await n.handleDeleteEndpoint(l.endpoint.id),C(null)}finally{u(!1)}}},L=(l==null?void 0:l.kind)==="provider"?os(t.config,t.customEndpoints,l.provider.id):0,V=(l==null?void 0:l.kind)==="provider"?a("providers.actions.delete"):(l==null?void 0:l.kind)==="preset"?a("modelManagement.presets.delete"):(l==null?void 0:l.kind)==="endpoint"?a("common.delete"):"",q=(l==null?void 0:l.kind)==="provider"?a("providers.confirm.delete",{name:l.provider.label||l.provider.id}):(l==null?void 0:l.kind)==="preset"?a("modelManagement.confirm.deletePreset",{name:l.preset.name}):(l==null?void 0:l.kind)==="endpoint"?a("modelManagement.deleteEndpointConfirm",{label:l.endpoint.label}):"",se=(l==null?void 0:l.kind)==="provider"?l.provider.label||l.provider.id:(l==null?void 0:l.kind)==="preset"?l.preset.name:(l==null?void 0:l.kind)==="endpoint"?l.endpoint.label:"",A=Object.values(n.routesByEndpoint).reduce((E,I)=>E+((I==null?void 0:I.length)??0),0),ne=Object.fromEntries(Object.entries(n.routesByEndpoint).map(([E,I])=>[E,(I==null?void 0:I.length)??0])),ae=[{value:"providers",icon:At,label:a("workbench.viewSwitch.providers"),description:a("workbench.viewSwitch.providersDesc"),count:s.providerCount},{value:"routing",icon:Bt,label:a("workbench.viewSwitch.routing"),description:a("workbench.viewSwitch.routingDesc"),count:A}];return e.jsxs("div",{className:"flex flex-col gap-6",children:[e.jsx(Ht,{actions:j==="providers"?e.jsx(B,{size:"sm",onClick:s.handleOpenCreate,children:a("providers.actions.add")}):e.jsx(B,{size:"sm",onClick:_,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:ae.map(E=>{const I=E.icon,U=j===E.value;return e.jsxs("button",{type:"button",role:"tab","aria-selected":U,onClick:()=>c(E.value),className:ve("motion-surface flex items-center gap-3 rounded-xl border p-4 text-left",U?"border-primary/40 bg-primary/5":"border-border bg-card hover:bg-muted/40"),children:[e.jsx("span",{className:ve("flex h-9 w-9 shrink-0 items-center justify-center rounded-lg",U?"bg-primary/10 text-primary":"bg-secondary text-muted-foreground"),children:e.jsx(I,{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:ve("text-sm font-semibold",U?"text-foreground":"text-muted-foreground"),children:E.label}),e.jsx(te,{variant:U?"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(ws,{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(Bs,{routing:n,config:t.config,customEndpoints:t.customEndpoints,routeCounts:ne,selectedEndpointId:k,onSelectEndpoint:R,onCreateEndpoint:_,onEditEndpoint:T,onDeleteEndpoint:E=>C({kind:"endpoint",endpoint:E}),onRequestDeletePreset:(E,I)=>C({kind:"preset",endpoint:E,preset:I})}),e.jsx(js,{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),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&&C({kind:"provider",provider:s.editingProvider})},onClose:()=>{s.setDrawerOpen(!1),s.setEditingProvider(void 0),s.setDrawerMode("create")},onSubmit:s.handleProviderSubmit}),e.jsx(zs,{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(fs,{open:!!s.noModelDialogProvider,provider:s.noModelDialogProvider,onClose:()=>s.setNoModelDialogProvider(null),onEdit:E=>{s.setNoModelDialogProvider(null),s.handleOpenEdit(E)}}),e.jsx(gs,{open:y,endpoint:d,onClose:()=>{b(!1),m(void 0)},onSuccess:()=>{t.configQuery.refetch()}}),e.jsx(bs,{dialog:n.presetDiffDialog,currentRoutes:n.presetDiffDialog?n.routesByEndpoint[n.presetDiffDialog.endpoint]||[]:[],onConfirm:(E,I)=>{n.setPresetDiffDialog(null),n.handleApplyPreset(E,I)},onClose:()=>n.setPresetDiffDialog(null)}),e.jsx($t,{open:!!l,onOpenChange:E=>{!E&&!N&&C(null)},title:V,description:q,confirmLabel:a(N?"common.actions.loading":"common.delete"),cancelLabel:a("common.actions.cancel"),loading:N,onConfirm:S,children:se?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:se}),(l==null?void 0:l.kind)==="provider"&&L>0?e.jsx("p",{className:"text-xs text-muted-foreground",children:a("providers.confirm.deleteImpact",{count:L})}):null]}):null})]})}export{la as default};
1
+ import{r as f,ax as Nt,j as e,ay as wt,as as ft,ab as be,az as kt,aA as Ct,aB as St,aC as Mt,aD as Pt,aE as Et,aF as ct,aG as Dt,aH as Rt,aI as Tt,aJ as Ot,aK as Lt,aL as Ft,aM as It,aN as At,aO as Bt}from"./vendor-CITafuNQ.js";import{d as zt}from"./router-BoBrmro7.js";import{C as $t}from"./ConfirmDialog-Ci29hhDD.js";import{P as Ht}from"./PageToolbar-xVyzEX46.js";import{t as ce,q as Se,e as ze,B,a as Ut,c as bt,b as qt,s as Vt,T as _t,f as Kt,g as Qt,h as Gt}from"./app-WMvqYU5W.js";import{B as te}from"./badge-DMgopDMC.js";import{c as ve}from"./global-D5dyWHqO.js";import{d as ut,g as mt,a as pt,b as Wt,c as ht,e as xt,r as Jt,f as Be,m as Le,h as Xt,u as Yt,P as dt,i as Zt,j as Re,S as es,B as ts,M as ss,k as as,l as rs,C as vt,O as jt,n as ns,o as os}from"./useProviderForm-BRhWbili.js";import{a as is}from"./query-DZF7K6hv.js";import{g as Te}from"./gateway-T6-6vX59.js";import{u as et}from"./useAppMutation-aXncU1Ie.js";import{D as $e,A as He,a as Ue,b as qe,c as Ve,d as _e,e as Ke}from"./DialogShell-iCyqEFRA.js";import{L as Ne,I as pe}from"./label-Dg8bOG83.js";import{S as tt,a as st,b as at,c as rt,d as Oe}from"./select-BMTHg2Ox.js";import{S as nt}from"./switch-BjJJ5nhB.js";import{u as W}from"./i18n-PeX9kBVO.js";import{C as Qe,a as Ge}from"./card-kh1_vqEo.js";import{a as lt}from"./PageState-BzdQq00f.js";import{b as ls}from"./types-DYz12j32.js";import{D as ds}from"./disclosure-Dpus5Sms.js";import{P as cs,c as us,b as ms}from"./popover-BPqySDlA.js";import"./radix-Bux_1C5J.js";function ps(a){const{t,pushToast:n,config:s,setConfig:o,configQuery:h,customEndpoints:x,tabs:j,ensureConfig:y}=a,b=is(),[d,m]=f.useState({}),[l,C]=f.useState({}),[N,u]=f.useState(null),[w,k]=f.useState({}),[M,R]=f.useState({}),[X,_]=f.useState({}),[T,c]=f.useState(null),[S,L]=f.useState(null),[V,q]=f.useState(null),[se,A]=f.useState(!1),[ne,ae]=f.useState(null),[E,I]=f.useState({}),[U,we]=f.useState(null),oe=f.useRef(null),[ie,he]=f.useState(null),ue=r=>{oe.current=r,he(r)},xe=()=>{oe.current=null,he(null)},ge=f.useMemo(()=>j.filter(r=>r.key!=="providers"),[j]);f.useEffect(()=>{if(!h.data)return;const r=h.data;m(g=>{const i=ut(r,x);if(!g||Object.keys(g).length===0)return i;const v={...i};for(const[P,O]of Object.entries(g)){if(!(P in i))continue;const F=mt(r,x,P);if(pt(O,F))v[P]=O;else{const J=new Map(O.map(K=>[K.source,K.id]));v[P]=i[P].map(K=>({...K,id:J.get(K.source)??K.id}))}}return v}),I(g=>{const i=Wt(r,x);if(!g||Object.keys(g).length===0)return i;const v={...i};for(const[P,O]of Object.entries(g)){if(!(P in i))continue;const F=ht(r,x,P);JSON.stringify(O)!==JSON.stringify(F)&&(v[P]=O)}return v}),C({}),k(xt(r,x))},[h.data,x]);const fe=(s==null?void 0:s.providers)??[],je=f.useMemo(()=>{const r=[],g=new Set;for(const i of fe){const v=i.label&&i.label!==i.id?`${i.label} (${i.id})`:i.id,P=i.models??[];if(P.length>0)for(const F of P){const J=`${i.id}:${F.id}`;g.has(J)||(g.add(J),r.push({value:J,label:`${v} · ${F.label??F.id}`,providerId:i.id,providerLabel:v,modelId:F.id,modelLabel:F.label??F.id,kind:"model",isDefault:i.defaultModel===F.id}))}else if(i.defaultModel){const F=`${i.id}:${i.defaultModel}`;g.has(F)||(g.add(F),r.push({value:F,label:`${v} · ${i.defaultModel}`,providerId:i.id,providerLabel:v,modelId:i.defaultModel,modelLabel:i.defaultModel,kind:"model",isDefault:!0}))}const O=`${i.id}:*`;g.has(O)||(g.add(O),r.push({value:O,label:t("settings.routing.providerPassthroughOption",{provider:v}),providerId:i.id,providerLabel:v,modelId:"*",modelLabel:"*",kind:"passthrough"}))}for(const i of Object.values(d).flat()){const v=i.target.trim();v&&!g.has(v)&&(g.add(v),r.push({value:v,label:v,modelId:v,modelLabel:v,kind:"custom"}))}return r},[fe,d,t]),Fe=r=>s?mt(s,x,r):{},Me=f.useMemo(()=>{const r={};for(const g of ge){const i=d[g.key]||[];r[g.key]=pt(i,Fe(g.key))}return r},[s,x,d,ge]),We=f.useMemo(()=>{const r={};if(!s)return r;for(const g of ge){const i=E[g.key];if(!i){r[g.key]=!1;continue}const v=ht(s,x,g.key);r[g.key]=JSON.stringify(i)!==JSON.stringify(v)}return r},[s,x,E,ge]),Je=(r,g,i)=>{I(v=>({...v,[r]:{...v[r]??{completion:null,reasoning:null,background:null,longContextThreshold:6e4},[g]:i}}))},D=async r=>{var v,P,O,F,J,K,Q,re;if(!y()||oe.current)return;const g=E[r];if(!g)return;const i={completion:(v=g.completion)!=null&&v.trim()?g.completion.trim():null,reasoning:(P=g.reasoning)!=null&&P.trim()?g.reasoning.trim():null,background:(O=g.background)!=null&&O.trim()?g.background.trim():null,longContextThreshold:Number.isFinite(g.longContextThreshold)&&g.longContextThreshold>0?Math.floor(g.longContextThreshold):s.defaults.longContextThreshold};we(r),ue(r);try{const Z=x.find(G=>G.id===r);if(Z){const G={...Z.routing??{},defaults:i,modelRoutes:((F=Z.routing)==null?void 0:F.modelRoutes)??{}};await ze.update(r,{routing:G}),o(de=>{if(!de)return de;const Ye=[...de.customEndpoints??[]],ot=Ye.findIndex(yt=>yt.id===r);return ot===-1?de:(Ye[ot]={...Ye[ot],routing:G},{...de,customEndpoints:Ye})}),await b.invalidateQueries({queryKey:Se.customEndpoints.all()})}else{const G=r,de={...s,endpointRouting:{...s.endpointRouting??{},[G]:{defaults:i,modelRoutes:((K=(J=s.endpointRouting)==null?void 0:J[G])==null?void 0:K.modelRoutes)??(G==="anthropic"?s.modelRoutes??{}:{}),compatibility:(re=(Q=s.endpointRouting)==null?void 0:Q[G])==null?void 0:re.compatibility}}};await Te.saveConfig(de),o(de)}I(G=>({...G,[r]:i})),n({title:t("workbench.defaults.saveSuccess"),variant:"success"}),h.refetch()}catch(Z){n({title:t("workbench.defaults.saveFailure",{message:ce(Z).message}),variant:"error"})}finally{we(null),xe()}},z=(r,g)=>{k(i=>({...i,[r]:g})),o(i=>{if(!i)return i;if(r==="anthropic"||r==="openai")return{...i,routingPresets:{...i.routingPresets,[r]:g}};const v=[...i.customEndpoints??[]],P=v.findIndex(O=>O.id===r);return P===-1?i:(v[P]={...v[P],routingPresets:g},{...i,customEndpoints:v})})},H=(r,g)=>{R(i=>({...i,[r]:g})),g.trim()&&_(i=>({...i,[r]:null}))},p=async r=>{if(!y()||oe.current)return;const g=(M[r]??"").trim();if(!g){_(i=>({...i,[r]:t("modelManagement.validation.presetName")}));return}if((w[r]??[]).some(i=>i.name.toLowerCase()===g.toLowerCase())){_(i=>({...i,[r]:t("modelManagement.validation.presetDuplicate",{name:g})}));return}c(r),ue(r);try{const v=(await Le.savePreset(r,g)).presets??[];z(r,v),R(P=>({...P,[r]:""})),_(P=>({...P,[r]:null})),n({title:t("modelManagement.toast.presetSaved",{name:g}),variant:"success"})}catch(i){n({title:t("modelManagement.toast.presetSaveFailure",{message:ce(i).message}),variant:"error"})}finally{c(null),xe(),h.refetch()}},$=async(r,g)=>{if(y()&&!oe.current){L({endpoint:r,name:g.name}),ue(r);try{const v=(await Le.applyPreset(r,g.name)).config;o(v);const P=ut(v,x);m(O=>({...O,[r]:P[r]??[]})),k(xt(v,x)),r!=="anthropic"&&r!=="openai"&&await b.invalidateQueries({queryKey:Se.customEndpoints.all()}),n({title:t("modelManagement.toast.presetApplySuccess",{name:g.name}),variant:"success"})}catch(i){n({title:t("modelManagement.toast.presetApplyFailure",{message:ce(i).message}),variant:"error"})}finally{L(null),xe(),h.refetch()}}},Y=async(r,g)=>{if(y()&&!oe.current){q({endpoint:r,name:g.name}),ue(r);try{const i=await Le.deletePreset(r,g.name);z(r,i.presets??[]),n({title:t("modelManagement.toast.presetDeleteSuccess",{name:g.name}),variant:"success"})}catch(i){n({title:t("modelManagement.toast.presetDeleteFailure",{message:ce(i).message}),variant:"error"})}finally{q(null),xe(),h.refetch()}}},Pe=async r=>{const g=x.find(i=>i.id===r);if(!(!g||g.deletable===!1))try{await ze.delete(r),await b.invalidateQueries({queryKey:Se.customEndpoints.all()}),o(i=>i&&{...i,customEndpoints:(i.customEndpoints??[]).filter(v=>v.id!==r)}),h.refetch(),n({title:t("modelManagement.deleteEndpointSuccess"),variant:"success"})}catch(i){const v=ce(i);n({title:t("modelManagement.deleteEndpointError",{error:v.message}),variant:"error"})}},ke=r=>{m(g=>({...g,[r]:[...g[r]||[],{id:Be(),source:"",target:""}]})),C(g=>({...g,[r]:null}))},ee=async(r,g)=>{if(y()&&!oe.current){A(!0),ue(r);try{if(r==="anthropic"||r==="openai"){const i=r,v=s.endpointRouting?{...s.endpointRouting}:{},P=v[i]??{defaults:s.defaults,modelRoutes:(i==="anthropic"?s.modelRoutes:{})??{}},O={defaults:P.defaults??s.defaults,modelRoutes:P.modelRoutes??{}},F={...s,endpointRouting:{...v,[i]:g?{...O,compatibility:{enabled:!0}}:{...O}}};await Te.saveConfig(F),o(F)}else{const i=[...s.customEndpoints??[]],v=i.findIndex(J=>J.id===r);if(v===-1)throw new Error(t("modelManagement.toast.endpointNotFound"));const P=i[v],O=P.routing??{defaults:s.defaults,modelRoutes:{}};i[v]={...P,routing:g?{...O,compatibility:{enabled:!0}}:{defaults:O.defaults,modelRoutes:O.modelRoutes}};const F={...s,customEndpoints:i};await Te.saveConfig(F),o(F)}n({title:t("modelManagement.toast.compatibilitySaved",{state:t(g?"common.status.enabled":"common.status.disabled")}),variant:"success"}),h.refetch()}catch(i){const v=ce(i);n({title:t("modelManagement.toast.compatibilitySaveFailure",{message:v.message}),variant:"error"})}finally{A(!1),xe()}}},ye=(r,g)=>{m(i=>{const v=i[r]||[];return v.some(P=>P.source.trim()===g.trim())?i:{...i,[r]:[...v,{id:Be(),source:g,target:""}]}}),C(i=>({...i,[r]:null}))},Ee=(r,g,i,v)=>{m(P=>({...P,[r]:(P[r]||[]).map(O=>O.id===g?{...O,[i]:v}:O)})),C(P=>({...P,[r]:null}))},Ce=(r,g)=>{m(i=>({...i,[r]:(i[r]||[]).filter(v=>v.id!==g)})),C(i=>({...i,[r]:null}))},De=(r,g,i)=>{g!==i&&(m(v=>{const P=v[r]||[],O=P.findIndex(J=>J.id===g),F=P.findIndex(J=>J.id===i);return O===-1||F===-1?v:{...v,[r]:Nt(P,O,F)}}),C(v=>({...v,[r]:null})))},Xe=r=>{var i;if(!s)return;const g=(s.customEndpoints??x).find(v=>v.id===r);if(g)m(v=>{var P;return{...v,[r]:Object.entries(((P=g.routing)==null?void 0:P.modelRoutes)??{}).map(([O,F])=>({id:Be(),source:O,target:F}))}});else{const v=s.endpointRouting??{},P=r,O=P==="anthropic"?s.modelRoutes??{}:{},F=((i=v[P])==null?void 0:i.modelRoutes)??O;m(J=>({...J,[r]:Object.entries(F).map(([K,Q])=>({id:Be(),source:K,target:Q}))}))}C(v=>({...v,[r]:null}))},le=et({mutationFn:async r=>(await Te.saveConfig(r.nextConfig),r)}),me=et({mutationFn:async r=>(await ze.update(r.endpoint,{routing:r.routing}),r)});return{endpointTabs:ge,routesByEndpoint:d,setRoutesByEndpoint:m,routeError:l,savingRouteFor:N,presetsByEndpoint:w,presetNameByEndpoint:M,presetErrorByEndpoint:X,savingPresetFor:T,applyingPreset:S,deletingPreset:V,savingCompatibilityPolicy:se,writingEndpoint:ie,presetDiffDialog:ne,setPresetDiffDialog:ae,providerModelOptions:je,isDirtyByEndpoint:Me,defaultsByEndpoint:E,isDefaultsDirtyByEndpoint:We,savingDefaultsFor:U,handleDefaultsChange:Je,handleSaveDefaults:D,handlePresetNameChange:H,handleSavePreset:p,handleApplyPreset:$,handleDeletePreset:Y,handleDeleteEndpoint:Pe,handleAddRoute:ke,handleAddSuggestion:ye,handleRouteChange:Ee,handleRemoveRoute:Ce,handleReorderRules:De,handleResetRoutes:Xe,handleSaveRoutes:async r=>{var v,P,O,F,J;if(!y()||oe.current)return;const g=d[r]||[],i={};for(const K of g){const Q=K.source.trim(),re=K.target.trim();if(!(!Q&&!re)){if(!Q||!re){C(Z=>({...Z,[r]:t("settings.validation.routePair")}));return}if(i[Q]){C(Z=>({...Z,[r]:t("settings.validation.routeDuplicate",{model:Q})}));return}i[Q]=re}}C(K=>({...K,[r]:null})),u(r),ue(r);try{const K=x.find(Q=>Q.id===r);if(K){const Q={...K.routing??{},modelRoutes:i,defaults:((v=K.routing)==null?void 0:v.defaults)||s.defaults};await me.mutateAsync({endpoint:r,routing:Q}),o(re=>{if(!re)return re;const Z=[...re.customEndpoints??[]],G=Z.findIndex(de=>de.id===r);return G===-1?re:(Z[G]={...Z[G],routing:Q},{...re,customEndpoints:Z})}),await b.invalidateQueries({queryKey:Se.customEndpoints.all()})}else{const Q={...s,endpointRouting:{...s.endpointRouting??{},[r]:{defaults:((O=(P=s.endpointRouting)==null?void 0:P[r])==null?void 0:O.defaults)??s.defaults,modelRoutes:i,compatibility:(J=(F=s.endpointRouting)==null?void 0:F[r])==null?void 0:J.compatibility}},modelRoutes:r==="anthropic"?i:s.modelRoutes??{}};await le.mutateAsync({endpoint:r,nextConfig:Q}),o(Q)}m(Q=>{const re=Q[r]??[],Z=new Map(re.map(G=>[G.source.trim(),G.id]));return{...Q,[r]:Object.entries(i).map(([G,de])=>({id:Z.get(G.trim())??Be(),source:G,target:de}))}}),n({title:t("modelManagement.toast.routesSaved"),variant:"success"}),h.refetch()}catch(K){n({title:t("modelManagement.toast.routesSaveFailure",{message:ce(K).message}),variant:"error"})}finally{u(null),xe()}},handleCompatibilityEnabledChange:ee,sanitizeDraftsForProvider:r=>{m(g=>{const i={};for(const[v,P]of Object.entries(g))i[v]=P.filter(O=>!Jt(O.target.trim(),r));return i})}}}function hs(a,t){const{t:n,pushToast:s,config:o,setConfig:h,configQuery:x,customEndpoints:j,ensureConfig:y}=a,{sanitizeDraftsForProvider:b}=t??{},[d,m]=f.useState(""),[l,C]=f.useState("all"),[N,u]=f.useState(!1),[w,k]=f.useState("create"),[M,R]=f.useState(void 0),[X,_]=f.useState(null),[T,c]=f.useState({}),[S,L]=f.useState(!1),[V,q]=f.useState(null),[se,A]=f.useState(!0),[ne,ae]=f.useState({}),[E,I]=f.useState(null),U=(o==null?void 0:o.providers)??[],we=U.length,oe=f.useMemo(()=>U.filter(D=>{var $;if(!(l==="all"||(D.type??"custom")===l))return!1;const H=d.trim().toLowerCase();return H?[D.id,D.label??"",D.baseUrl,D.defaultModel??"",...(($=D.models)==null?void 0:$.map(Y=>Y.id))??[]].join(" ").toLowerCase().includes(H):!0}),[d,l,U]),ie=f.useMemo(()=>{const D=new Map;for(const z of U){if(!z.defaultModel||!z.models)continue;const H=z.models.find(p=>p.id===z.defaultModel);H&&D.set(z.id,Xt(H))}return D},[U]),he=f.useMemo(()=>[{key:"anthropic-beta",value:"claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14",label:n("providers.testDialog.options.beta.label"),description:n("providers.testDialog.options.beta.description")}],[n]),ue=()=>{y()&&(k("create"),R(void 0),u(!0))},xe=D=>{y()&&(k("edit"),R(D),u(!0))},ge=async D=>{if(!o)throw new Error(n("settings.toast.missingConfig"));const z=w==="create"?[...U,D]:U.map(p=>M&&p.id===M.id?{...D,id:M.id}:p),H={...o,providers:z};await Te.saveConfig(H),h(H),x.refetch(),s({title:w==="create"?n("providers.toast.createSuccess",{name:D.label||D.id}):n("providers.toast.updateSuccess",{name:D.label||D.id}),variant:"success"})},fe=(D,z)=>{c(H=>({...H,[D]:z}))},je=async(D,z)=>{_(D.id);try{const H=z&&(z.headers||z.query)?{headers:z.headers&&Object.keys(z.headers).length>0?z.headers:void 0,query:z.query&&z.query.trim().length>0?z.query.trim():void 0}:void 0,p=await Le.testProvider(D.id,H);if(p.ok){fe(D.id,{ok:!0,status:p.status,statusText:p.statusText,durationMs:p.durationMs,testedAt:Date.now()}),s({title:n("providers.toast.testSuccess"),description:n("providers.toast.testSuccessDesc",{status:p.status,duration:p.durationMs?`${p.durationMs} ms`:"—"}),variant:"success"});return}fe(D.id,{ok:!1,status:p.status,statusText:p.statusText,durationMs:p.durationMs,message:`${p.status} ${p.statusText}`,testedAt:Date.now()}),s({title:n("providers.toast.testFailure",{message:`${p.status} ${p.statusText}`}),variant:"error"})}catch(H){const p=ce(H),$=p.status?`${p.status} ${p.message}`:p.message;fe(D.id,{ok:!1,status:p.status,message:$,testedAt:Date.now()}),s({title:n("providers.toast.testFailure",{message:$}),variant:"error"})}finally{_(null)}},Fe=D=>{var Pe,ke;if(!(!!((Pe=D.defaultModel)!=null&&Pe.trim())||!!((ke=D.models)!=null&&ke.some(ee=>ee.id.trim().length>0)))){I(D);return}if(D.type!=="anthropic"){je(D);return}const H=D.extraHeaders??{},p=new Map(he.map(ee=>[ee.key.toLowerCase(),ee])),$={};let Y=!0;for(const ee of he){const ye=Object.entries(H).find(([De])=>De.toLowerCase()===ee.key.toLowerCase());if(!ye)continue;const[Ee,Ce]=ye;String(Ce??"")!==ee.value&&(Y=!1,$[Ee]=String(Ce??""))}for(const[ee,ye]of Object.entries(H))p.has(ee.toLowerCase())||($[ee]=String(ye??""));ae($),A(Y),q(D),L(!0)},Me=()=>{L(!1),q(null),A(!0),ae({})};return{providers:U,providerCount:we,filteredProviders:oe,providerSearch:d,setProviderSearch:m,providerTypeFilter:l,setProviderTypeFilter:C,defaultLabels:ie,drawerOpen:N,setDrawerOpen:u,drawerMode:w,setDrawerMode:k,editingProvider:M,setEditingProvider:R,testingProviderId:X,testResults:T,testDialogOpen:S,testDialogProvider:V,testDialogUsePreset:se,setTestDialogUsePreset:A,testDialogPreservedExtras:ne,noModelDialogProvider:E,setNoModelDialogProvider:I,anthropicTestHeaderOptions:he,handleOpenCreate:ue,handleOpenEdit:xe,handleProviderSubmit:ge,handleDeleteProvider:async D=>{var ee,ye,Ee,Ce,De,Xe;if(!y())return;const z=U.filter(le=>le.id!==D.id),H=le=>{const me={};if(!le)return me;for(const[Ie,Ae]of Object.entries(le)){if(!Ae)continue;const[r]=Ae.split(":");r&&r===D.id||Ae===D.id||(me[Ie]=Ae)}return me},p=(o==null?void 0:o.endpointRouting)??{},$=H(((ee=p.anthropic)==null?void 0:ee.modelRoutes)??(o==null?void 0:o.modelRoutes)??{}),Y=H(((ye=p.openai)==null?void 0:ye.modelRoutes)??{}),Pe=((o==null?void 0:o.customEndpoints)??j).map(le=>{const me=le.routing,Ie=me==null?void 0:me.modelRoutes;return Ie?{...le,routing:{...me,defaults:me.defaults??o.defaults,modelRoutes:H(Ie)}}:le}),ke={...o,providers:z,modelRoutes:$,customEndpoints:Pe,endpointRouting:{anthropic:{defaults:((Ee=p.anthropic)==null?void 0:Ee.defaults)??o.defaults,modelRoutes:$,compatibility:(Ce=p.anthropic)==null?void 0:Ce.compatibility},openai:{defaults:((De=p.openai)==null?void 0:De.defaults)??o.defaults,modelRoutes:Y,compatibility:(Xe=p.openai)==null?void 0:Xe.compatibility}}};try{await Te.saveConfig(ke),h(ke),b==null||b(D.id),(M==null?void 0:M.id)===D.id&&(u(!1),R(void 0),k("create")),s({title:n("providers.toast.deleteSuccess",{name:D.label||D.id}),variant:"success"}),x.refetch()}catch(le){s({title:n("providers.toast.deleteFailure",{message:ce(le).message}),variant:"error"})}},handleTestConnection:je,initiateTestConnection:Fe,closeTestDialog:Me,confirmTestDialog:async()=>{if(!V)return;const D={};if(se)for(const p of he)D[p.key]=p.value;const z=new Map(he.map(p=>[p.key.toLowerCase(),p]));for(const[p,$]of Object.entries(ne))z.get(p.toLowerCase())&&se||(D[p]=$);const H=V;Me(),await je(H,{headers:Object.keys(D).length>0?D:void 0})}}}const xs=["anthropic","openai-auto","openai-chat","openai-responses"];function gs({open:a,endpoint:t,onClose:n,onSuccess:s}){const{t:o}=W(),[h,x]=f.useState({id:"",label:"",paths:[{path:"",protocol:"openai-auto"}],enabled:!0});f.useEffect(()=>{if(a){if(t){const u=t.paths&&t.paths.length>0?t.paths:t.path&&t.protocol?[{path:t.path,protocol:t.protocol}]:[{path:"",protocol:"openai-auto"}];x({id:t.id,label:t.label,paths:u,enabled:t.enabled!==!1});return}x({id:"",label:"",paths:[{path:"",protocol:"openai-auto"}],enabled:!0})}},[t,a]);const j=et({mutationFn:ze.create,invalidateKeys:[Se.customEndpoints.all()],successToast:()=>({title:o("modelManagement.createEndpointSuccess")}),errorToast:u=>({title:o("modelManagement.createEndpointError",{error:u.message})}),onSuccess:async()=>{s(),n()}}),y=et({mutationFn:u=>ze.update(u.id,u.updates),invalidateKeys:[Se.customEndpoints.all()],successToast:()=>({title:o("modelManagement.updateEndpointSuccess")}),errorToast:u=>({title:o("modelManagement.updateEndpointError",{error:u.message})}),onSuccess:async()=>{s(),n()}}),b=()=>{x(u=>({...u,paths:[...u.paths,{path:"",protocol:"anthropic"}]}))},d=u=>{h.paths.length!==1&&x(w=>({...w,paths:w.paths.filter((k,M)=>M!==u)}))},m=(u,w,k)=>{x(M=>{const R=[...M.paths];return R[u]={...R[u],[w]:k},{...M,paths:R}})},l=u=>{if(u==null||u.preventDefault(),!h.id.trim()||!h.label.trim())return;for(const k of h.paths)if(!k.path.trim())return;const w=h.paths.map(k=>({path:k.path.trim(),protocol:k.protocol}));if(t){y.mutate({id:t.id,updates:{label:h.label.trim(),paths:w,enabled:h.enabled}});return}j.mutate({id:h.id.trim(),label:h.label.trim(),paths:w,enabled:h.enabled})},C=j.isPending||y.isPending,N=h.paths.length===0?o("modelManagement.atLeastOnePath"):!h.id.trim()||!h.label.trim()?o("modelManagement.endpointValidationError"):h.paths.some(u=>!u.path.trim())?o("modelManagement.pathValidationError"):null;return e.jsx($e,{open:a,onOpenChange:u=>!u&&n(),children:e.jsxs(He,{className:"max-w-lg",onInteractOutside:u=>u.preventDefault(),children:[e.jsxs(Ue,{children:[e.jsx(qe,{children:o(t?"modelManagement.editEndpoint":"modelManagement.createEndpoint")}),e.jsx(Ve,{className:"truncate font-mono text-xs",children:t?t.id:o("modelManagement.endpointRoutingHint")})]}),e.jsx(_e,{children:e.jsxs("form",{id:"endpoint-form",onSubmit:l,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Ne,{children:[o("modelManagement.endpointId")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(pe,{value:h.id,onChange:u=>x(w=>({...w,id:u.target.value})),placeholder:o("modelManagement.endpointIdPlaceholder"),disabled:!!t,required:!0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o("modelManagement.endpointIdHint")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Ne,{children:[o("modelManagement.endpointLabel")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(pe,{value:h.label,onChange:u=>x(w=>({...w,label:u.target.value})),placeholder:o("modelManagement.endpointLabelPlaceholder"),required:!0})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Ne,{children:[o("modelManagement.endpointPaths")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsxs(B,{type:"button",variant:"ghost",size:"sm",onClick:b,children:[e.jsx(wt,{className:"mr-1 h-3 w-3"}),o("modelManagement.addPath")]})]}),e.jsx("div",{className:"space-y-3",children:h.paths.map((u,w)=>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(pe,{value:u.path,onChange:k=>m(w,"path",k.target.value),placeholder:o("modelManagement.endpointPathPlaceholder"),required:!0}),e.jsxs(tt,{value:u.protocol,onValueChange:k=>m(w,"protocol",k),children:[e.jsx(st,{children:e.jsx(at,{})}),e.jsx(rt,{children:xs.map(k=>e.jsx(Oe,{value:k,children:o(k==="anthropic"?"modelManagement.protocolAnthropic":k==="openai-auto"?"modelManagement.protocolOpenAI":k==="openai-chat"?"modelManagement.protocolOpenAIChat":"modelManagement.protocolOpenAIResponses")},k))})]})]}),h.paths.length>1?e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>d(w),className:"text-destructive",children:e.jsx(ft,{className:"h-4 w-4"})}):null]}),e.jsxs("div",{className:"space-y-1 text-xs text-muted-foreground",children:[w===0?e.jsx("p",{children:o("modelManagement.endpointPathHint")}):null,e.jsx("p",{children:o(`modelManagement.protocolHints.${u.protocol}`)})]})]},`${u.protocol}-${w}`))}),N?e.jsx("p",{className:"text-xs text-destructive",children:N}):null]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(nt,{id:"endpoint-enabled",checked:h.enabled,onCheckedChange:u=>x(w=>({...w,enabled:u}))}),e.jsx(Ne,{htmlFor:"endpoint-enabled",children:o("modelManagement.endpointEnabled")})]}),t?null:e.jsx("div",{className:"rounded-xl bg-accent p-4",children:e.jsx("p",{className:"text-sm text-primary",children:o("modelManagement.endpointRoutingHint")})})]})}),e.jsxs(Ke,{children:[e.jsx(B,{variant:"outline",onClick:n,disabled:C,children:o("common.cancel")}),e.jsx(B,{type:"submit",form:"endpoint-form",disabled:C,children:o(C?"common.saving":t?"common.save":"common.create")})]})]})})}function fs({open:a,provider:t,onClose:n,onEdit:s}){const{t:o}=W();return t?e.jsx($e,{open:a,onOpenChange:h=>!h&&n(),children:e.jsxs(He,{className:"max-w-md",children:[e.jsxs(Ue,{children:[e.jsx(qe,{children:o("providers.noModelDialog.title")}),e.jsx(Ve,{children:o("providers.noModelDialog.subtitle",{name:t.label||t.id})})]}),e.jsxs(_e,{className:"space-y-4",children:[e.jsx("div",{className:"rounded-xl bg-accent p-4 text-sm text-primary",children:o("providers.noModelDialog.description")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:o("providers.noModelDialog.hint")})]}),e.jsxs(Ke,{children:[e.jsx(B,{variant:"outline",onClick:n,children:o("common.actions.close")}),e.jsx(B,{onClick:()=>s(t),children:o("providers.noModelDialog.primary")})]})]})}):null}function bs({dialog:a,currentRoutes:t,onConfirm:n,onClose:s}){const{t:o}=W();if(!a)return null;const{endpoint:h,preset:x}=a,j=x.modelRoutes??{},y={};for(const N of t){const u=N.source.trim(),w=N.target.trim();u&&w&&(y[u]=w)}const b=new Set([...Object.keys(y),...Object.keys(j)]),d=[],m=[],l=[];for(const N of b){const u=N in y,w=N in j;w&&!u?d.push([N,j[N]]):u&&!w?m.push([N,y[N]]):u&&w&&y[N]!==j[N]&&l.push([N,y[N],j[N]])}const C=d.length>0||m.length>0||l.length>0;return e.jsx($e,{open:!0,onOpenChange:N=>!N&&s(),children:e.jsxs(He,{className:"max-w-2xl",children:[e.jsxs(Ue,{children:[e.jsx(qe,{children:o("modelManagement.presets.diffTitle")}),e.jsx(Ve,{children:o("modelManagement.presets.diffDescription",{name:x.name})})]}),e.jsx(_e,{children:C?e.jsxs("div",{className:"max-h-80 space-y-2 rounded-xl bg-secondary/50 p-3 text-sm",children:[d.map(([N,u])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-success-bg px-2 py-1.5 text-success",children:[e.jsx(te,{variant:"outline",className:"border-success/30 text-xs",children:o("modelManagement.presets.diffAdded")}),e.jsx("span",{className:"truncate",children:N}),e.jsx(be,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:u})]},`add-${N}`)),m.map(([N,u])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-error-bg px-2 py-1.5 text-error",children:[e.jsx(te,{variant:"outline",className:"border-error/30 text-xs",children:o("modelManagement.presets.diffRemoved")}),e.jsx("span",{className:"truncate",children:N}),e.jsx(be,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:u})]},`rm-${N}`)),l.map(([N,u,w])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-warning-bg px-2 py-1.5 text-warning",children:[e.jsx(te,{variant:"outline",className:"border-warning/30 text-xs",children:o("modelManagement.presets.diffChanged")}),e.jsx("span",{className:"truncate",children:N}),e.jsx(be,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate line-through opacity-60",children:u}),e.jsx(be,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:w})]},`chg-${N}`))]}):e.jsx("p",{className:"rounded-xl bg-secondary/50 py-8 text-center text-sm text-muted-foreground",children:o("modelManagement.presets.diffEmpty")})}),e.jsxs(Ke,{children:[e.jsx(B,{variant:"outline",onClick:s,children:o("common.cancel")}),e.jsx(B,{onClick:()=>n(h,x),disabled:!C,children:o("modelManagement.presets.diffConfirm")})]})]})})}function vs({open:a,providerId:t,providerName:n,existingModelIds:s,draft:o,onImport:h,onClose:x}){const{t:j}=W(),{pushToast:y}=Ut(),[b,d]=f.useState({phase:"loading"}),[m,l]=f.useState(""),[C,N]=f.useState(new Set),u=f.useRef(o);u.current=o,f.useEffect(()=>{if(!a)return;d({phase:"loading"}),l(""),N(new Set);let c=!1;return Le.probeModels(t,u.current).then(S=>{var L;c||(S.ok&&S.models?d({phase:"ready",models:S.models}):d({phase:"error",message:((L=S.statusText)==null?void 0:L.trim())||j("providers.drawer.probe.failedFallback"),status:S.status>0?S.status:void 0}))}).catch(S=>{c||d({phase:"error",message:ce(S).message})}),()=>{c=!0}},[a,t,j]);const w=f.useMemo(()=>new Set(s),[s]),k=f.useMemo(()=>{if(b.phase!=="ready")return[];const c=m.trim().toLowerCase();return c?b.models.filter(S=>S.id.toLowerCase().includes(c)||(S.label??"").toLowerCase().includes(c)):b.models},[b,m]),M=f.useMemo(()=>k.map(c=>c.id).filter(c=>!w.has(c)),[k,w]),R=c=>{N(S=>{const L=new Set(S);return L.has(c)?L.delete(c):L.add(c),L})},X=()=>{N(c=>new Set([...c,...M]))},_=()=>{N(new Set)},T=()=>{if(b.phase!=="ready"||C.size===0)return;const c=b.models.filter(S=>C.has(S.id));h(c),y({title:j("providers.drawer.probe.importSuccess",{count:c.length}),variant:"success"}),x()};return e.jsx($e,{open:a,onOpenChange:c=>!c&&x(),children:e.jsxs(He,{className:"max-w-2xl",children:[e.jsxs(Ue,{children:[e.jsx(qe,{children:j("providers.drawer.probe.title")}),e.jsx(Ve,{children:j("providers.drawer.probe.subtitle",{name:n})})]}),e.jsxs(_e,{className:"space-y-4",children:[b.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,b.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")}),b.status?e.jsxs(te,{variant:"warning",className:"shrink-0",children:["HTTP ",b.status]}):null]}),e.jsx("p",{className:"break-words text-xs leading-relaxed text-warning",children:b.message}),e.jsx("p",{className:"text-xs text-muted-foreground",children:j("providers.drawer.probe.failedHint")})]}):null,b.phase==="ready"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(pe,{value:m,onChange:c=>l(c.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:b.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(B,{type:"button",variant:"outline",size:"sm",className:"h-auto bg-card px-2 py-1 text-xs",onClick:X,disabled:M.length===0,children:j("providers.drawer.probe.selectAll")}),e.jsx(B,{type:"button",variant:"outline",size:"sm",className:"h-auto bg-card px-2 py-1 text-xs",onClick:_,disabled:C.size===0,children:j("providers.drawer.probe.clearSelection")})]}),e.jsx("span",{className:"text-muted-foreground",children:j("providers.drawer.probe.selectedCount",{count:C.size})})]}),k.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:k.map(c=>{const S=w.has(c.id),L=C.has(c.id);return e.jsxs("label",{className:ve("flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2.5 transition-colors",S?"cursor-not-allowed opacity-60":"cursor-pointer hover:border-primary/20 hover:bg-accent/50",L&&"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:L,disabled:S,onChange:()=>R(c.id)}),e.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-xs",children:c.id}),c.label?e.jsx("span",{className:"shrink-0 truncate text-xs text-muted-foreground",children:c.label}):null,S?e.jsx(te,{variant:"secondary",className:"shrink-0",children:j("providers.drawer.probe.imported")}):null]},c.id)})})]}):null]}),e.jsxs(Ke,{children:[e.jsx(B,{variant:"outline",onClick:x,children:j("common.actions.cancel")}),e.jsx(B,{onClick:T,disabled:b.phase!=="ready"||C.size===0,children:j("providers.drawer.probe.importAction",{count:C.size})})]})]})})}function js({open:a,mode:t,provider:n,existingProviderIds:s,onClose:o,onSubmit:h,testResult:x,testing:j,onTest:y,onDelete:b}){const{t:d}=W(),m=Yt({mode:t,provider:n,existingProviderIds:s}),{form:l,errors:C,advancedOpen:N,providerIdRef:u}=m,[w,k]=f.useState(!1),[M,R]=f.useState(null),[X,_]=f.useState("basics"),[T,c]=f.useState(!1),[S,L]=f.useState(!1),[V,q]=f.useState(null),se=f.useRef(null),A=f.useRef(null);f.useEffect(()=>{a&&(m.resetForm(),R(null),k(!1),_("basics"),c(!1),L(!1),q(null))},[a,n,t,m.resetForm]);const ne=f.useRef(o);ne.current=o,f.useEffect(()=>{if(!a)return;const p=$=>{$.key==="Escape"&&(document.querySelector('[role="dialog"][data-state="open"], [role="listbox"][data-state="open"], [data-radix-popper-content-wrapper]')||ne.current())};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[a]),f.useEffect(()=>{if(a){if(t==="create"&&u.current){u.current.focus();return}A.current&&A.current.focus()}},[a,t]);const ae=t==="create",E=f.useMemo(()=>l.models.filter(p=>p.id.trim().length>0),[l.models]),I=f.useMemo(()=>{var p;return((p=dt.find($=>$.value===l.type))==null?void 0:p.label)??"Custom"},[l.type]),U=l.label.trim()||l.id.trim()||d("providers.drawer.summary.untitled"),we=f.useMemo(()=>[{label:d("providers.drawer.summary.type"),value:I},{label:d("providers.drawer.summary.auth"),value:Zt(l.type,l.authMode,d)},{label:d("providers.drawer.summary.models"),value:E.length.toLocaleString()}],[E.length,l.authMode,l.type,I,d]),oe=async()=>{R(null);const p=m.validateErrors();if(Object.keys(p).length>0){p.baseUrl||p.id||p.extraHeaders?(_("basics"),p.extraHeaders&&m.setAdvancedOpen(!0)):p.models&&_("models");return}k(!0);try{const $=m.serialize();await h($)}catch($){R(d("providers.drawer.toast.saveFailure",{message:ce($).message})),k(!1);return}k(!1),o()};if(!a)return null;const ie=Re.findIndex(p=>p.id===X),he=ie===Re.length-1,ue=l.id.trim(),xe=ue.length>0&&(t==="edit"||!s.includes(ue)),ge=l.baseUrl.trim();let fe=ge.length>0;if(fe)try{new URL(ge)}catch{fe=!1}let je=!l.defaultModel||l.models.some(p=>p.id===l.defaultModel);if(je){const p=new Set;je=!l.models.some($=>{const Y=$.id.trim();return Y.length===0||p.has(Y)?!0:(p.add(Y),!1)})}const Fe={basics:xe&&fe,models:je},Me=Re.map((p,$)=>{let Y;return $===ie?Y="current":$<ie?Y=Fe[p.id]?"complete":"error":Y="upcoming",{id:p.id,label:d(p.labelKey),status:Y}}),We=p=>{_(p)},Je=async()=>{L(!0),q(null);try{const p=await Le.testProvider(l.id.trim()||"draft",{provider:m.serialize()});q({ok:p.ok,status:p.status,statusText:p.statusText,durationMs:p.durationMs,message:p.ok?void 0:p.statusText,testedAt:Date.now()})}catch(p){q({ok:!1,message:ce(p).message,testedAt:Date.now()})}finally{L(!1)}},D=()=>{ie<Re.length-1&&_(Re[ie+1].id)},z=()=>{ie>0&&_(Re[ie-1].id)},H={form:l,errors:C,isCreate:ae,advancedOpen:N,onAdvancedOpenChange:m.setAdvancedOpen,idInputRef:u,onProviderIdChange:m.handleProviderIdChange,onFieldChange:m.handleFieldChange,onTypeChange:m.handleTypeChange,onAuthModeChange:m.handleAuthModeChange,onNonStreamViaStreamChange:m.handleProviderNonStreamViaStreamChange,onUseAbsoluteUrlChange:m.handleUseAbsoluteUrlChange,onStreamUsageChange:m.handleStreamUsageChange,onAddHeader:m.handleAddHeader,onRemoveHeader:m.handleRemoveHeader,onHeaderChange:m.handleHeaderChange,onModelIdChange:m.handleModelIdChange,onModelChange:m.handleModelChange,onAddModel:m.handleAddModel,onRemoveModel:m.handleRemoveModel,onModelNonStreamViaStreamChange:m.handleModelNonStreamViaStreamChange,onSetDefaultModel:m.handleSetDefaultModel,testVerification:t==="edit"?y?{available:!0,testing:j??!1,result:x??null,onTest:y}:void 0:{available:!0,testing:S,result:V,onTest:()=>void Je()},probeModels:{available:l.baseUrl.trim().length>0,onProbe:()=>c(!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:se,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:d(ae?"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:d(ae?"providers.drawer.createTitle":"providers.drawer.editTitle")}),e.jsx("p",{id:"provider-drawer-desc",className:"text-sm text-muted-foreground",children:d("providers.drawer.description")})]})]}),e.jsx(B,{type:"button",ref:A,variant:"outline",onClick:o,className:"bg-card",children:d("common.actions.close")})]}),e.jsx("div",{className:"mt-4 grid gap-3 md:grid-cols-3",children:we.map(p=>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:p.label}),e.jsx("p",{className:"mt-2 text-sm font-semibold text-foreground",children:p.value})]},p.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(es,{steps:Me,current:X,onSelect:We,className:"mb-6"}),X==="basics"?e.jsx(ts,{...H}):null,X==="models"?e.jsx(ss,{...H}):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:d("providers.drawer.formSummary")}),e.jsx("p",{className:"mt-2 text-base font-semibold",children:U}),e.jsx("div",{className:"mt-4 space-y-3 text-sm",children:we.map(p=>e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("span",{className:"text-muted-foreground",children:p.label}),e.jsx("span",{className:"text-right font-medium",children:p.value})]},p.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:d("providers.drawer.sections.checklist")}),e.jsxs("ul",{className:"mt-3 space-y-2 text-sm text-muted-foreground",children:[e.jsx("li",{children:d("providers.drawer.hints.checkUrl")}),e.jsx("li",{children:d("providers.drawer.hints.checkAuth")}),e.jsx("li",{children:d("providers.drawer.hints.checkModels")})]})]}),N&&e.jsxs("div",{className:"rounded-xl bg-accent p-4 text-sm text-foreground",children:[e.jsx("p",{className:"font-medium text-primary",children:d("providers.drawer.hints.advancedTitle")}),e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:d("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:[!ae&&b?e.jsx("button",{type:"button",onClick:b,disabled:w,className:"text-muted-foreground underline-offset-2 hover:text-destructive hover:underline disabled:opacity-50",children:d("providers.actions.delete")}):null,M?e.jsx("span",{className:"text-destructive","aria-live":"polite",children:M}):null]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{type:"button",variant:"outline",onClick:o,disabled:w,className:"bg-card",children:d("common.actions.cancel")}),e.jsx(B,{type:"button",variant:"outline",onClick:z,disabled:w||ie===0,className:"bg-card",children:d("common.actions.previous")}),he?null:e.jsx(B,{type:"button",onClick:D,disabled:w,children:d("common.actions.next")}),e.jsx(B,{type:"button",onClick:oe,disabled:w,children:d(w?"common.actions.saving":"common.actions.save")})]})]})]}),e.jsx(vs,{open:T,providerId:(n==null?void 0:n.id)??(l.id.trim()||"draft"),providerName:(n==null?void 0:n.label)||l.label.trim()||l.id.trim()||d("providers.drawer.summary.untitled"),existingModelIds:l.models.map(p=>p.id.trim()).filter(Boolean),draft:m.serialize(),onImport:m.handleImportModels,onClose:()=>c(!1)})]})}function ys({provider:a,defaultModel:t,modelCount:n,requests24h:s,avgLatencyMs:o,routeCount:h,testResult:x,onTest:j,onEdit:y}){var N;const{t:b}=W(),d=a.label||a.id,m=d.slice(0,1).toUpperCase()||"?",l=((N=dt.find(u=>u.value===(a.type??"custom")))==null?void 0:N.label)??a.type??"custom",C=x?x.ok?"ok":"fail":"untested";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:m}),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:d,children:d}),e.jsx(te,{variant:"outline",className:"shrink-0 rounded-full px-2 py-0 text-[10px] font-normal text-muted-foreground",children:l})]}),e.jsx("code",{className:"mt-0.5 block truncate font-mono text-[10.5px] text-muted-foreground",title:a.baseUrl,children:a.baseUrl})]}),e.jsx(Ns,{state:C})]}),e.jsxs("div",{className:"mt-3 grid grid-cols-3 gap-2",children:[e.jsx(it,{label:b("providers.card.statModels"),value:n>0?String(n):"—"}),e.jsx(it,{label:b("providers.card.statRequests24h"),value:s!=null?s.toLocaleString():"—"}),e.jsx(it,{label:b("providers.card.statAvgLatency"),value:ls(o,b("common.units.ms"),{maximumFractionDigits:0})})]}),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:b("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:b("providers.card.routeCount",{count:h})}),e.jsxs("div",{className:"ml-auto flex shrink-0 gap-1.5",children:[e.jsx(B,{variant:"outline",size:"sm",className:"h-7 px-2.5 text-[11px]",onClick:j,children:b("providers.actions.test")}),e.jsx(B,{variant:"outline",size:"sm",className:"h-7 px-2.5 text-[11px]",onClick:y,children:b("providers.actions.edit")})]})]})]})}function it({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 Ns({state:a}){const{t}=W();return a==="ok"?e.jsx(te,{variant:"success",className:"shrink-0 rounded-full px-1.5 py-0 text-[10px]",children:t("providers.card.health.ok")}):a==="fail"?e.jsx(te,{variant:"destructive",className:"shrink-0 rounded-full px-1.5 py-0 text-[10px]",children:t("providers.card.health.fail")}):e.jsx(te,{variant:"secondary",className:"shrink-0 rounded-full px-1.5 py-0 text-[10px]",children:t("providers.card.health.untested")})}function ws({providersLength:a,filteredProviders:t,testResults:n,providerSearch:s,providerTypeFilter:o,configPending:h,defaultLabels:x,config:j,customEndpoints:y,onTest:b,onEdit:d,onProviderSearchChange:m,onProviderTypeChange:l,onResetFilters:C}){const{t:N}=W(),[u,w]=f.useState("usage"),k=bt(Se.stats.model(1,50),{url:"/api/stats/model",method:"GET",params:{days:1,limit:50}},{retry:!1}),{requestsByProvider:M,latencyByProvider:R}=f.useMemo(()=>{const T=new Map,c=new Map,S=new Map;for(const V of k.data??[]){const q=V.provider;T.set(q,(T.get(q)??0)+V.requests),V.avgLatencyMs>0&&(c.set(q,(c.get(q)??0)+V.avgLatencyMs*V.requests),S.set(q,(S.get(q)??0)+V.requests))}const L=new Map;for(const V of T.keys()){const q=S.get(V)??0;L.set(V,q>0?(c.get(V)??0)/q:null)}return{requestsByProvider:T,latencyByProvider:L}},[k.data]),X=f.useMemo(()=>{const T=new Map;for(const c of t)T.set(c.id,as(j,y,c.id).length);return T},[j,y,t]),_=f.useMemo(()=>{const T=[...t],c=(S,L)=>(S.label||S.id).localeCompare(L.label||L.id);return u==="usage"&&k.isSuccess?T.sort((S,L)=>(M.get(L.id)??0)-(M.get(S.id)??0)||c(S,L)):T.sort(c),T},[t,u,k.isSuccess,M]);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(Qe,{className:"overflow-hidden",children:e.jsx(Ge,{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(pe,{value:s,onChange:T=>m(T.target.value),placeholder:N("providers.filters.searchPlaceholder"),className:"h-9 w-full sm:w-64"}),e.jsxs(tt,{value:o,onValueChange:l,children:[e.jsx(st,{className:"h-9 w-[130px] text-xs",children:e.jsx(at,{})}),e.jsxs(rt,{children:[e.jsx(Oe,{value:"all",children:N("providers.filters.typeAll")}),dt.map(T=>e.jsx(Oe,{value:T.value??"custom",children:T.label},T.value??"custom"))]})]}),e.jsxs(tt,{value:u,onValueChange:T=>w(T),children:[e.jsx(st,{className:"h-9 w-[104px] text-xs","aria-label":N("providers.list.sortLabel"),children:e.jsx(at,{})}),e.jsxs(rt,{children:[e.jsx(Oe,{value:"usage",children:N("providers.list.sortUsage")}),e.jsx(Oe,{value:"name",children:N("providers.list.sortName")})]})]}),e.jsx(te,{variant:"secondary",className:"shrink-0 rounded-full px-2.5 py-1 text-[11px]",children:t.length}),e.jsx(B,{variant:"ghost",size:"sm",onClick:C,disabled:!s.trim()&&o==="all",className:"h-9 shrink-0 rounded-full px-2.5 text-xs",children:N("common.actions.reset")})]})})}),h?e.jsx("div",{className:"flex min-h-[160px] items-center justify-center text-sm text-muted-foreground",children:N("common.loading")}):a===0?e.jsx(lt,{compact:!0,title:N("providers.emptyState"),description:e.jsxs(e.Fragment,{children:[e.jsx("p",{children:N("providers.emptyStateSub")}),e.jsx("p",{className:"mt-1",children:N("workbench.list.emptyHint")})]})}):t.length===0?e.jsx(lt,{compact:!0,title:N("providers.emptyFiltered")}):e.jsx("div",{className:"grid gap-3.5 sm:grid-cols-2 xl:grid-cols-3",children:_.map(T=>{var c;return e.jsx(ys,{provider:T,defaultModel:x.get(T.id),modelCount:((c=T.models)==null?void 0:c.length)??0,requests24h:k.isSuccess?M.get(T.id)??0:null,avgLatencyMs:k.isSuccess?R.get(T.id)??null:null,routeCount:X.get(T.id)??0,testResult:n[T.id]??null,onTest:()=>b(T),onEdit:()=>d(T)},T.id)})})]})}function ks({routing:a,endpoint:t,tabInfo:n,config:s,customEndpoints:o}){var w,k;const{t:h}=W(),x=a.routesByEndpoint[t]||[],j=a.savingRouteFor===t,y=a.savingCompatibilityPolicy,b=a.writingEndpoint===t,d=((w=n==null?void 0:n.protocols)==null?void 0:w.some(M=>M.startsWith("openai")))??t==="openai",m=rs(t,s,o),l=d?(m==null?void 0:m.enabled)??!1:!1,N=((k=n==null?void 0:n.protocols)==null?void 0:k.includes("anthropic"))??t==="anthropic"?vt:jt,u=new Set(x.map(M=>M.source.trim()).filter(Boolean));return e.jsx(Qe,{"data-testid":"endpoint-config-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(Ge,{className:"space-y-3 p-4",children:[e.jsx("h3",{className:"text-[12.5px] font-semibold",children:h("workbench.endpointConfig.title")}),d?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(Ne,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:h("modelManagement.openaiCompatibility.toggleLabel")}),e.jsx("p",{className:"text-[10.5px] text-muted-foreground",children:h(l?"modelManagement.openaiCompatibility.enabledHint":"modelManagement.openaiCompatibility.disabledHint")})]}),e.jsx(nt,{"data-testid":"compatibility-toggle",checked:l,onCheckedChange:M=>void a.handleCompatibilityEnabledChange(t,M),disabled:y||b,"aria-label":h("modelManagement.openaiCompatibility.toggleLabel")})]}):null,e.jsxs("div",{children:[e.jsx("p",{className:"mb-1.5 text-[11px] text-muted-foreground",children:h("settings.routing.suggested")}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:N.map(M=>{const R=u.has(M);return e.jsx("button",{"data-testid":"suggestion-chip",type:"button",onClick:()=>a.handleAddSuggestion(t,M),disabled:j||R,className:ve("h-6 border px-2 text-[10.5px] transition-colors",R?"border-border bg-secondary/40 text-muted-foreground/50":"border-border bg-card hover:border-primary hover:text-primary"),children:M},`${t}-${M}`)})})]})]})})}const gt=6;function Ze({value:a,onChange:t,options:n,disabled:s,placeholder:o,ariaLabel:h}){const{t:x}=W(),j=f.useId(),[y,b]=f.useState(!1),[d,m]=f.useState(""),l=f.useRef(null),C=f.useRef(!1),[N,u]=qt(Vt.modelManagement.recentRouteTargets,[]),w=f.useMemo(()=>{const c=new Map;for(const S of n)c.set(S.value,S);return c},[n]),k=(c,S)=>S?[c.label,c.value,c.providerId??"",c.providerLabel??"",c.modelId??"",c.modelLabel??""].join(" ").toLowerCase().includes(S):!0,M=f.useMemo(()=>{const c=d.trim().toLowerCase(),S=n.filter(A=>k(A,c)),L=N.map(A=>w.get(A)??(c?void 0:{value:A,label:A,kind:"custom"})).filter(A=>!!A).filter(A=>k(A,c)).slice(0,gt),V=[];L.length>0&&V.push({key:"recent",label:x("modelManagement.targetPicker.recent"),options:L});const q=new Map,se=[];for(const A of S){if(A.kind==="custom"||!A.providerId){se.push(A);continue}const ne=`provider:${A.providerId}`,ae=q.get(ne);ae?ae.options.push(A):q.set(ne,{key:ne,label:A.providerLabel??A.providerId,options:[A]})}return V.push(...q.values()),se.length>0&&V.push({key:"custom",label:x("modelManagement.targetPicker.custom"),options:se,muted:!0}),V},[w,n,N,d,x]),R=M.reduce((c,S)=>c+S.options.length,0),X=c=>{t(c),u(S=>[c,...S.filter(L=>L!==c)].slice(0,gt)),m(""),C.current=!0,typeof document<"u"&&document.activeElement instanceof HTMLElement&&document.activeElement.blur(),b(!1),typeof window<"u"?window.requestAnimationFrame(()=>{C.current=!1}):C.current=!1},_=c=>c.kind==="passthrough"?x("modelManagement.targetPicker.passthrough"):c.kind==="custom"?x("modelManagement.targetPicker.customValue"):x("modelManagement.targetPicker.model"),T=c=>c.kind==="passthrough"||c.kind==="custom"?c.label:c.modelLabel??c.label;return e.jsxs(cs,{open:y,onOpenChange:c=>{c&&C.current||(b(c),c&&m(""))},children:[e.jsx(us,{asChild:!0,children:e.jsx(pe,{value:a,onChange:c=>{t(c.target.value),m(c.target.value),y||b(!0)},onFocus:()=>{m(""),b(!0)},onClick:()=>{y||b(!0)},placeholder:o,disabled:s,autoComplete:"off",role:"combobox","aria-label":h,"aria-expanded":y,"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:c=>{var S;c.preventDefault(),(S=l.current)==null||S.focus()},onCloseAutoFocus:c=>{c.preventDefault()},children:[e.jsxs("div",{className:"space-y-2 border-b border-border px-3 py-3",children:[e.jsx(pe,{ref:l,value:d,onChange:c=>m(c.target.value),placeholder:x("modelManagement.targetPicker.searchPlaceholder"),className:"h-9",autoComplete:"off"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:d.trim()?x("modelManagement.targetPicker.matchCount",{count:R}):x("modelManagement.targetPicker.helper")})]}),R===0?e.jsx("div",{className:"px-3 py-4 text-center text-xs text-muted-foreground",children:x("common.noMatches")}):e.jsx("div",{id:j,role:"listbox",className:"min-h-0 flex-1 overflow-y-auto p-1.5",children:M.map(c=>e.jsxs("div",{className:"py-1",children:[e.jsxs("div",{className:ve("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",c.muted&&"opacity-80"),children:[e.jsx("span",{className:"truncate",children:c.label}),e.jsx("span",{children:c.options.length})]}),e.jsx("div",{className:"space-y-1",children:c.options.map(S=>e.jsxs("button",{type:"button",role:"option","aria-selected":S.value===a.trim(),className:ve("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",S.value===a.trim()&&"bg-accent text-accent-foreground"),onMouseDown:L=>{L.preventDefault()},onClick:()=>X(S.value),children:[e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate font-medium",children:T(S)}),e.jsx("span",{className:"block truncate text-xs text-muted-foreground",children:S.value})]}),e.jsxs("span",{className:"flex shrink-0 items-center gap-1",children:[S.isDefault?e.jsx(te,{variant:"secondary",className:"text-[10px]",children:x("modelManagement.targetPicker.default")}):null,e.jsx(te,{variant:S.kind==="passthrough"?"outline":"secondary",className:"text-[10px]",children:_(S)})]})]},`${c.key}-${S.value}`))})]},c.key))})]})]})}function Cs({routing:a,endpoint:t}){const{t:n}=W(),s=a.defaultsByEndpoint[t]??null,o=a.isDefaultsDirtyByEndpoint[t]??!1,h=a.savingDefaultsFor===t,x=a.writingEndpoint===t,j=a.providerModelOptions;return e.jsx(Qe,{"data-testid":"routing-defaults-card",className:"border-primary/40 bg-primary/5 shadow-none",children:e.jsxs(Ge,{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:n("workbench.defaults.title")}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:n("workbench.defaults.cardSubtitle")})]}),e.jsxs(ds,{summary:e.jsx("span",{className:"text-[11px] font-medium text-muted-foreground",children:n("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(Ne,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:n("workbench.defaults.reasoningLabel")}),e.jsx(Ze,{value:(s==null?void 0:s.reasoning)??"",onChange:y=>a.handleDefaultsChange(t,"reasoning",y),options:j,disabled:h,ariaLabel:n("workbench.defaults.reasoningLabel"),placeholder:n("workbench.defaults.targetPlaceholder")})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Ne,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:n("workbench.defaults.backgroundLabel")}),e.jsx(Ze,{value:(s==null?void 0:s.background)??"",onChange:y=>a.handleDefaultsChange(t,"background",y),options:j,disabled:h,ariaLabel:n("workbench.defaults.backgroundLabel"),placeholder:n("workbench.defaults.targetPlaceholder")})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Ne,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:n("workbench.defaults.thresholdLabel")}),e.jsx(pe,{type:"number",min:1,value:(s==null?void 0:s.longContextThreshold)||"",onChange:y=>{const b=Number.parseInt(y.target.value,10);a.handleDefaultsChange(t,"longContextThreshold",Number.isFinite(b)?b:0)},disabled:h,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(be,{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(Ze,{value:(s==null?void 0:s.completion)??"",onChange:y=>a.handleDefaultsChange(t,"completion",y),options:j,disabled:h,ariaLabel:n("workbench.defaults.completionLabel"),placeholder:n("workbench.defaults.targetPlaceholder")})}),e.jsxs(B,{size:"sm","data-testid":"save-defaults",onClick:()=>void a.handleSaveDefaults(t),disabled:h||!o||x,className:"relative",children:[n(h?"common.actions.saving":"workbench.defaults.save"),o?e.jsx("span",{className:"absolute -right-1 -top-1 h-2 w-2 rounded-full bg-warning"}):null]})]})]})})}const Ss={anthropic:"/anthropic",openai:"/openai"};function Ms(a){var t;return(t=a.paths)!=null&&t.length?a.paths[0].path:a.path?a.path:`/${a.id}`}function Ps({tabs:a,customEndpoints:t,routeCounts:n,selectedEndpointId:s,onSelect:o,onCreate:h,onEditEndpoint:x,onDeleteEndpoint:j}){const{t:y}=W(),b=a.map(d=>{const m=t.find(C=>C.id===d.key);if(!m)return{key:d.key,label:d.label,path:Ss[d.key]??`/${d.key}`,protocols:d.protocols??[],enabled:!0};const l=m.paths??(m.path?[{path:m.path,protocol:m.protocol??"anthropic"}]:[]);return{key:d.key,label:m.label||m.id,path:Ms(m),protocols:[...new Set(l.map(C=>C.protocol))],enabled:m.enabled!==!1,custom:m}});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:y("workbench.endpointRail.title")}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:y("workbench.endpointRail.subtitle")})]}),e.jsxs("div",{className:"flex gap-1.5 p-2 lg:flex-col lg:gap-1",children:[b.map(d=>{const m=d.key===s,l=n[d.key]??0,C=!d.enabled;return e.jsxs("div",{"data-testid":"endpoint-row",className:ve("flex shrink-0 items-stretch border transition-colors lg:shrink",m?"border-primary/40 bg-primary/5":"border-border bg-card hover:bg-accent",C?"opacity-60":""),children:[e.jsxs("button",{type:"button",onClick:()=>o(d.key),className:"flex min-w-0 flex-1 items-center gap-2 px-2.5 py-2 text-left",children:[e.jsx("span",{className:ve("h-1.5 w-1.5 shrink-0 rounded-full",m?"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:d.label,children:d.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:d.path}),e.jsx("span",{"aria-hidden":!0,children:"·"}),e.jsx("span",{className:"shrink-0 tabular-nums",children:y("workbench.endpointRail.ruleCount",{count:l})})]})]})]}),d.custom?e.jsxs("div",{className:"flex items-center gap-0.5 pr-1",children:[e.jsx("button",{type:"button",onClick:()=>x(d.custom),className:"flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-foreground",title:y("common.edit"),"aria-label":y("common.edit"),children:e.jsx(kt,{className:"h-3 w-3","aria-hidden":!0})}),d.custom.deletable!==!1?e.jsx("button",{type:"button",onClick:()=>j(d.custom),className:"flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-destructive",title:y("common.delete"),"aria-label":y("common.delete"),children:e.jsx(Ct,{className:"h-3 w-3","aria-hidden":!0})}):null]}):null]},d.key)}),e.jsxs("button",{type:"button","data-testid":"create-endpoint",onClick:h,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:["+ ",y("workbench.endpointRail.add")]})]})]})}function Es({endpointPath:a,defaultTarget:t}){const{t:n}=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:n("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:n("workbench.flow.clientStep")}),e.jsx(be,{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:[n("workbench.flow.endpointStep")," ",e.jsx("span",{className:"font-mono",children:a})]}),e.jsx(be,{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:n("workbench.flow.matchStep")}),e.jsx(be,{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||n("workbench.flow.fallbackNote")})]})]})}function Ds({routing:a,endpoint:t,onRequestDeletePreset:n}){var m,l;const{t:s}=W(),o=a.presetsByEndpoint[t]??[],h=a.presetNameByEndpoint[t]??"",x=a.presetErrorByEndpoint[t],j=a.savingPresetFor===t,y=((m=a.applyingPreset)==null?void 0:m.endpoint)===t?a.applyingPreset.name:null,b=((l=a.deletingPreset)==null?void 0:l.endpoint)===t?a.deletingPreset.name:null,d=a.writingEndpoint===t;return e.jsx(Qe,{"data-testid":"routing-presets-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(Ge,{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(B,{variant:"outline",size:"sm","data-testid":"save-preset",onClick:()=>void a.handleSavePreset(t),disabled:j||d,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(pe,{"data-testid":"preset-name-input",value:h,onChange:C=>a.handlePresetNameChange(t,C.target.value),placeholder:s("modelManagement.presets.namePlaceholder"),disabled:j,className:"h-8 text-xs"}),x?e.jsx("p",{className:"text-xs text-destructive",children:x}):null,o.length===0?e.jsx("p",{className:"py-2 text-center text-[11px] text-muted-foreground",children:s("modelManagement.presets.empty")}):e.jsx(_t,{children:e.jsx("div",{className:"grid grid-cols-1 gap-1.5 sm:grid-cols-2",children:o.map(C=>{const N=y===C.name,u=b===C.name,w=Object.entries(C.modelRoutes??{}),k=w.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(Qt,{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:C.name}),e.jsx(te,{variant:"outline",className:"mt-0.5 text-[10px] font-normal",children:k>0?s("modelManagement.presets.rulesCount",{count:k}):s("modelManagement.presets.noRules")})]})}),k>0?e.jsx(Gt,{side:"bottom",className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1 text-xs",children:[w.slice(0,5).map(([M,R])=>e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"truncate",children:M}),e.jsx(be,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:R})]},M)),k>5?e.jsxs("div",{className:"text-muted-foreground",children:["…+",k-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:C}),disabled:N||u||d,children:s(N?"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:()=>n(t,C),disabled:u||N||d,children:s(u?"modelManagement.presets.deleting":"modelManagement.presets.delete")})]})]},C.name)})})})]})})}function Rs({entry:a,index:t,savingRoute:n,options:s,sourceListId:o,onRouteChange:h,onRemoveRoute:x}){const{t:j}=W(),{attributes:y,listeners:b,setNodeRef:d,setActivatorNodeRef:m,transform:l,transition:C,isDragging:N}=St({id:a.id});return e.jsxs("div",{ref:d,"data-testid":"route-rule-row","data-id":a.id,style:{transform:Pt.Transform.toString(l),transition:C},className:ve("flex items-center gap-2 border border-border bg-card p-2",N&&"z-10 opacity-60 shadow-[var(--surface-shadow-lg)]"),children:[e.jsx("button",{ref:m,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",...y,...b,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(pe,{"data-testid":"route-rule-source",value:a.source,onChange:u=>h(a.id,"source",u.target.value),placeholder:j("settings.routing.sourcePlaceholder"),list:o,disabled:n,className:"h-8 min-w-0 flex-1 text-xs"}),e.jsx(be,{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(Ze,{value:a.target,onChange:u=>h(a.id,"target",u),options:s,disabled:n,ariaLabel:j("workbench.routing.targetLabel"),placeholder:j("settings.routing.targetPlaceholder")})}),e.jsx(B,{variant:"ghost",size:"icon","data-testid":"route-rule-delete",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>x(a.id),disabled:n,"aria-label":j("common.delete"),children:e.jsx(ft,{className:"h-3.5 w-3.5","aria-hidden":!0})})]})}function Ts({routing:a,endpoint:t,tabInfo:n}){var u;const{t:s}=W(),o=a.routesByEndpoint[t]||[],h=a.routeError[t],x=a.savingRouteFor===t,j=a.isDirtyByEndpoint[t]??!1,y=a.writingEndpoint===t,b=a.providerModelOptions,d=`route-source-${t}`,m=Et(ct(It,{activationConstraint:{distance:6}}),ct(Ft,{coordinateGetter:Lt})),l=w=>{const{active:k,over:M}=w;!M||k.id===M.id||a.handleReorderRules(t,String(k.id),String(M.id))},N=((u=n==null?void 0:n.protocols)==null?void 0:u.includes("anthropic"))??t==="anthropic"?vt:jt;return e.jsx(Qe,{"data-testid":"routing-rules-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(Ge,{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(te,{variant:"outline",className:"text-[10.5px] font-normal tabular-nums",children:o.length})]}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:s("workbench.routing.rulesSubtitle")})]}),e.jsx(B,{variant:"outline",size:"sm","data-testid":"add-route",onClick:()=>a.handleAddRoute(t),disabled:x,children:s("settings.routing.add")})]}),h?e.jsx("p",{className:"text-xs text-destructive",children:h}):null,o.length===0?e.jsx(lt,{compact:!0,title:s("workbench.routing.emptyTitle"),description:s("workbench.routing.emptyDescription"),action:e.jsx(B,{size:"sm",onClick:()=>a.handleAddRoute(t),disabled:x,children:s("workbench.routing.addFirst")})}):e.jsx(Dt,{sensors:m,collisionDetection:Rt,onDragEnd:l,children:e.jsx(Tt,{items:o.map(w=>w.id),strategy:Ot,children:e.jsx("div",{className:"flex flex-col gap-1.5",children:o.map((w,k)=>e.jsx(Rs,{entry:w,index:k,savingRoute:x,options:b,sourceListId:d,onRouteChange:(M,R,X)=>a.handleRouteChange(t,M,R,X),onRemoveRoute:M=>a.handleRemoveRoute(t,M)},w.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(B,{variant:"outline",size:"sm","data-testid":"reset-routes",onClick:()=>a.handleResetRoutes(t),disabled:x||!j,children:s("common.actions.reset")}),e.jsxs(B,{size:"sm","data-testid":"save-routes",onClick:()=>void a.handleSaveRoutes(t),disabled:x||y,className:"relative",children:[s(x?"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:d,children:N.map(w=>e.jsx("option",{value:w},`${d}-${w}`))})]})})}const Os={simulateRequest(a){return{url:"/api/routing/simulate",method:"POST",data:a}}},Ls=350;function Fs(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 Is({tabs:a,endpoint:t,onEndpointChange:n}){var M;const{t:s}=W(),o=a.filter(R=>R.key!=="providers"),[h,x]=f.useState(((M=o[0])==null?void 0:M.key)??"anthropic"),j=t??h,y=R=>{t&&n?n(R):x(R)},[b,d]=f.useState(""),[m,l]=f.useState(!1),[C,N]=f.useState("");f.useEffect(()=>{const R=setTimeout(()=>N(b.trim()),Ls);return()=>clearTimeout(R)},[b]);const{data:u,isFetching:w,error:k}=bt(["routing","simulate",j,C,m],Os.simulateRequest({endpoint:j,model:C||void 0,thinking:m}),{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(tt,{value:j,onValueChange:y,children:[e.jsx(st,{className:"h-8 w-[168px]",children:e.jsx(at,{})}),e.jsx(rt,{children:o.map(R=>e.jsx(Oe,{value:R.key,children:R.label},R.key))})]})]}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(nt,{checked:m,onCheckedChange:l,"aria-label":s("workbench.hitSim.thinking")}),s("workbench.hitSim.thinking")]})]}),e.jsx(pe,{value:b,onChange:R=>d(R.target.value),placeholder:s("workbench.hitSim.modelPlaceholder"),className:"h-9 text-xs",spellCheck:!1,autoComplete:"off","aria-label":s("workbench.hitSim.modelPlaceholder")}),e.jsx(As,{result:u,loading:w,errorMessage:(k==null?void 0:k.message)??null,requestedModel:C})]})}function As({result:a,loading:t,errorMessage:n,requestedModel:s}){const{t:o}=W();if(n)return e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o("workbench.hitSim.errorPrefix"),": ",n]});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:o("workbench.hitSim.empty")});const h=Fs(a.reason,o),x=h.tone==="fallback",j=s||o("workbench.hitSim.anyModel");return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:x?"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:x?"text-[11px] font-semibold text-warning":"text-[11px] font-semibold text-success",children:h.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]}),h.detail?e.jsx("div",{className:"mt-1 text-[11px] text-muted-foreground",children:h.detail}):null]}),x?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:o("workbench.hitSim.fallbackHint")}):null]})}function Bs({routing:a,config:t,customEndpoints:n,selectedEndpointId:s,routeCounts:o,onSelectEndpoint:h,onCreateEndpoint:x,onEditEndpoint:j,onDeleteEndpoint:y,onRequestDeletePreset:b}){var N;W();const d=s??((N=a.endpointTabs[0])==null?void 0:N.key)??"anthropic",m=a.endpointTabs.find(u=>u.key===d),l=a.defaultsByEndpoint[d],C=(()=>{var w;if(d==="anthropic")return"/anthropic";if(d==="openai")return"/openai";const u=n.find(k=>k.id===d);return(w=u==null?void 0:u.paths)!=null&&w.length?u.paths[0].path:u!=null&&u.path?u.path:`/${d}`})();return e.jsxs("div",{"data-testid":"routing-workspace",className:"flex flex-col gap-3.5",children:[e.jsx(Es,{endpointPath:C,defaultTarget:(l==null?void 0:l.completion)??null}),e.jsxs("div",{className:"grid items-start gap-3.5 lg:grid-cols-[200px_minmax(0,1fr)_288px]",children:[e.jsx(Ps,{tabs:a.endpointTabs,customEndpoints:n,routeCounts:o,selectedEndpointId:d,onSelect:h,onCreate:x,onEditEndpoint:j,onDeleteEndpoint:y}),e.jsxs("div",{className:"flex flex-col gap-3.5",children:[e.jsx(Cs,{routing:a,endpoint:d}),e.jsx(Ts,{routing:a,endpoint:d,tabInfo:m}),e.jsx(Ds,{routing:a,endpoint:d,onRequestDeletePreset:b})]}),e.jsxs("div",{className:"flex flex-col gap-3.5",children:[e.jsx(Is,{tabs:a.endpointTabs,endpoint:d,onEndpointChange:h}),e.jsx(ks,{routing:a,endpoint:d,tabInfo:m,config:t,customEndpoints:n})]})]})]})}function zs({open:a,provider:t,options:n,usePreset:s,preservedExtras:o,onPresetChange:h,onConfirm:x,onClose:j}){const{t:y}=W();return t?e.jsx($e,{open:a,onOpenChange:b=>!b&&j(),children:e.jsxs(He,{className:"max-w-2xl",onInteractOutside:b=>b.preventDefault(),children:[e.jsxs(Ue,{children:[e.jsx(qe,{children:y("providers.testDialog.title")}),e.jsx(Ve,{children:y("providers.testDialog.subtitle",{name:t.label||t.id})})]}),e.jsxs(_e,{className:"space-y-4",children:[e.jsx("div",{className:"rounded-xl bg-accent p-4 text-sm text-primary",children:y("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(Ne,{htmlFor:"provider-test-preset",children:y("providers.testDialog.presetLabel")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:y("providers.testDialog.presetDescription")})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(nt,{id:"provider-test-preset",checked:s,onCheckedChange:h})})]}),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:y("providers.testDialog.presetPreviewSummary")}),e.jsx("div",{className:"mt-2 space-y-1",children:n.map(b=>e.jsxs("code",{className:"block rounded-lg bg-secondary px-2 py-1 text-xs",children:[b.key,": ",b.value]},b.key))})]})}):e.jsx("p",{className:"text-xs text-muted-foreground",children:y("providers.testDialog.presetDescription")})]}),Object.keys(o).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:y("providers.testDialog.preservedInfo")}),Object.entries(o).map(([b,d])=>e.jsxs("code",{className:"block rounded-lg border border-transparent bg-card px-2 py-1 shadow-[var(--surface-shadow)]",children:[b,": ",d]},b))]})]}),e.jsxs(Ke,{children:[e.jsx(B,{variant:"outline",onClick:j,children:y("providers.testDialog.cancel")}),e.jsx(B,{onClick:()=>void x(),children:y("providers.testDialog.primary")})]})]})}):null}function la(){const{t:a}=W(),t=ns(),n=ps(t),s=hs(t,{sanitizeDraftsForProvider:n.sanitizeDraftsForProvider}),[o,h]=zt(),x=o.get("tab"),j=x==="routing"||x==="endpoints"?"routing":"providers";f.useEffect(()=>{x==="endpoints"&&h(E=>{const I=new URLSearchParams(E);return I.set("tab","routing"),I},{replace:!0})},[x,h]);const[y,b]=f.useState(!1),[d,m]=f.useState(void 0),[l,C]=f.useState(null),[N,u]=f.useState(!1),w=o.get("endpoint"),[k,M]=f.useState(w);f.useEffect(()=>{M(w)},[w]);const R=E=>{h(I=>{const U=new URLSearchParams(I);return U.set("tab","routing"),U.set("endpoint",E),U},{replace:!0})},X=()=>{h(E=>{const I=new URLSearchParams(E);return I.delete("endpoint"),I},{replace:!0})};f.useEffect(()=>{k&&(t.customEndpointsQuery.isPending||n.endpointTabs.some(E=>E.key===k)||X())},[k,n.endpointTabs,t.customEndpointsQuery.isPending]);const _=()=>{m(void 0),b(!0)},T=E=>{m(E),b(!0)},c=E=>{h(I=>{const U=new URLSearchParams(I);return E==="providers"?U.delete("tab"):U.set("tab",E),U},{replace:!0})},S=async()=>{if(l){u(!0);try{l.kind==="provider"?await s.handleDeleteProvider(l.provider):l.kind==="preset"?await n.handleDeletePreset(l.endpoint,l.preset):await n.handleDeleteEndpoint(l.endpoint.id),C(null)}finally{u(!1)}}},L=(l==null?void 0:l.kind)==="provider"?os(t.config,t.customEndpoints,l.provider.id):0,V=(l==null?void 0:l.kind)==="provider"?a("providers.actions.delete"):(l==null?void 0:l.kind)==="preset"?a("modelManagement.presets.delete"):(l==null?void 0:l.kind)==="endpoint"?a("common.delete"):"",q=(l==null?void 0:l.kind)==="provider"?a("providers.confirm.delete",{name:l.provider.label||l.provider.id}):(l==null?void 0:l.kind)==="preset"?a("modelManagement.confirm.deletePreset",{name:l.preset.name}):(l==null?void 0:l.kind)==="endpoint"?a("modelManagement.deleteEndpointConfirm",{label:l.endpoint.label}):"",se=(l==null?void 0:l.kind)==="provider"?l.provider.label||l.provider.id:(l==null?void 0:l.kind)==="preset"?l.preset.name:(l==null?void 0:l.kind)==="endpoint"?l.endpoint.label:"",A=Object.values(n.routesByEndpoint).reduce((E,I)=>E+((I==null?void 0:I.length)??0),0),ne=Object.fromEntries(Object.entries(n.routesByEndpoint).map(([E,I])=>[E,(I==null?void 0:I.length)??0])),ae=[{value:"providers",icon:At,label:a("workbench.viewSwitch.providers"),description:a("workbench.viewSwitch.providersDesc"),count:s.providerCount},{value:"routing",icon:Bt,label:a("workbench.viewSwitch.routing"),description:a("workbench.viewSwitch.routingDesc"),count:A}];return e.jsxs("div",{className:"flex flex-col gap-6",children:[e.jsx(Ht,{actions:j==="providers"?e.jsx(B,{size:"sm",onClick:s.handleOpenCreate,children:a("providers.actions.add")}):e.jsx(B,{size:"sm",onClick:_,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:ae.map(E=>{const I=E.icon,U=j===E.value;return e.jsxs("button",{type:"button",role:"tab","aria-selected":U,onClick:()=>c(E.value),className:ve("motion-surface flex items-center gap-3 rounded-xl border p-4 text-left",U?"border-primary/40 bg-primary/5":"border-border bg-card hover:bg-muted/40"),children:[e.jsx("span",{className:ve("flex h-9 w-9 shrink-0 items-center justify-center rounded-lg",U?"bg-primary/10 text-primary":"bg-secondary text-muted-foreground"),children:e.jsx(I,{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:ve("text-sm font-semibold",U?"text-foreground":"text-muted-foreground"),children:E.label}),e.jsx(te,{variant:U?"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(ws,{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(Bs,{routing:n,config:t.config,customEndpoints:t.customEndpoints,routeCounts:ne,selectedEndpointId:k,onSelectEndpoint:R,onCreateEndpoint:_,onEditEndpoint:T,onDeleteEndpoint:E=>C({kind:"endpoint",endpoint:E}),onRequestDeletePreset:(E,I)=>C({kind:"preset",endpoint:E,preset:I})}),e.jsx(js,{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),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&&C({kind:"provider",provider:s.editingProvider})},onClose:()=>{s.setDrawerOpen(!1),s.setEditingProvider(void 0),s.setDrawerMode("create")},onSubmit:s.handleProviderSubmit}),e.jsx(zs,{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(fs,{open:!!s.noModelDialogProvider,provider:s.noModelDialogProvider,onClose:()=>s.setNoModelDialogProvider(null),onEdit:E=>{s.setNoModelDialogProvider(null),s.handleOpenEdit(E)}}),e.jsx(gs,{open:y,endpoint:d,onClose:()=>{b(!1),m(void 0)},onSuccess:()=>{t.configQuery.refetch()}}),e.jsx(bs,{dialog:n.presetDiffDialog,currentRoutes:n.presetDiffDialog?n.routesByEndpoint[n.presetDiffDialog.endpoint]||[]:[],onConfirm:(E,I)=>{n.setPresetDiffDialog(null),n.handleApplyPreset(E,I)},onClose:()=>n.setPresetDiffDialog(null)}),e.jsx($t,{open:!!l,onOpenChange:E=>{!E&&!N&&C(null)},title:V,description:q,confirmLabel:a(N?"common.actions.loading":"common.delete"),cancelLabel:a("common.actions.cancel"),loading:N,onConfirm:S,children:se?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:se}),(l==null?void 0:l.kind)==="provider"&&L>0?e.jsx("p",{className:"text-xs text-muted-foreground",children:a("providers.confirm.deleteImpact",{count:L})}):null]}):null})]})}export{la as default};