@chenpu17/cc-gw 0.12.0 → 0.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/package.json +7 -7
- package/src/web/dist/assets/About-D2m94wu2.js +1 -0
- package/src/web/dist/assets/ApiKeys-Bt-otGF_.js +1 -0
- package/src/web/dist/assets/{ConfirmDialog-cZsL-k-v.js → ConfirmDialog-CRSbmgE7.js} +1 -1
- package/src/web/dist/assets/Dashboard-81qp43jm.js +1 -0
- package/src/web/dist/assets/DialogShell-DxWKa5oR.js +1 -0
- package/src/web/dist/assets/Events-BQ4Dkqon.js +1 -0
- package/src/web/dist/assets/Help-XaAZ__Kz.js +4 -0
- package/src/web/dist/assets/Login-atwWPGzz.js +1 -0
- package/src/web/dist/assets/Logs-BYFIK_hM.js +1 -0
- package/src/web/dist/assets/PageSection-CC5EhfMe.js +1 -0
- package/src/web/dist/assets/PageState-XybOeENt.js +1 -0
- package/src/web/dist/assets/PageToolbar-CnLp4aWt.js +1 -0
- package/src/web/dist/assets/ProvidersPage-CFCY2xSG.js +1 -0
- package/src/web/dist/assets/RoutingPage-35o5ZSMg.js +1 -0
- package/src/web/dist/assets/Settings-DC1TPeS9.js +1 -0
- package/src/web/dist/assets/Setup-CnQPVK9X.js +2 -0
- package/src/web/dist/assets/TargetCombobox-DkVdA04_.js +1 -0
- package/src/web/dist/assets/apiKeys-CMk2nxB_.js +1 -0
- package/src/web/dist/assets/app-CRxPj2SJ.js +61 -0
- package/src/web/dist/assets/badge-eRkhnmCs.js +1 -0
- package/src/web/dist/assets/chartTheme-Cx-0Jiew.js +1 -0
- package/src/web/dist/assets/{charts-core-DlIzYcw_.js → charts-core-BOHudNiN.js} +1 -1
- package/src/web/dist/assets/{charts-engine-C14rMTiz.js → charts-engine-BhFpDbO0.js} +1 -1
- package/src/web/dist/assets/{charts-react-Bz6GVFr3.js → charts-react-CPWg-GRD.js} +1 -1
- package/src/web/dist/assets/clipboard-DqvcglYs.js +1 -0
- package/src/web/dist/assets/currency-Bx141-XL.js +3 -0
- package/src/web/dist/assets/disclosure-CU-KJc8C.js +1 -0
- package/src/web/dist/assets/{gateway-B_xLF-Rk.js → gateway-DyhqzHSh.js} +1 -1
- package/src/web/dist/assets/{global-CJOj9WGx.js → global-BLUcvOa8.js} +1 -1
- package/src/web/dist/assets/global-BQq8O0Tv.css +1 -0
- package/src/web/dist/assets/{i18n-Dp-o1LhZ.js → i18n-v60Yn7Ls.js} +1 -1
- package/src/web/dist/assets/{label-Da-JMxO2.js → label-CdbE1ezd.js} +1 -1
- package/src/web/dist/assets/{landing-MsSWlQKc.js → landing-BQdbaG8s.js} +4 -4
- package/src/web/dist/assets/modelManagement-DwdbGu0o.js +1 -0
- package/src/web/dist/assets/package-Dmrvm3RO.js +1 -0
- package/src/web/dist/assets/popover-CuM9b3U7.js +1 -0
- package/src/web/dist/assets/{query-DVc6ZTRQ.js → query-CvboQrUT.js} +1 -1
- package/src/web/dist/assets/{radix-B9EIjzyN.js → radix-d0BukFWM.js} +2 -2
- package/src/web/dist/assets/router-CqUBCAsx.js +19 -0
- package/src/web/dist/assets/segmented-control-5mZhY1KZ.js +1 -0
- package/src/web/dist/assets/shared-zfHsnBTk.js +1 -0
- package/src/web/dist/assets/switch-CZn1nypU.js +1 -0
- package/src/web/dist/assets/tabs-CrNMQMmG.js +1 -0
- package/src/web/dist/assets/{types-DYz12j32.js → types-BT3gK5lJ.js} +1 -1
- package/src/web/dist/assets/useAppMutation-B29oVzxS.js +1 -0
- package/src/web/dist/assets/{useEventStream-CQTreYBE.js → useEventStream-DN2DYBVS.js} +1 -1
- package/src/web/dist/assets/useProviderForm-DIuM3Z2u.js +1 -0
- package/src/web/dist/assets/vendor-JUtelXU0.js +445 -0
- package/src/web/dist/index.html +28 -9
- package/src/web/dist/landing.html +7 -7
- package/src/web/dist/assets/About-B4KoKSAM.js +0 -1
- package/src/web/dist/assets/ApiKeys-CwiStTlS.js +0 -1
- package/src/web/dist/assets/Dashboard-khRk8U0-.js +0 -1
- package/src/web/dist/assets/DialogShell-BbpG8sot.js +0 -1
- package/src/web/dist/assets/Events-BGQklKqB.js +0 -1
- package/src/web/dist/assets/Help-B2MDKuj8.js +0 -4
- package/src/web/dist/assets/Login-CrvH8tn2.js +0 -1
- package/src/web/dist/assets/Logs-DoAgVjw3.js +0 -1
- package/src/web/dist/assets/PageSection-Bv6dZZwN.js +0 -1
- package/src/web/dist/assets/PageState-U6DpaNu4.js +0 -1
- package/src/web/dist/assets/PageToolbar-BnDacS2l.js +0 -1
- package/src/web/dist/assets/ProvidersWorkbench-CI7TbMf1.js +0 -1
- package/src/web/dist/assets/Settings-BnqMqPol.js +0 -1
- package/src/web/dist/assets/Setup-deGPdPcE.js +0 -2
- package/src/web/dist/assets/apiKeys-Ol_q3sZL.js +0 -1
- package/src/web/dist/assets/app-BBAnVEPg.js +0 -61
- package/src/web/dist/assets/badge-RZTsODn-.js +0 -1
- package/src/web/dist/assets/card-DhuLMeO9.js +0 -1
- package/src/web/dist/assets/clipboard-BnAnBk_-.js +0 -1
- package/src/web/dist/assets/disclosure-CJdf1-ap.js +0 -1
- package/src/web/dist/assets/global-CWlBZlIY.css +0 -1
- package/src/web/dist/assets/metric-card-B_6litu2.js +0 -1
- package/src/web/dist/assets/package-DHb277_G.js +0 -1
- package/src/web/dist/assets/popover-JpUYyIhi.js +0 -1
- package/src/web/dist/assets/router-CUBM_FND.js +0 -19
- package/src/web/dist/assets/segmented-control-D80bc13p.js +0 -1
- package/src/web/dist/assets/select-BTwqvh0l.js +0 -1
- package/src/web/dist/assets/shared-BIsbTzWd.js +0 -1
- package/src/web/dist/assets/switch-CeKtgMDT.js +0 -1
- package/src/web/dist/assets/table-rPjqxS-f.js +0 -1
- package/src/web/dist/assets/tabs-DYNHHISl.js +0 -1
- package/src/web/dist/assets/useAppMutation-Ds2SX3kE.js +0 -1
- package/src/web/dist/assets/useProviderForm-CtZEenP9.js +0 -1
- package/src/web/dist/assets/utils-HY2ZFw0f.js +0 -3
- package/src/web/dist/assets/vendor-D2wC0h2o.js +0 -409
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as m,j as e,aI as Ge,aJ as Ue,aK as Je,aL as Xe,aM as Ye,aN as Ze,aO as es,aP as ss,aQ as ts,aR as rs,aS as as,aD as ns,aT as is,aU as ls,aV as os,a4 as ds,av as cs,aW as us}from"./vendor-JUtelXU0.js";import{C as de}from"./ConfirmDialog-CRSbmgE7.js";import{P as ms}from"./PageToolbar-CnLp4aWt.js";import{B as Y}from"./badge-eRkhnmCs.js";import{t as ce,b as Te,q as ue,B as k,u as Ke,e as _e,d as ze,C as be,c as je,s as De}from"./app-CRxPj2SJ.js";import{r as ps,m as Ve,a as xs,u as gs,s as hs}from"./modelManagement-DwdbGu0o.js";import{g as Pe}from"./gateway-DyhqzHSh.js";import{L as ee,I as G}from"./label-CdbE1ezd.js";import{D as ye,A as Ne,a as we,b as Ce,c as Se,d as ke,e as Me}from"./DialogShell-DxWKa5oR.js";import{S as Re,a as Ee,b as Oe,c as Ae,e as He,f as $e,d as ne,D as Qe}from"./disclosure-CU-KJc8C.js";import{P as fs,a as vs,d as bs,b as js,p as Ie,u as ys,B as Ns,M as ws,c as Cs}from"./useProviderForm-DIuM3Z2u.js";import{u as q}from"./i18n-v60Yn7Ls.js";import{a as fe}from"./PageState-XybOeENt.js";import{c as te}from"./global-BLUcvOa8.js";import{T as Ss}from"./TargetCombobox-DkVdA04_.js";import{u as We}from"./useAppMutation-B29oVzxS.js";import{c as ks}from"./clipboard-DqvcglYs.js";import{S as Ms}from"./switch-CZn1nypU.js";import{g as Ds}from"./router-CqUBCAsx.js";import"./query-CvboQrUT.js";import"./radix-d0BukFWM.js";import"./popover-CuM9b3U7.js";function Ps(s){const{t,pushToast:i,config:r,setConfig:p,configQuery:n,customEndpoints:j,ensureConfig:x}=s,[h,a]=m.useState(""),[d,b]=m.useState("all"),[c,o]=m.useState(null),[E,O]=m.useState({}),[g,v]=m.useState(!1),[M,A]=m.useState(null),[$,L]=m.useState(!0),[T,l]=m.useState({}),[w,F]=m.useState(null),P=(r==null?void 0:r.providers)??[],D=P.length,y=m.useMemo(()=>P.filter(f=>{var z;if(!(d==="all"||(f.type??"custom")===d))return!1;const S=h.trim().toLowerCase();return S?[f.id,f.label??"",f.baseUrl??"",f.defaultModel??"",...((z=f.models)==null?void 0:z.map(re=>re.id))??[]].join(" ").toLowerCase().includes(S):!0}),[h,d,P]),U=m.useMemo(()=>{const f=new Map;for(const C of P){if(!C.defaultModel||!C.models)continue;const S=C.models.find(N=>N.id===C.defaultModel);S&&f.set(C.id,ps(S))}return f},[P]),B=m.useMemo(()=>[{key:"anthropic-beta",value:"claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14",label:t("providers.testDialog.options.beta.label"),description:t("providers.testDialog.options.beta.description")}],[t]),J=async f=>{if(!r)throw new Error(t("settings.toast.missingConfig"));const C={...r,providers:[...P,f]};await Pe.saveConfig(C),p(C),n.refetch(),i({title:t("providers.toast.createSuccess",{name:f.label||f.id}),variant:"success"})},u=async f=>{if(!r)throw new Error(t("settings.toast.missingConfig"));const C={...r,providers:P.map(S=>S.id===f.id?f:S)};await Pe.saveConfig(C),p(C),n.refetch(),i({title:t("providers.toast.updateSuccess",{name:f.label||f.id}),variant:"success"})},I=(f,C)=>{O(S=>({...S,[f]:C}))},_=async(f,C)=>{o(f.id);try{const S={provider:f};C!=null&&C.headers&&Object.keys(C.headers).length>0&&(S.headers=C.headers),C!=null&&C.query&&C.query.trim().length>0&&(S.query=C.query.trim());const N=await Ve.testProvider(f.id,S);if(N.ok){I(f.id,{ok:!0,status:N.status,statusText:N.statusText,durationMs:N.durationMs,testedAt:Date.now()}),i({title:t("providers.toast.testSuccess"),description:t("providers.toast.testSuccessDesc",{status:N.status,duration:N.durationMs?`${N.durationMs} ms`:"—"}),variant:"success"});return}I(f.id,{ok:!1,status:N.status,statusText:N.statusText,durationMs:N.durationMs,message:`${N.status} ${N.statusText}`,testedAt:Date.now()}),i({title:t("providers.toast.testFailure",{message:`${N.status} ${N.statusText}`}),variant:"error"})}catch(S){const N=ce(S),z=N.status?`${N.status} ${N.message}`:N.message;I(f.id,{ok:!1,status:N.status,message:z,testedAt:Date.now()}),i({title:t("providers.toast.testFailure",{message:z}),variant:"error"})}finally{o(null)}},W=f=>{var me,pe;if(!(!!((me=f.defaultModel)!=null&&me.trim())||!!((pe=f.models)!=null&&pe.some(X=>X.id.trim().length>0)))){F(f);return}if(f.type!=="anthropic"){_(f);return}const S=f.extraHeaders??{},N=new Map(B.map(X=>[X.key.toLowerCase(),X])),z={};let re=!0;for(const X of B){const ae=Object.entries(S).find(([ge])=>ge.toLowerCase()===X.key.toLowerCase());if(!ae)continue;const[xe,ie]=ae;String(ie??"")!==X.value&&(re=!1,z[xe]=String(ie??""))}for(const[X,ae]of Object.entries(S))N.has(X.toLowerCase())||(z[X]=String(ae??""));l(z),L(re),A(f),v(!0)},K=()=>{v(!1),A(null),L(!0),l({})};return{providers:P,providerCount:D,filteredProviders:y,providerSearch:h,setProviderSearch:a,providerTypeFilter:d,setProviderTypeFilter:b,defaultLabels:U,testingProviderId:c,testResults:E,testDialogOpen:g,testDialogProvider:M,testDialogUsePreset:$,setTestDialogUsePreset:L,testDialogPreservedExtras:T,noModelDialogProvider:w,setNoModelDialogProvider:F,anthropicTestHeaderOptions:B,handleCreateProvider:J,handleUpdateProvider:u,handleDeleteProvider:async f=>{var ae,xe,ie,ge,Le,Fe;if(!x())return;const C=P.filter(R=>R.id!==f.id).map(R=>{if(R.type!=="aggregate"||!R.models)return R;const H=R.models.map(Z=>({...Z,members:(Z.members??[]).filter(he=>he.target.split(":")[0]!==f.id)})).filter(Z=>(Z.members??[]).length>0),se=H.some(Z=>Z.id===R.defaultModel)?R.defaultModel:void 0;return{...R,models:H,defaultModel:se}}),S=R=>{const H={};if(!R)return H;for(const[se,Z]of Object.entries(R)){if(!Z)continue;const[he]=Z.split(":");he&&he===f.id||Z===f.id||(H[se]=Z)}return H},N=R=>{if(!R)return R;const H=se=>se&&xs(se,f.id)?null:se;return{...R,completion:H(R.completion),reasoning:H(R.reasoning),background:H(R.background)}},z=(r==null?void 0:r.endpointRouting)??{},re=S(((ae=z.anthropic)==null?void 0:ae.modelRoutes)??(r==null?void 0:r.modelRoutes)??{}),me=S(((xe=z.openai)==null?void 0:xe.modelRoutes)??{}),pe=((r==null?void 0:r.customEndpoints)??j).map(R=>{const H=R.routing;if(!H)return R;const se=H.defaults?N(H.defaults):H.modelRoutes?N(r.defaults):void 0;return{...R,routing:{...H,...se?{defaults:se}:{},...H.modelRoutes?{modelRoutes:S(H.modelRoutes)}:{}}}}),X={...r,providers:C,defaults:N(r.defaults)??r.defaults,modelRoutes:re,customEndpoints:pe,endpointRouting:{anthropic:{defaults:N(((ie=z.anthropic)==null?void 0:ie.defaults)??r.defaults)??r.defaults,modelRoutes:re,compatibility:(ge=z.anthropic)==null?void 0:ge.compatibility},openai:{defaults:N(((Le=z.openai)==null?void 0:Le.defaults)??r.defaults)??r.defaults,modelRoutes:me,compatibility:(Fe=z.openai)==null?void 0:Fe.compatibility}}};try{await Pe.saveConfig(X),p(X),i({title:t("providers.toast.deleteSuccess",{name:f.label||f.id}),variant:"success"}),n.refetch()}catch(R){i({title:t("providers.toast.deleteFailure",{message:ce(R).message}),variant:"error"})}},handleTestConnection:_,initiateTestConnection:W,closeTestDialog:K,confirmTestDialog:async()=>{if(!M)return;const f={};if($)for(const N of B)f[N.key]=N.value;const C=new Map(B.map(N=>[N.key.toLowerCase(),N]));for(const[N,z]of Object.entries(T))C.get(N.toLowerCase())&&$||(f[N]=z);const S=M;K(),await _(S,{headers:Object.keys(f).length>0?f:void 0})}}}const le="preset:",oe="manual:",Ts=[{value:"openai",labelKey:"providers.presets.manualOpenAiCompatible"},{value:"anthropic",labelKey:"providers.presets.manualAnthropicCompatible"},{value:"aggregate",labelKey:"providers.aggregate.typeLabel"}];function Rs({open:s,onOpenChange:t,existingProviderIds:i,onSubmit:r,onCreated:p}){const{t:n,i18n:j}=q(),[x,h]=m.useState(""),[a,d]=m.useState(""),[b,c]=m.useState(""),[o,E]=m.useState(""),[O,g]=m.useState({}),[v,M]=m.useState(null),[A,$]=m.useState(!1),L=Te(ue.providers.presets(),{url:"/api/provider-presets",method:"GET"},{retry:!1,staleTime:1/0,enabled:s}),T=m.useMemo(()=>{var u;return((u=L.data)==null?void 0:u.presets)??[]},[L.data]),l=()=>{h(""),d(""),c(""),E(""),g({}),M(null),$(!1)},w=u=>{u||(t(!1),l())},F=u=>{var I;if(h(u),M(null),u.startsWith(le)){const _=T.find(W=>W.id===u.slice(le.length));if(_){E(_.baseUrl),g(Object.fromEntries(_.endpoints.map(W=>[W.id,W.baseUrl])));return}}if(u.startsWith(oe)){const _=u.slice(oe.length);E(((I=vs[_??"custom"])==null?void 0:I.baseUrl)??"")}g({})},P=u=>{d(u),(!b.trim()||b===a)&&c(u)},D=x.startsWith(le)?T.find(u=>u.id===x.slice(le.length)):void 0,y=x.startsWith(oe)?x.slice(oe.length):void 0,U=y==="aggregate",B=u=>{var I;return(I=j.resolvedLanguage)!=null&&I.startsWith("en")?n(`providers.presets.catalog.${u.id}`,{defaultValue:u.description}):u.description},J=async()=>{const u=a.trim(),I=o.trim();if(!u){M({field:"id",message:n("providers.drawer.errors.idRequired")});return}if(i.includes(u)){M({field:"id",message:n("providers.drawer.errors.idDuplicate")});return}if(!U){if(!I){M({field:"baseUrl",message:n("providers.drawer.errors.baseUrlInvalid")});return}try{new URL(I)}catch{M({field:"baseUrl",message:n("providers.drawer.errors.baseUrlInvalid")});return}for(const V of(D==null?void 0:D.endpoints)??[]){const Q=(O[V.id]??V.baseUrl).trim();try{new URL(Q)}catch{M({field:"endpointUrl",endpointId:V.id,message:n("providers.endpoints.errors.baseUrlInvalid")});return}}}const _=D?D.type:y??"custom",W=bs(_),K={id:u,label:b.trim()||u,type:_,baseUrl:U?void 0:I,authMode:W==="apiKey"&&_!=="anthropic"?void 0:W,...D!=null&&D.balanceAdapter?{balanceAdapter:D.balanceAdapter}:null,...D&&D.endpoints.length>0?{endpoints:D.endpoints.map(V=>({id:V.id,protocol:V.protocol,baseUrl:(O[V.id]??V.baseUrl).trim()}))}:null};D&&D.defaultModels.length>0&&(K.models=D.defaultModels.map(V=>({id:V})),K.defaultModel=D.defaultModels[0]),$(!0);try{await r(K)}catch(V){$(!1),M({field:null,message:n("providers.drawer.toast.saveFailure",{message:ce(V).message})});return}p(u),w(!1)};return e.jsx(ye,{open:s,onOpenChange:w,children:e.jsxs(Ne,{className:"max-w-lg",children:[e.jsxs(we,{children:[e.jsx(Ce,{children:n("providers.presets.title")}),e.jsx(Se,{children:n("providers.presets.description")})]}),e.jsxs(ke,{className:"space-y-4",children:[e.jsxs(ee,{className:"flex flex-col gap-2 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:n("providers.presets.template")}),e.jsxs(Re,{value:x,onValueChange:F,children:[e.jsx(Ee,{"aria-label":n("providers.presets.template"),children:e.jsx(Oe,{placeholder:n("providers.presets.templatePlaceholder")})}),e.jsxs(Ae,{children:[T.length>0?e.jsxs(He,{children:[e.jsx($e,{children:n("providers.presets.groupPresets")}),T.map(u=>e.jsx(ne,{value:`${le}${u.id}`,children:e.jsxs("span",{className:"flex flex-col",children:[e.jsx("span",{children:u.label}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:B(u)})]})},u.id))]}):null,e.jsxs(He,{children:[e.jsx($e,{children:n("providers.presets.groupManual")}),Ts.map(u=>e.jsx(ne,{value:`${oe}${u.value}`,children:n(u.labelKey)},u.value))]})]})]})]}),D?e.jsxs("p",{className:"border border-border bg-secondary/50 px-3 py-2 text-xs leading-relaxed text-muted-foreground",children:[B(D),D.noModelProbe?` ${n("providers.presets.noModelProbeNote")}`:""]}):null,e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs(ee,{className:"flex flex-col gap-2 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:n("providers.drawer.fields.id")}),e.jsx(G,{value:a,onChange:u=>P(u.target.value),placeholder:n("providers.drawer.fields.idPlaceholder"),"aria-invalid":(v==null?void 0:v.field)==="id","aria-describedby":v?"create-provider-error":void 0})]}),e.jsxs(ee,{className:"flex flex-col gap-2 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:n("providers.drawer.fields.label")}),e.jsx(G,{value:b,onChange:u=>c(u.target.value),placeholder:n("providers.drawer.fields.labelPlaceholder")})]})]}),U?e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:n("providers.aggregate.drawer.explainerBody")}):e.jsxs(ee,{className:"flex flex-col gap-2 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:n("providers.drawer.fields.baseUrl")}),e.jsx(G,{value:o,onChange:u=>E(u.target.value),placeholder:n("providers.drawer.fields.baseUrlPlaceholder"),"aria-invalid":(v==null?void 0:v.field)==="baseUrl","aria-describedby":v?"create-provider-error":void 0})]}),D&&D.endpoints.length>0&&!U?e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:n("providers.presets.endpointsHint")}),D.endpoints.map(u=>{var _;const I=((_=fs.find(W=>W.value===u.protocol))==null?void 0:_.label)??u.protocol;return e.jsxs(ee,{className:"flex flex-col gap-2 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:n("providers.presets.endpointBaseUrl",{protocol:I})}),e.jsx(G,{value:O[u.id]??u.baseUrl,onChange:W=>g(K=>({...K,[u.id]:W.target.value})),"aria-invalid":(v==null?void 0:v.field)==="endpointUrl"&&v.endpointId===u.id,"aria-describedby":v?"create-provider-error":void 0})]},u.id)})]}):null,v?e.jsx("p",{id:"create-provider-error",className:"text-xs text-destructive","aria-live":"polite",children:v.message}):null]}),e.jsxs(Me,{children:[e.jsx(k,{variant:"outline",onClick:()=>w(!1),disabled:A,children:n("common.actions.cancel")}),e.jsx(k,{onClick:()=>void J(),disabled:A||!x,children:n(A?"common.actions.saving":"providers.presets.createAction")})]})]})})}function Es({open:s,provider:t,onClose:i,onEdit:r}){const{t:p}=q();return t?e.jsx(ye,{open:s,onOpenChange:n=>!n&&i(),children:e.jsxs(Ne,{className:"max-w-md",children:[e.jsxs(we,{children:[e.jsx(Ce,{children:p("providers.noModelDialog.title")}),e.jsx(Se,{children:p("providers.noModelDialog.subtitle",{name:t.label||t.id})})]}),e.jsxs(ke,{className:"space-y-4",children:[e.jsx("div",{className:"rounded-xl bg-secondary p-4 text-sm text-muted-foreground",children:p("providers.noModelDialog.description")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:p("providers.noModelDialog.hint")})]}),e.jsxs(Me,{children:[e.jsx(k,{variant:"outline",onClick:i,children:p("common.actions.close")}),e.jsx(k,{onClick:()=>r(t),children:p("providers.noModelDialog.primary")})]})]})}):null}function Os(s){const{t}=q(),{form:i,errors:r,onModelIdChange:p,onAddModel:n,onRemoveModel:j,onAddMember:x,onRemoveMember:h,onMemberTargetChange:a,onReorderMembers:d,onModelFailoverChange:b,memberOptions:c}=s;return e.jsx("div",{className:"space-y-8",children:e.jsxs("section",{className:"space-y-4","aria-labelledby":"aggregate-model-fields",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{id:"aggregate-model-fields",className:"text-sm font-semibold",children:t("providers.aggregate.drawer.stepTitle")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t("providers.aggregate.drawer.modelsDescription")})]}),e.jsx(k,{type:"button",variant:"outline",size:"sm",onClick:n,className:"bg-card text-xs",children:t("providers.drawer.fields.addModel")})]}),r.models?e.jsx("p",{className:"text-xs text-destructive",children:r.models}):null,e.jsxs("div",{className:"space-y-4",children:[i.models.map((o,E)=>{var O,g;return e.jsxs("div",{"data-testid":"aggregate-model-card",className:"border border-border bg-card p-3",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(ee,{className:"flex flex-col gap-2 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:t("providers.aggregate.drawer.modelIdLabel")}),e.jsx(G,{value:o.id,onChange:v=>p(E,v.target.value),placeholder:t("providers.aggregate.drawer.modelIdPlaceholder"),className:"font-mono"})]}),e.jsx("p",{className:"self-end text-xs leading-relaxed text-muted-foreground",children:t("providers.aggregate.drawer.modelIdHint")})]}),e.jsx(As,{modelKey:o._key,members:o.members,options:c,error:(O=r.members)==null?void 0:O[o._key],onAddMember:x,onRemoveMember:h,onMemberTargetChange:a,onReorderMembers:d}),e.jsxs(Qe,{summary:t("providers.aggregate.drawer.failoverTitle"),className:"mt-3 bg-secondary/50",summaryClassName:"px-3 py-2 text-xs font-medium",contentClassName:"space-y-4 px-3 py-3",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs(ee,{className:"flex flex-col gap-1.5 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:t("providers.aggregate.drawer.consecutiveFailures")}),e.jsx(G,{type:"number",min:1,value:o.failover.consecutiveFailures,onChange:v=>b(o._key,{consecutiveFailures:v.target.value}),placeholder:t("providers.aggregate.drawer.consecutiveFailuresHint")})]}),e.jsxs(ee,{className:"flex flex-col gap-1.5 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:t("providers.aggregate.drawer.cooldownSeconds")}),e.jsx(G,{type:"number",min:1,max:86400,value:o.failover.cooldownSeconds,onChange:v=>b(o._key,{cooldownSeconds:v.target.value}),placeholder:t("providers.aggregate.drawer.cooldownSecondsHint")})]}),e.jsxs(ee,{className:"flex flex-col gap-1.5 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:t("providers.aggregate.drawer.failureWindowSeconds")}),e.jsx(G,{type:"number",min:1,value:o.failover.failureWindowSeconds,onChange:v=>b(o._key,{failureWindowSeconds:v.target.value}),placeholder:t("providers.aggregate.drawer.failureWindowSecondsHint")})]})]}),e.jsxs(ee,{className:"flex flex-col gap-1.5 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:t("providers.aggregate.drawer.triggerStatusCodes")}),e.jsx(G,{value:o.failover.triggerStatusCodes,onChange:v=>b(o._key,{triggerStatusCodes:v.target.value}),placeholder:t("providers.aggregate.drawer.triggerStatusCodesHint"),className:"font-mono text-xs",spellCheck:!1})]}),(g=r.failover)!=null&&g[o._key]?e.jsx("p",{className:"text-xs text-destructive",children:r.failover[o._key]}):null,e.jsx("p",{className:"text-[11px] text-muted-foreground",children:t("providers.aggregate.drawer.defaultsHint")})]}),e.jsx("div",{className:"mt-3 flex justify-end",children:e.jsx(k,{type:"button",variant:"ghost",size:"sm",className:"h-auto px-2 text-destructive",onClick:()=>j(E),children:t("providers.drawer.fields.removeModel")})})]},o._key)}),i.models.length===0?e.jsxs("div",{className:"rounded-xl border border-warning/30 bg-warning-bg p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-warning",children:t("providers.aggregate.drawer.noModelsTitle")}),e.jsx("p",{className:"mt-1 text-xs leading-relaxed text-warning",children:t("providers.aggregate.drawer.noModelsHint")})]}):null]})]})})}function As({modelKey:s,members:t,options:i,error:r,onAddMember:p,onRemoveMember:n,onMemberTargetChange:j,onReorderMembers:x}){const{t:h}=q(),a=Ge(Ue(Ye,{activationConstraint:{distance:6}}),Ue(Xe,{coordinateGetter:Je})),d=b=>{const{active:c,over:o}=b;!o||c.id===o.id||x(s,String(c.id),String(o.id))};return e.jsxs("div",{className:"mt-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:"text-xs font-medium text-foreground",children:h("providers.aggregate.drawer.membersTitle")}),e.jsx(k,{type:"button",variant:"outline",size:"sm","data-testid":"aggregate-add-member",onClick:()=>p(s),className:"h-7 bg-card px-2.5 text-[11px]",children:h("providers.aggregate.drawer.addMember")})]}),r?e.jsx("p",{className:"text-xs text-destructive",children:r}):null,t.length===0?e.jsx("p",{className:"border border-dashed border-border bg-secondary/40 px-3 py-3 text-xs text-muted-foreground",children:h("providers.aggregate.drawer.memberEmptyHint")}):e.jsx(Ze,{sensors:a,collisionDetection:es,onDragEnd:d,children:e.jsx(ss,{items:t.map(b=>b._key),strategy:ts,children:e.jsx("div",{className:"flex flex-col gap-1.5",children:t.map((b,c)=>e.jsx(Is,{modelKey:s,member:b,index:c,options:i,onRemoveMember:n,onMemberTargetChange:j},b._key))})})}),e.jsx("p",{className:"text-[11px] leading-relaxed text-muted-foreground",children:h("providers.aggregate.drawer.memberHint")})]})}function Is({modelKey:s,member:t,index:i,options:r,onRemoveMember:p,onMemberTargetChange:n}){const{t:j}=q(),{attributes:x,listeners:h,setNodeRef:a,setActivatorNodeRef:d,transform:b,transition:c,isDragging:o}=rs({id:t._key});return e.jsxs("div",{ref:a,"data-testid":"aggregate-member-row",style:{transform:is.Transform.toString(b),transition:c},className:te("flex items-center gap-2 border border-border bg-card p-2",o&&"z-10 opacity-60 shadow-[var(--surface-shadow-lg)]"),children:[e.jsx("button",{ref:d,type:"button","data-testid":"aggregate-member-grip","aria-label":j("workbench.routing.dragHandle"),className:"flex h-7 w-4 shrink-0 cursor-grab touch-none items-center justify-center text-muted-foreground hover:text-foreground active:cursor-grabbing",...x,...h,children:e.jsx(as,{className:"h-4 w-4","aria-hidden":!0})}),e.jsx("span",{className:"w-4 shrink-0 text-center text-[10.5px] tabular-nums text-muted-foreground",children:i+1}),i===0?e.jsx(Y,{variant:"outline",className:"shrink-0 px-1.5 text-[10px] font-normal text-muted-foreground",children:j("providers.aggregate.drawer.primaryBadge")}):null,e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(Ss,{value:t.target,onChange:E=>n(s,t._key,E),options:r,placeholder:j("providers.aggregate.drawer.memberPlaceholder"),ariaLabel:j("providers.aggregate.drawer.memberTarget")})}),e.jsx(k,{variant:"ghost",size:"icon","data-testid":"aggregate-member-delete",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>p(s,t._key),"aria-label":j("common.delete"),children:e.jsx(ns,{className:"h-3.5 w-3.5","aria-hidden":!0})})]})}function Ls({open:s,providerId:t,providerName:i,existingModelIds:r,draft:p,onImport:n,onClose:j}){const{t:x}=q(),{pushToast:h}=Ke(),[a,d]=m.useState({phase:"loading"}),[b,c]=m.useState(""),[o,E]=m.useState(new Set),O=m.useRef(p);O.current=p,m.useEffect(()=>{if(!s)return;d({phase:"loading"}),c(""),E(new Set);let l=!1;return Ve.probeModels(t,O.current).then(w=>{var F;l||(w.ok&&w.models?d({phase:"ready",models:w.models}):d({phase:"error",message:((F=w.statusText)==null?void 0:F.trim())||x("providers.drawer.probe.failedFallback"),status:w.status>0?w.status:void 0}))}).catch(w=>{l||d({phase:"error",message:ce(w).message})}),()=>{l=!0}},[s,t,x]);const g=m.useMemo(()=>new Set(r),[r]),v=m.useMemo(()=>{if(a.phase!=="ready")return[];const l=b.trim().toLowerCase();return l?a.models.filter(w=>w.id.toLowerCase().includes(l)||(w.label??"").toLowerCase().includes(l)):a.models},[a,b]),M=m.useMemo(()=>v.map(l=>l.id).filter(l=>!g.has(l)),[v,g]),A=l=>{E(w=>{const F=new Set(w);return F.has(l)?F.delete(l):F.add(l),F})},$=()=>{E(l=>new Set([...l,...M]))},L=()=>{E(new Set)},T=()=>{if(a.phase!=="ready"||o.size===0)return;const l=a.models.filter(w=>o.has(w.id));n(l),h({title:x("providers.drawer.probe.importSuccess",{count:l.length}),variant:"success"}),j()};return e.jsx(ye,{open:s,onOpenChange:l=>!l&&j(),children:e.jsxs(Ne,{className:"max-w-2xl",children:[e.jsxs(we,{children:[e.jsx(Ce,{children:x("providers.drawer.probe.title")}),e.jsx(Se,{children:x("providers.drawer.probe.subtitle",{name:i})})]}),e.jsxs(ke,{className:"space-y-4",children:[a.phase==="loading"?e.jsx("p",{className:"rounded-xl bg-secondary/50 px-4 py-6 text-center text-sm text-muted-foreground",children:x("providers.drawer.probe.loading")}):null,a.phase==="error"?e.jsxs("div",{className:"space-y-2 rounded-xl border border-warning/30 bg-warning-bg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-semibold text-warning",children:x("providers.drawer.probe.failedTitle")}),a.status?e.jsxs(Y,{variant:"warning",className:"shrink-0",children:["HTTP ",a.status]}):null]}),e.jsx("p",{className:"break-words text-xs leading-relaxed text-warning",children:a.message}),e.jsx("p",{className:"text-xs text-muted-foreground",children:x("providers.drawer.probe.failedHint")})]}):null,a.phase==="ready"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(G,{value:b,onChange:l=>c(l.target.value),placeholder:x("providers.drawer.probe.searchPlaceholder"),className:"h-9"}),e.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:x("providers.drawer.probe.totalCount",{count:a.models.length})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"h-auto bg-card px-2 py-1 text-xs",onClick:$,disabled:M.length===0,children:x("providers.drawer.probe.selectAll")}),e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"h-auto bg-card px-2 py-1 text-xs",onClick:L,disabled:o.size===0,children:x("providers.drawer.probe.clearSelection")})]}),e.jsx("span",{className:"text-muted-foreground",children:x("providers.drawer.probe.selectedCount",{count:o.size})})]}),v.length===0?e.jsx("p",{className:"rounded-xl bg-secondary/50 px-4 py-6 text-center text-sm text-muted-foreground",children:x("providers.drawer.probe.emptyResult")}):e.jsx("div",{className:"grid max-h-80 gap-1 overflow-y-auto",children:v.map(l=>{const w=g.has(l.id),F=o.has(l.id);return e.jsxs("label",{className:te("flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2.5 transition-colors",w?"cursor-not-allowed opacity-60":"cursor-pointer hover:border-foreground/30 hover:bg-accent/50",F&&"border-foreground bg-secondary"),children:[e.jsx("input",{type:"checkbox",className:"h-4 w-4 shrink-0 rounded border-input accent-primary",checked:F,disabled:w,onChange:()=>A(l.id)}),e.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-xs",children:l.id}),l.label?e.jsx("span",{className:"shrink-0 truncate text-xs text-muted-foreground",children:l.label}):null,w?e.jsx(Y,{variant:"secondary",className:"shrink-0",children:x("providers.drawer.probe.imported")}):null]},l.id)})})]}):null]}),e.jsxs(Me,{children:[e.jsx(k,{variant:"outline",onClick:j,children:x("common.actions.cancel")}),e.jsx(k,{onClick:T,disabled:a.phase!=="ready"||o.size===0,children:x("providers.drawer.probe.importAction",{count:o.size})})]})]})})}const qe={refresh(s){return _e(ze.post(`/api/providers/${s}/balance/refresh`))},all(){return _e(ze.get("/api/providers/balances"))}},Fs=[{value:"deepseek",label:"DeepSeek"},{value:"moonshot",label:"Moonshot / Kimi"},{value:"siliconflow",label:"SiliconFlow"},{value:"openrouter",label:"OpenRouter"}];function Us({form:s,errors:t,onKeyChange:i,onAddKey:r,onRemoveKey:p}){const{t:n}=q(),[j,x]=m.useState(new Set),h=a=>{x(d=>{const b=new Set(d);return b.has(a)?b.delete(a):b.add(a),b})};return e.jsxs("section",{className:"space-y-3","aria-labelledby":"provider-keys-fields",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{id:"provider-keys-fields",className:"text-sm font-semibold",children:s.keys.length>0?`${n("providers.keys.title")} (${s.keys.length})`:n("providers.keys.title")}),e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:n("providers.keys.hint")})]}),e.jsx(k,{type:"button",variant:"outline",size:"sm",onClick:r,className:"bg-card text-xs",children:n("providers.keys.add")})]}),s.keys.length>0?e.jsx("div",{className:"divide-y divide-border border border-border",children:s.keys.map((a,d)=>{var c;const b=(c=t.keys)==null?void 0:c[a._key];return e.jsxs("div",{className:"space-y-2 p-3","data-testid":"provider-key-row",children:[e.jsxs("div",{className:"grid gap-2 md:grid-cols-[auto_minmax(0,0.8fr)_minmax(0,0.8fr)_minmax(0,2fr)_auto_auto] md:items-center",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx("input",{type:"radio",name:`provider-active-key-${s.id}`,checked:a.active,onChange:()=>i(d,{active:!0}),"aria-label":n("providers.keys.active"),className:"h-4 w-4 accent-primary"}),n("providers.keys.active")]}),e.jsx(G,{value:a.id,onChange:o=>i(d,{id:o.target.value}),placeholder:n("providers.keys.idPlaceholder"),"aria-label":n("providers.keys.id"),className:"h-8 text-xs","aria-invalid":!!b}),e.jsx(G,{value:a.label,onChange:o=>i(d,{label:o.target.value}),placeholder:n("providers.keys.labelPlaceholder"),"aria-label":n("providers.keys.label"),className:"h-8 text-xs"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx(G,{type:j.has(a._key)?"text":"password",value:a.value,onChange:o=>i(d,{value:o.target.value}),placeholder:n("providers.keys.valuePlaceholder"),"aria-label":n("providers.keys.value"),autoComplete:"off",className:"h-8 font-mono text-xs"}),e.jsx(k,{type:"button",variant:"ghost",size:"sm",className:"h-8 w-8 shrink-0 px-0",onClick:()=>h(a._key),"aria-label":j.has(a._key)?n("providers.keys.hide"):n("providers.keys.reveal"),children:j.has(a._key)?e.jsx(ls,{className:"h-4 w-4","aria-hidden":"true"}):e.jsx(os,{className:"h-4 w-4","aria-hidden":"true"})})]}),e.jsx("span",{className:"text-right",children:e.jsx(k,{type:"button",variant:"ghost",size:"sm",className:"h-auto px-2 text-xs text-destructive",onClick:()=>p(d),children:n("common.delete")})})]}),b?e.jsx("p",{className:"text-xs text-destructive",children:b}):null]},a._key)})}):e.jsx("p",{className:"border border-dashed border-border px-3 py-3 text-xs text-muted-foreground",children:n("providers.keys.empty")})]})}function _s({value:s,onChange:t}){const{t:i}=q();return e.jsxs(Re,{value:s||"none",onValueChange:r=>t(r==="none"?"":r),children:[e.jsx(Ee,{className:"h-8 w-[220px] text-xs","aria-label":i("providers.balance.adapter"),children:e.jsx(Oe,{placeholder:i("providers.balance.adapterNone")})}),e.jsxs(Ae,{children:[e.jsx(ne,{value:"none",children:i("providers.balance.adapterNone")}),Fs.map(r=>e.jsx(ne,{value:r.value,children:r.label},r.value))]})]})}function zs({providerId:s,adapter:t,savedAdapter:i,onAdapterChange:r}){const{t:p}=q(),n=Te(ue.providers.balances(),{url:"/api/providers/balances",method:"GET"},{retry:!1}),j=m.useMemo(()=>{var a;return((a=n.data)==null?void 0:a.balances.find(d=>d.providerId===s))??null},[n.data,s]),x=We({mutationFn:()=>qe.refresh(s),successToast:a=>({title:p("providers.balance.refreshSuccess"),description:a.display??p("providers.balance.displayEmpty")}),errorToast:a=>({title:p("providers.balance.refreshFailure",{message:a.message})}),invalidateKeys:[ue.providers.balances()]}),h=(t||void 0)!==i;return e.jsxs("section",{className:"space-y-3","aria-labelledby":"provider-balance-fields",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{id:"provider-balance-fields",className:"text-sm font-semibold",children:p("providers.balance.title")}),e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:p("providers.balance.hint")})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(_s,{value:t,onChange:r}),e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"bg-card text-xs",onClick:()=>x.mutate(),disabled:!i||h||x.isPending,title:i?h?p("providers.balance.unsavedAdapter"):void 0:p("providers.balance.noAdapter"),children:x.isPending?p("providers.balance.refreshing"):p("providers.balance.refresh")}),h&&i?e.jsx("span",{className:"text-xs text-muted-foreground",children:p("providers.balance.unsavedAdapter")}):null]}),j?e.jsxs("div",{className:"border border-border p-4",children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground",children:p("providers.balance.snapshotLabel")}),e.jsx("p",{className:"mt-2 font-mono text-sm font-semibold tabular-nums",children:j.display??p("providers.balance.displayEmpty")}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:p("providers.balance.fetchedAt",{time:new Date(j.fetchedAt).toLocaleString()})}),e.jsx(Qe,{summary:p("providers.balance.rawTitle"),className:"mt-3 bg-secondary/50",summaryClassName:"px-3 py-2 text-xs font-medium",contentClassName:"px-3 py-3",children:e.jsx("pre",{className:"max-h-64 overflow-auto font-mono text-xs leading-relaxed text-foreground",children:JSON.stringify(j.raw,null,2)})})]}):i?e.jsx("p",{className:"border border-dashed border-border px-3 py-3 text-xs text-muted-foreground",children:p("providers.balance.neverRefreshed")}):null]})}const Hs={anthropic:"Anthropic",openai:"OpenAI Chat","openai-responses":"Responses"};function ve({label:s,children:t}){return e.jsxs("div",{className:"grid gap-1 py-2 sm:grid-cols-[110px_minmax(0,1fr)] sm:gap-3 sm:py-1.5",children:[e.jsx("dt",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:s}),e.jsx("dd",{className:"min-w-0 text-xs text-foreground",children:t})]})}function Be({value:s}){const{t}=q(),{pushToast:i}=Ke(),[r,p]=m.useState(!1),n=async()=>{try{await ks(s),p(!0),window.setTimeout(()=>p(!1),1500)}catch{i({title:t("common.actions.copyFailed"),variant:"error"})}};return e.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[e.jsx("span",{className:"truncate font-mono",children:s}),e.jsx(k,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 shrink-0 px-0 text-muted-foreground hover:text-foreground",onClick:()=>void n(),"aria-label":t("providers.profile.copy"),children:r?e.jsx(ds,{className:"h-3.5 w-3.5 text-foreground","aria-hidden":"true"}):e.jsx(cs,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]})}function $s({provider:s}){var b;const{t}=q(),i=s.type==="aggregate",r=m.useMemo(()=>!s.keys||s.keys.length===0?null:s.keys.find(c=>c.active)??s.keys[0],[s.keys]),p=r?t("providers.profile.namedKeys",{count:((b=s.keys)==null?void 0:b.length)??0,id:r.label||r.id}):s.apiKey?t("providers.profile.singleKey"):t("providers.profile.noKey"),n=m.useMemo(()=>{const c=[];s.nonStreamViaStream&&c.push(t("providers.drawer.fields.nonStreamViaStream")),s.useAbsoluteUrl&&c.push(t("providers.drawer.fields.useAbsoluteUrl")),s.streamUsage&&c.push(t("providers.drawer.fields.streamUsage")),s.rpmLimit&&c.push(`RPM ${s.rpmLimit}`),s.rpmMaxWaitSeconds&&c.push(t("providers.profile.rpmWait",{seconds:s.rpmMaxWaitSeconds}));const o=Object.keys(s.extraHeaders??{}).length;return o>0&&c.push(t("providers.profile.headers",{count:o})),c},[s,t]),j=Te(ue.providers.balances(),{url:"/api/providers/balances",method:"GET"},{retry:!1,enabled:!!s.balanceAdapter}),x=m.useMemo(()=>{var c;return((c=j.data)==null?void 0:c.balances.find(o=>o.providerId===s.id))??null},[j.data,s.id]),h=We({mutationFn:()=>qe.refresh(s.id),successToast:c=>({title:t("providers.balance.refreshSuccess"),description:c.display??t("providers.balance.displayEmpty")}),errorToast:c=>({title:t("providers.balance.refreshFailure",{message:c.message})}),invalidateKeys:[ue.providers.balances()]}),a=s.models??[],d=s.defaultModel;return e.jsxs("div",{className:"space-y-5","data-testid":"provider-profile-view",children:[e.jsxs("section",{"aria-labelledby":"provider-profile-connection",className:"space-y-2",children:[e.jsx("h3",{id:"provider-profile-connection",className:"text-sm font-semibold",children:t("providers.profile.connection")}),i?e.jsx("p",{className:"border border-border bg-secondary/40 px-3 py-2.5 text-xs leading-relaxed text-muted-foreground",children:t("providers.aggregate.drawer.explainerBody")}):e.jsxs("dl",{className:"divide-y divide-border border border-border px-3 py-1.5",children:[e.jsx(ve,{label:t("providers.profile.primaryEndpoint"),children:s.baseUrl?e.jsx(Be,{value:s.baseUrl}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),(s.endpoints??[]).map(c=>e.jsx(ve,{label:t("providers.profile.protocolEndpoint"),children:e.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[e.jsx(Y,{variant:"outline",className:"shrink-0 text-[10px]",children:Hs[c.protocol]}),e.jsx(Be,{value:c.baseUrl})]})},c.id)),e.jsx(ve,{label:t("providers.drawer.sections.auth"),children:e.jsxs("span",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{children:js(s.type,s.authMode??"apiKey",t)}),e.jsx("span",{className:"text-muted-foreground",children:"·"}),e.jsx("span",{className:te(r||s.apiKey?"text-foreground":"text-warning"),children:p})]})}),s.balanceAdapter?e.jsx(ve,{label:t("providers.balance.title"),children:e.jsxs("span",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{children:s.balanceAdapter}),x!=null&&x.display?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"·"}),e.jsx("span",{className:"font-medium",children:x.display})]}):null,e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"h-6 bg-card px-2 text-[11px]",onClick:()=>h.mutate(),disabled:h.isPending,children:h.isPending?t("common.loading"):t("providers.balance.refresh")})]})}):null]}),n.length>0?e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:t("providers.profile.advanced")}),n.map(c=>e.jsx(Y,{variant:"secondary",className:"text-[10px] font-normal",children:c},c))]}):null]}),e.jsxs("section",{"aria-labelledby":"provider-profile-models",className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("h3",{id:"provider-profile-models",className:"text-sm font-semibold",children:a.length>0?`${t("providers.drawer.fields.models")} (${a.length})`:t("providers.drawer.fields.models")}),i?null:e.jsx("span",{className:"text-[11px] text-muted-foreground",children:t("providers.profile.defaultIs",{model:d??t("providers.card.noDefault")})})]}),a.length===0?e.jsx("p",{className:"border border-dashed border-border px-3 py-4 text-xs text-muted-foreground",children:t("providers.profile.noModelsHint")}):i?e.jsx("ul",{className:"divide-y divide-border border border-border",children:a.map(c=>e.jsxs("li",{className:"px-3 py-2",children:[e.jsx("p",{className:"font-mono text-xs",children:c.id}),c.members&&c.members.length>0?e.jsx("p",{className:"mt-0.5 truncate font-mono text-[11px] text-muted-foreground",title:c.members.map(o=>o.target).join(" → "),children:c.members.map(o=>o.target).join(" → ")}):null]},c.id))}):e.jsx("div",{className:"grid gap-1.5 sm:grid-cols-2 lg:grid-cols-3",children:a.map(c=>{const o=c.id===d;return e.jsxs("div",{className:te("flex min-w-0 items-center gap-2 border px-2.5 py-1.5",o?"border-foreground/60 bg-secondary/60":"border-border bg-secondary/30"),title:c.label?`${c.label} (${c.id})`:c.id,children:[e.jsx("span",{className:te("h-1.5 w-1.5 shrink-0 rounded-full",o?"bg-foreground":"bg-border"),"aria-hidden":"true"}),e.jsx("span",{className:"truncate font-mono text-xs",children:c.id}),o?e.jsx("span",{className:"ml-auto shrink-0 text-[10px] font-medium text-foreground",children:t("providers.profile.defaultTag")}):null]},c.id)})})]}),!i&&s.type&&s.type!=="openai"&&s.type!=="anthropic"?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:t("providers.profile.typeFootnote",{type:Ie(s.type,t)})}):null]})}function Bs({provider:s,providers:t,onSubmit:i}){const r=ys({mode:"edit",provider:s,existingProviderIds:[],providers:t}),[p,n]=m.useState(!1),[j,x]=m.useState(null),h=m.useRef(null);h.current===null&&(h.current=JSON.stringify(r.form));const a=JSON.stringify(r.form)!==h.current,d=m.useRef(s);return d.current!==s&&(d.current=s,a||(r.resetForm(),h.current=null)),{providerForm:r,dirty:a,saving:p,saveError:j,save:async()=>{if(!r.validate())return!1;n(!0),x(null);try{const o=r.serialize();return await i(o),h.current=JSON.stringify(r.form),!0}catch(o){return x(ce(o).message),!1}finally{n(!1)}},discard:()=>{r.resetForm(),h.current=null,x(null)}}}const Ks={anthropic:"Anthropic",openai:"OpenAI Chat","openai-responses":"Responses"};function Vs({provider:s,allProviders:t,testResult:i,testing:r,onTest:p,onRequestDelete:n,onSubmit:j,onDirtyChange:x,startInEdit:h=!1}){const{t:a}=q(),[d,b]=m.useState(!1),[c,o]=m.useState(h?"edit":"view"),[E,O]=m.useState(!1),{providerForm:g,dirty:v,saving:M,saveError:A,save:$,discard:L}=Bs({provider:s,providers:t,onSubmit:j}),{form:T,errors:l,advancedOpen:w,providerIdRef:F}=g,P=T.type==="aggregate";m.useEffect(()=>{h&&o("edit")},[h]);const D=async()=>{await $()&&o("view")},y=()=>{L(),o("view")},U=()=>{if(v){O(!0);return}o("view")};m.useEffect(()=>(x==null||x(v),()=>x==null?void 0:x(!1)),[v,x]);const B=m.useMemo(()=>{var V;const K=[];for(const Q of t){if(Q.type==="aggregate")continue;const f=Q.label&&Q.label!==Q.id?`${Q.label} (${Q.id})`:Q.id,C=(V=Q.models)!=null&&V.length?Q.models:Q.defaultModel?[{id:Q.defaultModel}]:[];for(const S of C)K.push({value:`${Q.id}:${S.id}`,label:`${f} · ${S.label??S.id}`,providerId:Q.id,providerLabel:f,modelId:S.id,modelLabel:S.label??S.id,kind:"model"})}return K},[t]),J={form:T,errors:l,isCreate:!1,advancedOpen:w,onAdvancedOpenChange:g.setAdvancedOpen,idInputRef:F,onProviderIdChange:g.handleProviderIdChange,onFieldChange:g.handleFieldChange,onTypeChange:g.handleTypeChange,onAuthModeChange:g.handleAuthModeChange,onNonStreamViaStreamChange:g.handleProviderNonStreamViaStreamChange,onUseAbsoluteUrlChange:g.handleUseAbsoluteUrlChange,onStreamUsageChange:g.handleStreamUsageChange,onAddHeader:g.handleAddHeader,onRemoveHeader:g.handleRemoveHeader,onHeaderChange:g.handleHeaderChange,onModelIdChange:g.handleModelIdChange,onModelChange:g.handleModelChange,onAddModel:g.handleAddModel,onRemoveModel:g.handleRemoveModel,onModelNonStreamViaStreamChange:g.handleModelNonStreamViaStreamChange,onSetDefaultModel:g.handleSetDefaultModel,onEndpointChange:g.handleEndpointChange,onAddEndpoint:g.handleAddEndpoint,onRemoveEndpoint:g.handleRemoveEndpoint,memberOptions:B,onAddMember:g.handleAddMember,onRemoveMember:g.handleRemoveMember,onMemberTargetChange:g.handleMemberTargetChange,onReorderMembers:g.handleReorderMembers,onModelFailoverChange:g.handleModelFailoverChange,testVerification:P?void 0:{available:!0,testing:r,result:i,onTest:()=>p(g.serialize())},probeModels:P?void 0:{available:T.baseUrl.trim().length>0,onProbe:()=>b(!0)}},u=c==="edit",I=u?T.type:s.type,_=u?T.endpoints:s.endpoints??[],W=u?T.models.length:(s.models??[]).length;return e.jsxs(be,{className:"overflow-hidden","data-testid":"provider-detail-panel",children:[e.jsxs("header",{className:"flex flex-wrap items-start justify-between gap-3 border-b border-border bg-secondary/50 px-5 py-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h2",{className:"truncate text-base font-semibold tracking-[-0.02em]",children:s.label||s.id}),i?i.ok?e.jsx(Y,{variant:"success",className:"shrink-0 text-[10px]",children:i.durationMs!==void 0?`${a("providers.masterDetail.testOkShort")} · ${i.durationMs}ms`:a("providers.masterDetail.testOkShort")}):e.jsx(Y,{variant:"destructive",className:"shrink-0 text-[10px]",title:i.message??void 0,children:a("providers.masterDetail.testFailedShort")}):null,u?e.jsx(Y,{variant:"outline",className:"shrink-0 text-[10px] text-muted-foreground",children:a("providers.profile.editingTag")}):null]}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5",children:[e.jsx(Y,{variant:"secondary",className:"text-[10px]",children:Ie(I,a)}),I==="aggregate"?null:_.map(K=>e.jsxs(Y,{variant:"outline",className:"text-[10px]",children:["+ ",Ks[K.protocol]]},K.id)),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:a("providers.masterDetail.modelsMeta",{count:W})})]}),e.jsx("p",{className:"mt-0.5 font-mono text-xs text-muted-foreground",children:s.id})]}),e.jsxs("div",{className:"flex shrink-0 gap-2",children:[P?null:e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"bg-card text-xs",onClick:()=>p(g.serialize()),disabled:r,children:a(r?"common.actions.testingConnection":"providers.actions.test")}),u?e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"bg-card text-xs",onClick:U,disabled:M,children:a("providers.profile.cancelEdit")}):e.jsx(k,{type:"button",variant:"outline",size:"sm","data-testid":"provider-edit",onClick:()=>o("edit"),children:a("providers.profile.edit")}),e.jsx(k,{type:"button",variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive",onClick:()=>n(s),disabled:M,children:a("providers.actions.delete")})]})]}),e.jsx(je,{className:"p-5",children:u?e.jsxs("div",{className:"space-y-5",children:[e.jsx(Ns,{...J}),P?null:e.jsxs(e.Fragment,{children:[e.jsx(Us,{form:T,errors:l,onKeyChange:g.handleKeyChange,onAddKey:g.handleAddKey,onRemoveKey:g.handleRemoveKey}),e.jsx(zs,{providerId:s.id,adapter:T.balanceAdapter,savedAdapter:s.balanceAdapter,onAdapterChange:g.handleBalanceAdapterChange})]}),P?e.jsx(Os,{...J}):e.jsx(ws,{...J})]}):e.jsx($s,{provider:s})}),u&&(v||A)?e.jsxs("footer",{className:"sticky bottom-0 flex flex-wrap items-center justify-between gap-3 border-t border-border bg-card px-5 py-3",children:[e.jsx("div",{className:"min-w-0 text-xs",children:e.jsx("span",{className:te("font-medium",A?"text-destructive":"text-foreground"),"aria-live":"polite",children:A?a("providers.drawer.toast.saveFailure",{message:A}):a("providers.masterDetail.dirtyHint")})}),e.jsxs("div",{className:"flex shrink-0 gap-2",children:[e.jsx(k,{type:"button",variant:"outline",size:"sm",className:"bg-card text-xs",onClick:y,disabled:M,children:a("providers.masterDetail.discard")}),e.jsx(k,{type:"button",variant:"outline",size:"sm","data-testid":"provider-save",onClick:()=>void D(),disabled:M,children:a(M?"common.actions.saving":"providers.masterDetail.save")})]})]}):null,e.jsx(de,{open:E,onOpenChange:O,title:a("providers.masterDetail.unsavedTitle"),description:a("providers.masterDetail.unsavedBody"),confirmLabel:a("providers.masterDetail.unsavedConfirm"),cancelLabel:a("common.actions.cancel"),onConfirm:()=>{L(),o("view"),O(!1)}}),e.jsx(Ls,{open:d,providerId:s.id,providerName:s.label||s.id,existingModelIds:T.models.map(K=>K.id.trim()).filter(Boolean),draft:g.serialize(),onImport:g.handleImportModels,onClose:()=>b(!1)})]})}function Qs({providers:s,configPending:t,configError:i,onRetryConfig:r,selectedProviderId:p,onSelectProvider:n,onTest:j,onRequestDelete:x,onDirtyChange:h,autoEditProviderId:a}){const{t:d}=q(),{filteredProviders:b,providerSearch:c,setProviderSearch:o,providerTypeFilter:E,setProviderTypeFilter:O}=s,g=s.providers.length,[v,M]=m.useState(!1),[A,$]=m.useState(null),L=m.useCallback(y=>{M(y),h==null||h(y)},[h]),[T,l]=m.useState(!1),w=m.useRef(!0);m.useEffect(()=>{if(w.current){w.current=!1;return}l(!!p)},[p]),m.useEffect(()=>{if(!v)return;const y=U=>{U.preventDefault(),U.returnValue=""};return window.addEventListener("beforeunload",y),()=>window.removeEventListener("beforeunload",y)},[v]);const F=y=>{if(v&&y!==p){$(y);return}n(y),l(!0)},P=s.providers.find(y=>y.id===p)??null,D=y=>{var J,u;const U=[],B=((J=y.models)==null?void 0:J.length)??0;if(U.push(d("providers.masterDetail.modelsMeta",{count:B})),y.type!=="aggregate"){const I=((u=y.keys)==null?void 0:u.length)??0;U.push(I>0?d("providers.masterDetail.keysMeta",{count:I}):d("providers.masterDetail.noKeysMeta"))}return U.join(" · ")};return e.jsx("div",{className:"grid gap-4 lg:grid-cols-[300px_minmax(0,1fr)]",children:i?e.jsx(fe,{className:"lg:col-span-2",tone:"danger",title:d("common.status.error"),description:i,action:r?e.jsx(k,{variant:"outline",onClick:r,children:d("common.actions.refresh")}):void 0}):e.jsxs(e.Fragment,{children:[e.jsx(be,{className:te("h-fit overflow-hidden lg:sticky lg:top-4",T&&P?"hidden lg:block":""),children:e.jsxs(je,{className:"p-0",children:[e.jsxs("div",{className:"space-y-2 border-b border-border bg-secondary/50 px-3 py-3",children:[e.jsx(G,{value:c,onChange:y=>o(y.target.value),placeholder:d("providers.filters.searchPlaceholder"),className:"h-9"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Re,{value:E,onValueChange:O,children:[e.jsx(Ee,{className:"h-9 flex-1 text-xs","aria-label":d("providers.table.type"),children:e.jsx(Oe,{})}),e.jsxs(Ae,{children:[e.jsx(ne,{value:"all",children:d("providers.filters.typeAll")}),Cs.map(y=>e.jsx(ne,{value:y.value??"custom",children:y.label},y.value??"custom"))]})]}),e.jsx(Y,{variant:"secondary",className:"shrink-0 px-2.5 py-1 text-[11px]",children:d("providers.groupCount",{count:b.length})})]})]}),t?e.jsx("div",{className:"flex min-h-[160px] items-center justify-center text-sm text-muted-foreground",children:d("common.loading")}):g===0?e.jsx("div",{className:"p-4",children:e.jsx(fe,{compact:!0,title:d("providers.emptyState"),description:e.jsxs(e.Fragment,{children:[e.jsx("p",{children:d("providers.emptyStateSub")}),e.jsx("p",{className:"mt-1",children:d("workbench.list.emptyHint")})]})})}):b.length===0?e.jsx("div",{className:"p-4",children:e.jsx(fe,{compact:!0,title:d("providers.emptyFiltered")})}):e.jsx("ul",{className:"max-h-[60vh] overflow-y-auto p-2 lg:max-h-[calc(100vh-320px)]",children:b.map(y=>{const U=y.id===p,B=s.testResults[y.id]??null,J=B!==null&&!B.ok,u=J?B.message?`${d("providers.masterDetail.testFailedShort")}: ${B.message}`:d("providers.masterDetail.testFailedShort"):void 0;return e.jsx("li",{children:e.jsxs("button",{type:"button","data-testid":"provider-rail-row",onClick:()=>F(y.id),"aria-current":U?"true":void 0,className:te("motion-surface w-full border border-transparent px-3 py-2.5 text-left",U?"border-foreground bg-secondary":"hover:bg-muted/40"),children:[e.jsxs("span",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-1.5 text-sm font-medium",children:[J?e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-destructive",title:u,"aria-label":d("providers.masterDetail.testFailedShort")}):null,e.jsx("span",{className:"truncate",children:y.label||y.id})]}),e.jsx(Y,{variant:U?"default":"secondary",className:"shrink-0 text-[10px]",children:Ie(y.type,d)})]}),e.jsxs("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",children:[y.id," · ",D(y)]})]})},y.id)})})]})}),e.jsxs("div",{className:te("min-w-0",T?"block":"hidden lg:block"),children:[P?e.jsxs(k,{type:"button",variant:"ghost",size:"sm",className:"mb-2 lg:hidden",onClick:()=>l(!1),children:[e.jsx(us,{className:"mr-1.5 h-4 w-4","aria-hidden":"true"}),d("providers.masterDetail.backToList")]}):null,t?e.jsx(be,{children:e.jsx(je,{className:"flex min-h-[240px] items-center justify-center text-sm text-muted-foreground",children:d("common.loading")})}):P?e.jsx(Vs,{provider:P,allProviders:s.providers,testResult:s.testResults[P.id]??null,testing:s.testingProviderId===P.id,onTest:j,onRequestDelete:x,onSubmit:s.handleUpdateProvider,onDirtyChange:L,startInEdit:a===P.id},P.id):e.jsx(be,{children:e.jsx(je,{className:"p-0",children:e.jsx(fe,{title:d("providers.masterDetail.emptyDetailTitle"),description:d("providers.masterDetail.emptyDetailHint")})})})]}),e.jsx(de,{open:!!A,onOpenChange:y=>{y||$(null)},title:d("providers.masterDetail.unsavedTitle"),description:d("providers.masterDetail.unsavedBody"),confirmLabel:d("providers.masterDetail.unsavedConfirm"),cancelLabel:d("common.actions.cancel"),onConfirm:()=>{A&&(n(A),l(!0)),$(null)}})]})})}function Ws({open:s,provider:t,options:i,usePreset:r,preservedExtras:p,onPresetChange:n,onConfirm:j,onClose:x}){const{t:h}=q();return t?e.jsx(ye,{open:s,onOpenChange:a=>!a&&x(),children:e.jsxs(Ne,{className:"max-w-2xl",onInteractOutside:a=>a.preventDefault(),children:[e.jsxs(we,{children:[e.jsx(Ce,{children:h("providers.testDialog.title")}),e.jsx(Se,{children:h("providers.testDialog.subtitle",{name:t.label||t.id})})]}),e.jsxs(ke,{className:"space-y-4",children:[e.jsx("div",{className:"rounded-xl bg-secondary p-4 text-sm text-muted-foreground",children:h("providers.testDialog.description")}),e.jsxs("div",{className:"space-y-4 rounded-xl bg-secondary/50 p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"provider-test-preset",children:h("providers.testDialog.presetLabel")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:h("providers.testDialog.presetDescription")})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(Ms,{id:"provider-test-preset",checked:r,onCheckedChange:n})})]}),r?e.jsx("div",{className:"space-y-2",children:e.jsxs("details",{className:"border border-border bg-card p-2 text-xs",children:[e.jsx("summary",{className:"cursor-pointer text-foreground underline decoration-muted-foreground/40 underline-offset-2 hover:decoration-foreground",children:h("providers.testDialog.presetPreviewSummary")}),e.jsx("div",{className:"mt-2 space-y-1",children:i.map(a=>e.jsxs("code",{className:"block rounded-lg bg-secondary px-2 py-1 text-xs",children:[a.key,": ",a.value]},a.key))})]})}):e.jsx("p",{className:"text-xs text-muted-foreground",children:h("providers.testDialog.presetDescription")})]}),Object.keys(p).length>0&&e.jsxs("div",{className:"space-y-2 rounded-xl bg-secondary/50 p-4 text-xs",children:[e.jsx("p",{className:"font-medium",children:h("providers.testDialog.preservedInfo")}),Object.entries(p).map(([a,d])=>e.jsxs("code",{className:"block border border-border bg-card px-2 py-1",children:[a,": ",d]},a))]})]}),e.jsxs(Me,{children:[e.jsx(k,{variant:"outline",onClick:x,children:h("providers.testDialog.cancel")}),e.jsx(k,{onClick:()=>void j(),children:h("providers.testDialog.primary")})]})]})}):null}function ht(){var T;const{t:s}=q(),t=gs(),i=Ps(t),[r,p]=m.useState(null),[n,j]=m.useState(!1),[x,h]=m.useState(!1),[a,d]=m.useState(!1),b=m.useRef(!1),c=m.useCallback(l=>{b.current=l,d(l)},[]),[o,E]=m.useState(null),O=Ds(({currentLocation:l,nextLocation:w})=>a&&l.pathname!==w.pathname),[g,v]=m.useState(()=>typeof window>"u"?null:window.localStorage.getItem(De.workbench.providerSelection)),[M,A]=m.useState(null);m.useEffect(()=>{M&&g!==M&&A(null)},[M,g]),m.useEffect(()=>{if(!g){window.localStorage.removeItem(De.workbench.providerSelection);return}window.localStorage.setItem(De.workbench.providerSelection,g)},[g]),m.useEffect(()=>{g&&(t.configQuery.isPending||t.configQuery.isFetching||i.providers.some(l=>l.id===g)||v(null))},[g,i.providers,t.configQuery.isPending,t.configQuery.isFetching]);const $=async()=>{if(r){j(!0);try{r.kind==="provider"&&await i.handleDeleteProvider(r.provider),p(null)}finally{j(!1)}}},L=(r==null?void 0:r.kind)==="provider"?hs(t.config,t.customEndpoints,r.provider.id):{routes:0,defaults:0,aggregateMembers:0};return e.jsxs("div",{className:"flex flex-col gap-6",children:[e.jsx(ms,{status:e.jsx(Y,{variant:"secondary",children:s("providers.groupCount",{count:i.providerCount})}),actions:e.jsx(k,{size:"sm",onClick:()=>h(!0),children:s("providers.actions.add")})}),e.jsx(Qs,{providers:i,configPending:t.configQuery.isPending||!t.config&&t.configQuery.isFetching,configError:!t.config&&t.configQuery.isError?((T=t.configQuery.error)==null?void 0:T.message)??s("common.status.error"):null,onRetryConfig:()=>void t.configQuery.refetch(),selectedProviderId:g,onSelectProvider:v,onTest:l=>i.initiateTestConnection(l),onRequestDelete:l=>p({kind:"provider",provider:l}),onDirtyChange:c,autoEditProviderId:M}),e.jsx(Rs,{open:x,onOpenChange:h,existingProviderIds:i.providers.map(l=>l.id),onSubmit:i.handleCreateProvider,onCreated:l=>{t.configQuery.refetch().then(()=>{if(b.current){E(l);return}v(l),A(l)})}}),e.jsx(Ws,{open:i.testDialogOpen,provider:i.testDialogProvider,options:i.anthropicTestHeaderOptions,preservedExtras:i.testDialogPreservedExtras,usePreset:i.testDialogUsePreset,onPresetChange:i.setTestDialogUsePreset,onConfirm:i.confirmTestDialog,onClose:i.closeTestDialog}),e.jsx(Es,{open:!!i.noModelDialogProvider,provider:i.noModelDialogProvider,onClose:()=>i.setNoModelDialogProvider(null),onEdit:l=>{i.setNoModelDialogProvider(null),v(l.id),A(l.id)}}),e.jsx(de,{open:!!r,onOpenChange:l=>{!l&&!n&&p(null)},title:(r==null?void 0:r.kind)==="provider"?s("providers.actions.delete"):"",description:(r==null?void 0:r.kind)==="provider"?s("providers.confirm.delete",{name:r.provider.label||r.provider.id}):"",confirmLabel:s(n?"common.actions.loading":"common.delete"),cancelLabel:s("common.actions.cancel"),loading:n,onConfirm:$,children:(r==null?void 0:r.kind)==="provider"?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"rounded-xl border border-destructive/20 bg-destructive/5 px-3 py-2 font-mono text-xs text-foreground",children:r.provider.label||r.provider.id}),L.routes>0?e.jsx("p",{className:"text-xs text-muted-foreground",children:s("providers.confirm.deleteImpact",{count:L.routes})}):null,L.defaults>0?e.jsx("p",{className:"text-xs text-muted-foreground",children:s("providers.confirm.deleteDefaultsImpact",{count:L.defaults})}):null,L.aggregateMembers>0?e.jsx("p",{className:"text-xs text-muted-foreground",children:s("providers.confirm.deleteAggregateImpact",{count:L.aggregateMembers})}):null]}):null}),e.jsx(de,{open:O.state==="blocked",onOpenChange:l=>{!l&&O.state==="blocked"&&O.reset()},title:s("providers.masterDetail.unsavedTitle"),description:s("providers.masterDetail.unsavedBody"),confirmLabel:s("providers.masterDetail.unsavedConfirm"),cancelLabel:s("common.actions.cancel"),onConfirm:()=>{O.state==="blocked"&&O.proceed()}}),e.jsx(de,{open:!!o,onOpenChange:l=>{l||E(null)},title:s("providers.masterDetail.unsavedTitle"),description:s("providers.masterDetail.unsavedBody"),confirmLabel:s("providers.masterDetail.unsavedConfirm"),cancelLabel:s("common.actions.cancel"),onConfirm:()=>{o&&v(o),E(null)}})]})}export{ht as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as N,aX as vt,j as e,aY as Ue,aD as Ve,aZ as We,a_ as Je,am as q,aR as Nt,aS as wt,aT as kt,aI as Et,aJ as ze,aN as Ct,aO as St,aP as Rt,aQ as Dt,aK as Mt,aL as Pt,aM as Tt,a$ as Ot,Y as Bt}from"./vendor-JUtelXU0.js";import{g as Lt,u as Ft}from"./router-CqUBCAsx.js";import{C as Qe}from"./ConfirmDialog-CRSbmgE7.js";import{a as Ge}from"./PageState-XybOeENt.js";import{P as At}from"./PageToolbar-CnLp4aWt.js";import{t as J,q as Z,f as ae,B as F,T as $t,g as It,h as zt,i as Qt,C as ye,c as ve,b as _t}from"./app-CRxPj2SJ.js";import{d as _e,g as qe,b as He,c as qt,e as se,f as Ke,h as ne,m as ke,i as Ht,C as Xe,O as Ye,u as Kt}from"./modelManagement-DwdbGu0o.js";import{a as Ut}from"./query-CvboQrUT.js";import{g as ge}from"./gateway-DyhqzHSh.js";import{u as be}from"./useAppMutation-B29oVzxS.js";import{D as Ee,A as Ce,a as Se,b as Re,c as De,d as Me,e as Ze}from"./DialogShell-DxWKa5oR.js";import{L as K,I as G}from"./label-CdbE1ezd.js";import{S as Pe,a as Te,b as Oe,c as Be,d as Le,D as Vt}from"./disclosure-CU-KJc8C.js";import{S as Fe}from"./switch-CZn1nypU.js";import{u as I}from"./i18n-v60Yn7Ls.js";import{B as re}from"./badge-eRkhnmCs.js";import{c as je}from"./global-BLUcvOa8.js";import{T as fe}from"./TargetCombobox-DkVdA04_.js";import"./radix-d0BukFWM.js";import"./popover-CuM9b3U7.js";function Wt(a){const{t:s,pushToast:o,config:l,setConfig:r,configQuery:g,customEndpoints:f,tabs:m,ensureConfig:u}=a,c=Ut(),[b,y]=N.useState({}),[R,C]=N.useState({}),[p,w]=N.useState(null),[v,h]=N.useState({}),[x,D]=N.useState({}),[M,z]=N.useState({}),[U,V]=N.useState(null),[oe,ie]=N.useState(null),[le,de]=N.useState(null),[Ne,ce]=N.useState(!1),[ue,me]=N.useState(null),[W,X]=N.useState({}),[he,ee]=N.useState(null),_=N.useRef(null),[pe,te]=N.useState(null),H=t=>{_.current=t,te(t)},k=()=>{_.current=null,te(null)},T=N.useMemo(()=>m.filter(t=>t.key!=="providers"),[m]);N.useEffect(()=>{if(!g.data)return;const t=g.data;y(i=>{const n=_e(t,f);if(!i||Object.keys(i).length===0)return n;const d={...n};for(const[j,E]of Object.entries(i)){if(!(j in n))continue;const S=qe(t,f,j);if(He(E,S))d[j]=E;else{const L=new Map(E.map(O=>[O.source,O.id]));d[j]=n[j].map(O=>({...O,id:L.get(O.source)??O.id}))}}return d}),X(i=>{const n=qt(t,f);if(!i||Object.keys(i).length===0)return n;const d={...n};for(const[j,E]of Object.entries(i)){if(!(j in n))continue;const S=se(t,f,j);JSON.stringify(E)!==JSON.stringify(S)&&(d[j]=E)}return d}),C({}),h(Ke(t,f))},[g.data,f]);const Y=(l==null?void 0:l.providers)??[],Ae=t=>{const i=t==null?void 0:t.trim();if(!i||!i.includes(":"))return null;const n=i.split(":",1)[0].trim();return n?Y.some(d=>d.id===n)?null:n:i},et=N.useMemo(()=>{const t=[],i=new Set;for(const n of Y){const d=n.label&&n.label!==n.id?`${n.label} (${n.id})`:n.id,j=n.models??[];if(j.length>0)for(const S of j){const L=`${n.id}:${S.id}`;i.has(L)||(i.add(L),t.push({value:L,label:`${d} · ${S.label??S.id}`,providerId:n.id,providerLabel:d,modelId:S.id,modelLabel:S.label??S.id,kind:"model",isDefault:n.defaultModel===S.id}))}else if(n.defaultModel){const S=`${n.id}:${n.defaultModel}`;i.has(S)||(i.add(S),t.push({value:S,label:`${d} · ${n.defaultModel}`,providerId:n.id,providerLabel:d,modelId:n.defaultModel,modelLabel:n.defaultModel,kind:"model",isDefault:!0}))}const E=`${n.id}:*`;i.has(E)||(i.add(E),t.push({value:E,label:s("settings.routing.providerPassthroughOption",{provider:d}),providerId:n.id,providerLabel:d,modelId:"*",modelLabel:"*",kind:"passthrough"}))}for(const n of Object.values(b).flat()){const d=n.target.trim();d&&!i.has(d)&&(i.add(d),t.push({value:d,label:d,modelId:d,modelLabel:d,kind:"custom"}))}return t},[Y,b,s]),tt=t=>l?qe(l,f,t):{},st=N.useMemo(()=>{const t={};for(const i of T){const n=b[i.key]||[];t[i.key]=He(n,tt(i.key))}return t},[l,f,b,T]),nt=N.useMemo(()=>{const t={};if(!l)return t;for(const i of T){const n=W[i.key];if(!n){t[i.key]=!1;continue}const d=se(l,f,i.key);t[i.key]=JSON.stringify(n)!==JSON.stringify(d)}return t},[l,f,W,T]),at=(t,i,n)=>{X(d=>({...d,[t]:{...d[t]??{completion:null,reasoning:null,background:null,longContextThreshold:6e4},[i]:n}}))},rt=async t=>{var d,j,E,S,L,O,B,$;if(!u()||_.current)return;const i=W[t];if(!i)return;const n={completion:(d=i.completion)!=null&&d.trim()?i.completion.trim():null,reasoning:(j=i.reasoning)!=null&&j.trim()?i.reasoning.trim():null,background:(E=i.background)!=null&&E.trim()?i.background.trim():null,longContextThreshold:Number.isFinite(i.longContextThreshold)&&i.longContextThreshold>0?Math.floor(i.longContextThreshold):l.defaults.longContextThreshold};for(const A of[n.completion,n.reasoning,n.background]){const P=Ae(A);if(P){o({title:s("settings.validation.routeUnknownProvider",{provider:P}),variant:"error"});return}}ee(t),H(t);try{const A=f.find(P=>P.id===t);if(A){const P={...A.routing??{},defaults:n,modelRoutes:((S=A.routing)==null?void 0:S.modelRoutes)??{}};await ae.update(t,{routing:P}),r(Q=>{if(!Q)return Q;const xe=[...Q.customEndpoints??[]],we=xe.findIndex(yt=>yt.id===t);return we===-1?Q:(xe[we]={...xe[we],routing:P},{...Q,customEndpoints:xe})}),await c.invalidateQueries({queryKey:Z.customEndpoints.all()})}else{const P=t,Q={...l,endpointRouting:{...l.endpointRouting??{},[P]:{defaults:n,modelRoutes:((O=(L=l.endpointRouting)==null?void 0:L[P])==null?void 0:O.modelRoutes)??(P==="anthropic"?l.modelRoutes??{}:{}),compatibility:($=(B=l.endpointRouting)==null?void 0:B[P])==null?void 0:$.compatibility}}};await ge.saveConfig(Q),r(Q)}X(P=>({...P,[t]:n})),o({title:s("workbench.defaults.saveSuccess"),variant:"success"}),g.refetch()}catch(A){o({title:s("workbench.defaults.saveFailure",{message:J(A).message}),variant:"error"})}finally{ee(null),k()}},$e=(t,i)=>{h(n=>({...n,[t]:i})),r(n=>{if(!n)return n;if(t==="anthropic"||t==="openai")return{...n,routingPresets:{...n.routingPresets,[t]:i}};const d=[...n.customEndpoints??[]],j=d.findIndex(E=>E.id===t);return j===-1?n:(d[j]={...d[j],routingPresets:i},{...n,customEndpoints:d})})},ot=(t,i)=>{D(n=>({...n,[t]:i})),i.trim()&&z(n=>({...n,[t]:null}))},it=async t=>{if(!u()||_.current)return;const i=(x[t]??"").trim();if(!i){z(n=>({...n,[t]:s("modelManagement.validation.presetName")}));return}if((v[t]??[]).some(n=>n.name.toLowerCase()===i.toLowerCase())){z(n=>({...n,[t]:s("modelManagement.validation.presetDuplicate",{name:i})}));return}V(t),H(t);try{const d=(await ke.savePreset(t,i)).presets??[];$e(t,d),D(j=>({...j,[t]:""})),z(j=>({...j,[t]:null})),o({title:s("modelManagement.toast.presetSaved",{name:i}),variant:"success"})}catch(n){o({title:s("modelManagement.toast.presetSaveFailure",{message:J(n).message}),variant:"error"})}finally{V(null),k(),g.refetch()}},lt=async(t,i)=>{if(u()&&!_.current){ie({endpoint:t,name:i.name}),H(t);try{const d=(await ke.applyPreset(t,i.name)).config;r(d);const j=_e(d,f);y(E=>({...E,[t]:j[t]??[]})),Ie(t,se(l,f,t),se(d,f,t)),h(Ke(d,f)),t!=="anthropic"&&t!=="openai"&&await c.invalidateQueries({queryKey:Z.customEndpoints.all()}),o({title:s("modelManagement.toast.presetApplySuccess",{name:i.name}),variant:"success"})}catch(n){o({title:s("modelManagement.toast.presetApplyFailure",{message:J(n).message}),variant:"error"})}finally{ie(null),k(),g.refetch()}}},dt=async(t,i)=>{if(u()&&!_.current){de({endpoint:t,name:i.name}),H(t);try{const n=await ke.deletePreset(t,i.name);$e(t,n.presets??[]),o({title:s("modelManagement.toast.presetDeleteSuccess",{name:i.name}),variant:"success"})}catch(n){o({title:s("modelManagement.toast.presetDeleteFailure",{message:J(n).message}),variant:"error"})}finally{de(null),k(),g.refetch()}}},ct=async t=>{const i=f.find(n=>n.id===t);if(!(!i||i.deletable===!1))try{await ae.delete(t),await c.invalidateQueries({queryKey:Z.customEndpoints.all()}),r(n=>n&&{...n,customEndpoints:(n.customEndpoints??[]).filter(d=>d.id!==t)}),g.refetch(),o({title:s("modelManagement.deleteEndpointSuccess"),variant:"success"})}catch(n){const d=J(n);o({title:s("modelManagement.deleteEndpointError",{error:d.message}),variant:"error"})}},ut=t=>{y(i=>({...i,[t]:[...i[t]||[],{id:ne(),source:"",target:""}]})),C(i=>({...i,[t]:null}))},mt=async(t,i)=>{if(u()&&!_.current){ce(!0),H(t);try{if(t==="anthropic"||t==="openai"){const n=t,d=l.endpointRouting?{...l.endpointRouting}:{},j=d[n]??{defaults:l.defaults,modelRoutes:(n==="anthropic"?l.modelRoutes:{})??{}},E={defaults:j.defaults??l.defaults,modelRoutes:j.modelRoutes??{}},S={...l,endpointRouting:{...d,[n]:i?{...E,compatibility:{enabled:!0}}:{...E}}};await ge.saveConfig(S),r(S)}else{const n=[...l.customEndpoints??[]],d=n.findIndex(L=>L.id===t);if(d===-1)throw new Error(s("modelManagement.toast.endpointNotFound"));const j=n[d],E=j.routing??{defaults:l.defaults,modelRoutes:{}};n[d]={...j,routing:i?{...E,compatibility:{enabled:!0}}:{defaults:E.defaults,modelRoutes:E.modelRoutes}};const S={...l,customEndpoints:n};await ge.saveConfig(S),r(S)}o({title:s("modelManagement.toast.compatibilitySaved",{state:s(i?"common.status.enabled":"common.status.disabled")}),variant:"success"}),g.refetch()}catch(n){const d=J(n);o({title:s("modelManagement.toast.compatibilitySaveFailure",{message:d.message}),variant:"error"})}finally{ce(!1),k()}}},ht=(t,i)=>{y(n=>{const d=n[t]||[];return d.some(j=>j.source.trim()===i.trim())?n:{...n,[t]:[...d,{id:ne(),source:i,target:""}]}}),C(n=>({...n,[t]:null}))},pt=(t,i,n,d)=>{y(j=>({...j,[t]:(j[t]||[]).map(E=>E.id===i?{...E,[n]:d}:E)})),C(j=>({...j,[t]:null}))},xt=(t,i)=>{y(n=>({...n,[t]:(n[t]||[]).filter(d=>d.id!==i)})),C(n=>({...n,[t]:null}))},gt=(t,i,n)=>{i!==n&&(y(d=>{const j=d[t]||[],E=j.findIndex(L=>L.id===i),S=j.findIndex(L=>L.id===n);return E===-1||S===-1?d:{...d,[t]:vt(j,E,S)}}),C(d=>({...d,[t]:null})))},ft=t=>{var n;if(!l)return;const i=(l.customEndpoints??f).find(d=>d.id===t);if(i)y(d=>{var j;return{...d,[t]:Object.entries(((j=i.routing)==null?void 0:j.modelRoutes)??{}).map(([E,S])=>({id:ne(),source:E,target:S}))}});else{const d=l.endpointRouting??{},j=t,E=j==="anthropic"?l.modelRoutes??{}:{},S=((n=d[j])==null?void 0:n.modelRoutes)??E;y(L=>({...L,[t]:Object.entries(S).map(([O,B])=>({id:ne(),source:O,target:B}))}))}C(d=>({...d,[t]:null}))},bt=be({mutationFn:async t=>(await ge.saveConfig(t.nextConfig),t)}),jt=be({mutationFn:async t=>(await ae.update(t.endpoint,{routing:t.routing}),t)}),Ie=(t,i,n)=>{X(d=>{const j=d[t];return j&&JSON.stringify(j)!==JSON.stringify(i)?d:{...d,[t]:n}})};return{endpointTabs:T,routesByEndpoint:b,setRoutesByEndpoint:y,routeError:R,savingRouteFor:p,presetsByEndpoint:v,presetNameByEndpoint:x,presetErrorByEndpoint:M,savingPresetFor:U,applyingPreset:oe,deletingPreset:le,savingCompatibilityPolicy:Ne,writingEndpoint:pe,presetDiffDialog:ue,setPresetDiffDialog:me,providerModelOptions:et,isDirtyByEndpoint:st,defaultsByEndpoint:W,isDefaultsDirtyByEndpoint:nt,savingDefaultsFor:he,handleDefaultsChange:at,handleSaveDefaults:rt,handlePresetNameChange:ot,handleSavePreset:it,handleApplyPreset:lt,handleDeletePreset:dt,handleDeleteEndpoint:ct,handleAddRoute:ut,handleAddSuggestion:ht,handleRouteChange:pt,handleRemoveRoute:xt,handleReorderRules:gt,handleResetRoutes:ft,handleSaveRoutes:async t=>{var d,j,E,S,L;if(!u()||_.current)return;const i=b[t]||[],n={};for(const O of i){const B=O.source.trim(),$=O.target.trim();if(!B&&!$)continue;if(!B||!$){C(P=>({...P,[t]:s("settings.validation.routePair")}));return}if(n[B]){C(P=>({...P,[t]:s("settings.validation.routeDuplicate",{model:B})}));return}const A=Ae($);if(A){C(P=>({...P,[t]:s("settings.validation.routeUnknownProvider",{provider:A})}));return}n[B]=$}C(O=>({...O,[t]:null})),w(t),H(t);try{const O=f.find(B=>B.id===t);if(O){const B={...O.routing??{},modelRoutes:n,defaults:((d=O.routing)==null?void 0:d.defaults)||l.defaults};await jt.mutateAsync({endpoint:t,routing:B}),r($=>{if(!$)return $;const A=[...$.customEndpoints??[]],P=A.findIndex(Q=>Q.id===t);return P===-1?$:(A[P]={...A[P],routing:B},{...$,customEndpoints:A})}),await c.invalidateQueries({queryKey:Z.customEndpoints.all()}),Ie(t,se(l,f,t),B.defaults)}else{const B={...l,endpointRouting:{...l.endpointRouting??{},[t]:{defaults:((E=(j=l.endpointRouting)==null?void 0:j[t])==null?void 0:E.defaults)??l.defaults,modelRoutes:n,compatibility:(L=(S=l.endpointRouting)==null?void 0:S[t])==null?void 0:L.compatibility}},modelRoutes:t==="anthropic"?n:l.modelRoutes??{}};await bt.mutateAsync({endpoint:t,nextConfig:B}),r(B)}y(B=>{const $=B[t]??[],A=new Map($.map(P=>[P.source.trim(),P.id]));return{...B,[t]:Object.entries(n).map(([P,Q])=>({id:A.get(P.trim())??ne(),source:P,target:Q}))}}),o({title:s("modelManagement.toast.routesSaved"),variant:"success"}),g.refetch()}catch(O){o({title:s("modelManagement.toast.routesSaveFailure",{message:J(O).message}),variant:"error"})}finally{w(null),k()}},handleCompatibilityEnabledChange:mt}}const Jt=["anthropic","openai-auto","openai-chat","openai-responses"];function Gt({open:a,endpoint:s,onClose:o,onSuccess:l}){const{t:r}=I(),[g,f]=N.useState(!1),[m,u]=N.useState({id:"",label:"",paths:[{path:"",protocol:"openai-auto"}],enabled:!0});N.useEffect(()=>{if(a){if(f(!1),s){const h=s.paths&&s.paths.length>0?s.paths:s.path&&s.protocol?[{path:s.path,protocol:s.protocol}]:[{path:"",protocol:"openai-auto"}];u({id:s.id,label:s.label,paths:h,enabled:s.enabled!==!1});return}u({id:"",label:"",paths:[{path:"",protocol:"openai-auto"}],enabled:!0})}},[s,a]);const c=be({mutationFn:ae.create,invalidateKeys:[Z.customEndpoints.all()],successToast:()=>({title:r("modelManagement.createEndpointSuccess")}),errorToast:h=>({title:r("modelManagement.createEndpointError",{error:h.message})}),onSuccess:async h=>{var x;l((x=h.endpoint)==null?void 0:x.id),o()}}),b=be({mutationFn:h=>ae.update(h.id,h.updates),invalidateKeys:[Z.customEndpoints.all()],successToast:()=>({title:r("modelManagement.updateEndpointSuccess")}),errorToast:h=>({title:r("modelManagement.updateEndpointError",{error:h.message})}),onSuccess:async()=>{l(),o()}}),y=()=>{u(h=>({...h,paths:[...h.paths,{path:"",protocol:"anthropic"}]}))},R=h=>{m.paths.length!==1&&u(x=>({...x,paths:x.paths.filter((D,M)=>M!==h)}))},C=(h,x,D)=>{u(M=>{const z=[...M.paths];return z[h]={...z[h],[x]:D},{...M,paths:z}})},p=h=>{if(h==null||h.preventDefault(),f(!0),!m.id.trim()||!m.label.trim())return;for(const D of m.paths)if(!D.path.trim())return;const x=m.paths.map(D=>({path:D.path.trim(),protocol:D.protocol}));if(s){b.mutate({id:s.id,updates:{label:m.label.trim(),paths:x,enabled:m.enabled}});return}c.mutate({id:m.id.trim(),label:m.label.trim(),paths:x,enabled:m.enabled})},w=c.isPending||b.isPending,v=m.paths.length===0?r("modelManagement.atLeastOnePath"):!m.id.trim()||!m.label.trim()?r("modelManagement.endpointValidationError"):m.paths.some(h=>!h.path.trim())?r("modelManagement.pathValidationError"):null;return e.jsx(Ee,{open:a,onOpenChange:h=>!h&&o(),children:e.jsxs(Ce,{className:"max-w-lg",onInteractOutside:h=>h.preventDefault(),children:[e.jsxs(Se,{children:[e.jsx(Re,{children:r(s?"modelManagement.editEndpoint":"modelManagement.createEndpoint")}),e.jsx(De,{className:"truncate font-mono text-xs",children:s?s.id:r("modelManagement.endpointRoutingHint")})]}),e.jsx(Me,{children:e.jsxs("form",{id:"endpoint-form",onSubmit:p,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(K,{children:[r("modelManagement.endpointId")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(G,{value:m.id,onChange:h=>u(x=>({...x,id:h.target.value})),placeholder:r("modelManagement.endpointIdPlaceholder"),disabled:!!s}),e.jsx("p",{className:"text-xs text-muted-foreground",children:r("modelManagement.endpointIdHint")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(K,{children:[r("modelManagement.endpointLabel")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(G,{value:m.label,onChange:h=>u(x=>({...x,label:h.target.value})),placeholder:r("modelManagement.endpointLabelPlaceholder")})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(K,{children:[r("modelManagement.endpointPaths")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsxs(F,{type:"button",variant:"ghost",size:"sm",onClick:y,children:[e.jsx(Ue,{className:"mr-1 h-3 w-3"}),r("modelManagement.addPath")]})]}),e.jsx("div",{className:"space-y-3",children:m.paths.map((h,x)=>e.jsxs("div",{className:"space-y-2 border border-border bg-card p-3",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(G,{value:h.path,onChange:D=>C(x,"path",D.target.value),placeholder:r("modelManagement.endpointPathPlaceholder")}),e.jsxs(Pe,{value:h.protocol,onValueChange:D=>C(x,"protocol",D),children:[e.jsx(Te,{children:e.jsx(Oe,{})}),e.jsx(Be,{children:Jt.map(D=>e.jsx(Le,{value:D,children:r(D==="anthropic"?"modelManagement.protocolAnthropic":D==="openai-auto"?"modelManagement.protocolOpenAI":D==="openai-chat"?"modelManagement.protocolOpenAIChat":"modelManagement.protocolOpenAIResponses")},D))})]})]}),m.paths.length>1?e.jsx(F,{type:"button",variant:"ghost",size:"sm",onClick:()=>R(x),className:"text-destructive",children:e.jsx(Ve,{className:"h-4 w-4"})}):null]}),e.jsxs("div",{className:"space-y-1 text-xs text-muted-foreground",children:[x===0?e.jsx("p",{children:r("modelManagement.endpointPathHint")}):null,e.jsx("p",{children:r(`modelManagement.protocolHints.${h.protocol}`)})]})]},`${h.protocol}-${x}`))}),v&&g?e.jsx("p",{className:"text-xs text-destructive",children:v}):null]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Fe,{id:"endpoint-enabled",checked:m.enabled,onCheckedChange:h=>u(x=>({...x,enabled:h}))}),e.jsx(K,{htmlFor:"endpoint-enabled",children:r("modelManagement.endpointEnabled")})]}),s?null:e.jsx("div",{className:"rounded-xl bg-secondary p-4",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:r("modelManagement.endpointRoutingHint")})})]})}),e.jsxs(Ze,{children:[e.jsx(F,{variant:"outline",onClick:o,disabled:w,children:r("common.cancel")}),e.jsx(F,{type:"submit",form:"endpoint-form",disabled:w,children:r(w?"common.saving":s?"common.save":"common.create")})]})]})})}function Xt({tabs:a,customEndpoints:s,routeCounts:o,selectedEndpointId:l,onSelect:r,onEditEndpoint:g,onDeleteEndpoint:f}){var b;const{t:m}=I(),u=s.find(y=>y.id===l),c=u?u.label||u.id:((b=a.find(y=>y.key===l))==null?void 0:b.label)??l;return e.jsxs("div",{className:"flex items-center gap-1.5 lg:hidden",children:[e.jsxs(Pe,{value:l,onValueChange:r,children:[e.jsx(Te,{"data-testid":"routing-endpoint-switcher","aria-label":m("workbench.endpointSwitcher.label"),className:"h-8 w-[230px] text-xs",children:e.jsx(Oe,{children:c})}),e.jsx(Be,{children:a.map(y=>{const R=s.find(w=>w.id===y.key),C=R?R.label||R.id:y.label,p=o[y.key]??0;return e.jsx(Le,{value:y.key,className:"text-xs",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:C}),e.jsx("span",{className:"shrink-0 tabular-nums text-muted-foreground",children:m("workbench.endpointSwitcher.ruleCount",{count:p})})]})},y.key)})})]}),u?e.jsxs(e.Fragment,{children:[e.jsx(F,{variant:"ghost",size:"icon","data-testid":"endpoint-edit",className:"h-7 w-7",title:m("common.edit"),"aria-label":m("common.edit"),onClick:()=>g(u),children:e.jsx(We,{className:"h-3.5 w-3.5","aria-hidden":!0})}),u.deletable!==!1?e.jsx(F,{variant:"ghost",size:"icon","data-testid":"endpoint-delete",className:"h-7 w-7 text-muted-foreground hover:text-destructive",title:m("common.delete"),"aria-label":m("common.delete"),onClick:()=>f(u),children:e.jsx(Je,{className:"h-3.5 w-3.5","aria-hidden":!0})}):null]}):null]})}function Yt({dialog:a,currentRoutes:s,onConfirm:o,onClose:l}){const{t:r}=I();if(!a)return null;const{endpoint:g,preset:f}=a,m=f.modelRoutes??{},u={};for(const p of s){const w=p.source.trim(),v=p.target.trim();w&&v&&(u[w]=v)}const c=new Set([...Object.keys(u),...Object.keys(m)]),b=[],y=[],R=[];for(const p of c){const w=p in u,v=p in m;v&&!w?b.push([p,m[p]]):w&&!v?y.push([p,u[p]]):w&&v&&u[p]!==m[p]&&R.push([p,u[p],m[p]])}const C=b.length>0||y.length>0||R.length>0;return e.jsx(Ee,{open:!0,onOpenChange:p=>!p&&l(),children:e.jsxs(Ce,{className:"max-w-2xl",children:[e.jsxs(Se,{children:[e.jsx(Re,{children:r("modelManagement.presets.diffTitle")}),e.jsx(De,{children:r("modelManagement.presets.diffDescription",{name:f.name})})]}),e.jsx(Me,{children:C?e.jsxs("div",{className:"max-h-80 space-y-2 rounded-xl bg-secondary/50 p-3 text-sm",children:[b.map(([p,w])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-success-bg px-2 py-1.5 text-success",children:[e.jsx(re,{variant:"outline",className:"border-success/30 text-xs",children:r("modelManagement.presets.diffAdded")}),e.jsx("span",{className:"truncate",children:p}),e.jsx(q,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:w})]},`add-${p}`)),y.map(([p,w])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-error-bg px-2 py-1.5 text-error",children:[e.jsx(re,{variant:"outline",className:"border-error/30 text-xs",children:r("modelManagement.presets.diffRemoved")}),e.jsx("span",{className:"truncate",children:p}),e.jsx(q,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:w})]},`rm-${p}`)),R.map(([p,w,v])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-warning-bg px-2 py-1.5 text-warning",children:[e.jsx(re,{variant:"outline",className:"border-warning/30 text-xs",children:r("modelManagement.presets.diffChanged")}),e.jsx("span",{className:"truncate",children:p}),e.jsx(q,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate line-through opacity-60",children:w}),e.jsx(q,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:v})]},`chg-${p}`))]}):e.jsx("p",{className:"rounded-xl bg-secondary/50 py-8 text-center text-sm text-muted-foreground",children:r("modelManagement.presets.diffEmpty")})}),e.jsxs(Ze,{children:[e.jsx(F,{variant:"outline",onClick:l,children:r("common.cancel")}),e.jsx(F,{onClick:()=>o(g,f),disabled:!C,children:r("modelManagement.presets.diffConfirm")})]})]})})}function Zt({routing:a,endpoint:s,onRequestDeletePreset:o,embedded:l=!1}){var p,w;const{t:r}=I(),g=a.presetsByEndpoint[s]??[],f=a.presetNameByEndpoint[s]??"",m=a.presetErrorByEndpoint[s],u=a.savingPresetFor===s,c=((p=a.applyingPreset)==null?void 0:p.endpoint)===s?a.applyingPreset.name:null,b=((w=a.deletingPreset)==null?void 0:w.endpoint)===s?a.deletingPreset.name:null,y=a.writingEndpoint===s,R=!!a.isDirtyByEndpoint[s],C=e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(G,{"data-testid":"preset-name-input",value:f,onChange:v=>a.handlePresetNameChange(s,v.target.value),placeholder:r("modelManagement.presets.namePlaceholder"),disabled:u,className:"h-8 flex-1 text-xs"}),e.jsx(F,{variant:"outline",size:"sm","data-testid":"save-preset",onClick:()=>void a.handleSavePreset(s),disabled:u||y||R,children:r(u?"modelManagement.presets.saving":"modelManagement.presets.save")})]}),R?e.jsx("p",{className:"text-[11px] text-warning",children:r("modelManagement.presets.dirtyBlocked")}):null,m?e.jsx("p",{className:"text-xs text-destructive",children:m}):null,g.length===0?e.jsx("p",{className:"py-2 text-center text-[11px] text-muted-foreground",children:r("modelManagement.presets.empty")}):e.jsx($t,{children:e.jsx("div",{className:"grid grid-cols-1 gap-1.5 sm:grid-cols-2",children:g.map(v=>{const h=c===v.name,x=b===v.name,D=Object.entries(v.modelRoutes??{}),M=D.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(It,{children:[e.jsx(zt,{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:v.name}),e.jsx(re,{variant:"outline",className:"mt-0.5 text-[10px] font-normal",children:M>0?r("modelManagement.presets.rulesCount",{count:M}):r("modelManagement.presets.noRules")})]})}),M>0?e.jsx(Qt,{side:"bottom",className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1 text-xs",children:[D.slice(0,5).map(([z,U])=>e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"truncate",children:z}),e.jsx(q,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:U})]},z)),M>5?e.jsxs("div",{className:"text-muted-foreground",children:["…+",M-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-foreground underline decoration-muted-foreground/40 underline-offset-2 hover:decoration-foreground disabled:opacity-50",onClick:()=>a.setPresetDiffDialog({endpoint:s,preset:v}),disabled:h||x||y,children:r(h?"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":r("common.delete"),onClick:()=>o(s,v),disabled:x||h||y,children:r(x?"modelManagement.presets.deleting":"modelManagement.presets.delete")})]})]},v.name)})})})]});return l?e.jsx("div",{"data-testid":"routing-presets-card",children:C}):e.jsx(ye,{"data-testid":"routing-presets-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(ve,{className:"space-y-3 p-4",children:[e.jsx("h3",{className:"text-[13px] font-semibold",children:r("modelManagement.presets.title")}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:r("modelManagement.presets.description")}),C]})})}function es({open:a,onOpenChange:s,routing:o,endpoint:l,onRequestDeletePreset:r}){const{t:g}=I();return e.jsx(Ee,{open:a,onOpenChange:s,children:e.jsxs(Ce,{className:"max-w-lg",children:[e.jsxs(Se,{children:[e.jsx(Re,{children:g("modelManagement.presets.title")}),e.jsx(De,{className:"text-xs",children:g("modelManagement.presets.description")})]}),e.jsx(Me,{children:e.jsx(Zt,{routing:o,endpoint:l,embedded:!0,onRequestDeletePreset:r})})]})})}function ts({routing:a,endpoint:s,tabInfo:o,config:l,customEndpoints:r}){var v,h;const{t:g}=I(),f=a.routesByEndpoint[s]||[],m=a.savingRouteFor===s,u=a.savingCompatibilityPolicy,c=a.writingEndpoint===s,b=((v=o==null?void 0:o.protocols)==null?void 0:v.some(x=>x.startsWith("openai")))??s==="openai",y=Ht(s,l,r),R=b?(y==null?void 0:y.enabled)??!1:!1,p=((h=o==null?void 0:o.protocols)==null?void 0:h.includes("anthropic"))??s==="anthropic"?Xe:Ye,w=new Set(f.map(x=>x.source.trim()).filter(Boolean));return e.jsx(ye,{"data-testid":"endpoint-config-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(ve,{className:"space-y-3 p-4",children:[e.jsx("h3",{className:"text-[12.5px] font-semibold",children:g("workbench.endpointConfig.title")}),b?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(K,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:g("modelManagement.openaiCompatibility.toggleLabel")}),e.jsx("p",{className:"text-[10.5px] text-muted-foreground",children:g(R?"modelManagement.openaiCompatibility.enabledHint":"modelManagement.openaiCompatibility.disabledHint")})]}),e.jsx(Fe,{"data-testid":"compatibility-toggle",checked:R,onCheckedChange:x=>void a.handleCompatibilityEnabledChange(s,x),disabled:u||c,"aria-label":g("modelManagement.openaiCompatibility.toggleLabel")})]}):null,e.jsxs("div",{children:[e.jsx("p",{className:"mb-1.5 text-[11px] text-muted-foreground",children:g("settings.routing.suggested")}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:p.map(x=>{const D=w.has(x);return e.jsx("button",{"data-testid":"suggestion-chip",type:"button",onClick:()=>a.handleAddSuggestion(s,x),disabled:m||D,className:je("h-6 border px-2 text-[10.5px] transition-colors",D?"border-border bg-secondary/40 text-muted-foreground/50":"border-border bg-card hover:border-foreground hover:text-foreground"),children:x},`${s}-${x}`)})})]})]})})}function ss({routing:a,endpoint:s}){const{t:o}=I(),l=a.defaultsByEndpoint[s]??null,r=a.isDefaultsDirtyByEndpoint[s]??!1,g=a.savingDefaultsFor===s,f=a.writingEndpoint===s,m=a.providerModelOptions;return e.jsx(ye,{"data-testid":"routing-defaults-card",className:"border-foreground bg-secondary shadow-none",children:e.jsxs(ve,{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-foreground",children:o("workbench.defaults.title")}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:o("workbench.defaults.cardSubtitle")})]}),e.jsxs(Vt,{summary:e.jsx("span",{className:"text-[11px] font-medium text-muted-foreground",children:o("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(K,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:o("workbench.defaults.reasoningLabel")}),e.jsx(fe,{value:(l==null?void 0:l.reasoning)??"",onChange:u=>a.handleDefaultsChange(s,"reasoning",u),options:m,disabled:g,ariaLabel:o("workbench.defaults.reasoningLabel"),placeholder:o("workbench.defaults.targetPlaceholder")})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(K,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:o("workbench.defaults.backgroundLabel")}),e.jsx(fe,{value:(l==null?void 0:l.background)??"",onChange:u=>a.handleDefaultsChange(s,"background",u),options:m,disabled:g,ariaLabel:o("workbench.defaults.backgroundLabel"),placeholder:o("workbench.defaults.targetPlaceholder")})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(K,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:o("workbench.defaults.thresholdLabel")}),e.jsx(G,{type:"number",min:1,value:(l==null?void 0:l.longContextThreshold)||"",onChange:u=>{const c=Number.parseInt(u.target.value,10);a.handleDefaultsChange(s,"longContextThreshold",Number.isFinite(c)?c:0)},disabled:g,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(q,{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(fe,{value:(l==null?void 0:l.completion)??"",onChange:u=>a.handleDefaultsChange(s,"completion",u),options:m,disabled:g,ariaLabel:o("workbench.defaults.completionLabel"),placeholder:o("workbench.defaults.targetPlaceholder")})}),e.jsxs(F,{variant:"outline",size:"sm","data-testid":"save-defaults",onClick:()=>void a.handleSaveDefaults(s),disabled:g||!r||f,className:"relative",children:[o(g?"common.actions.saving":"workbench.defaults.save"),r?e.jsx("span",{className:"absolute -right-1 -top-1 h-2 w-2 rounded-full bg-warning"}):null]})]})]})})}function ns({tabs:a,customEndpoints:s,routeCounts:o,selectedEndpointId:l,onSelect:r,onEditEndpoint:g,onDeleteEndpoint:f}){const{t:m}=I(),u=a.map(c=>{const b=s.find(y=>y.id===c.key);return b?{key:c.key,label:b.label||b.id,enabled:b.enabled!==!1,custom:b}:{key:c.key,label:c.label,enabled:!0}});return e.jsxs("aside",{"data-testid":"endpoint-rail","aria-label":m("workbench.endpointRail.title"),className:"hidden lg:flex lg:sticky lg:top-4 flex-col gap-1 border border-border bg-card p-1.5 shadow-[var(--surface-shadow)] lg:max-h-[calc(100vh-2rem)] lg:overflow-y-auto",children:[e.jsxs("div",{className:"px-2 pb-1 pt-2",children:[e.jsx("h2",{className:"text-[12.5px] font-semibold",children:m("workbench.endpointRail.title")}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:m("workbench.endpointRail.subtitle")})]}),u.map(c=>{const b=c.key===l,y=o[c.key]??0,R=!c.enabled;return e.jsxs("div",{"data-testid":"routing-endpoint-row",className:je("flex items-stretch border transition-colors",b?"border-foreground bg-secondary":"border-transparent hover:bg-accent",R?"opacity-60":""),children:[e.jsxs("button",{type:"button",onClick:()=>r(c.key),"aria-current":b?"true":void 0,className:"flex min-w-0 flex-1 items-center gap-2 px-2 py-2 text-left",children:[e.jsx("span",{className:je("h-1.5 w-1.5 shrink-0 rounded-full",R?"bg-muted-foreground/30":b?"bg-foreground":"bg-muted-foreground/50"),"aria-hidden":!0}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-xs font-medium",title:c.label,children:c.label}),e.jsx("span",{className:"shrink-0 text-[10.5px] tabular-nums text-muted-foreground",children:m("workbench.endpointRail.ruleCount",{count:y})})]}),c.custom?e.jsxs("div",{className:"flex items-center gap-0.5 pr-1",children:[e.jsx("button",{type:"button","data-testid":"endpoint-edit",onClick:()=>g(c.custom),className:"flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-foreground",title:m("common.edit"),"aria-label":m("common.edit"),children:e.jsx(We,{className:"h-3 w-3","aria-hidden":!0})}),c.custom.deletable!==!1?e.jsx("button",{type:"button","data-testid":"endpoint-delete",onClick:()=>f(c.custom),className:"flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-destructive",title:m("common.delete"),"aria-label":m("common.delete"),children:e.jsx(Je,{className:"h-3 w-3","aria-hidden":!0})}):null]}):null]},c.key)})]})}function as({endpointPath:a,defaultTarget:s}){const{t:o}=I();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:o("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:o("workbench.flow.clientStep")}),e.jsx(q,{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:[o("workbench.flow.endpointStep")," ",e.jsx("span",{className:"font-mono",children:a})]}),e.jsx(q,{className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0}),e.jsx("span",{className:"border border-foreground bg-secondary px-2.5 py-1 text-[11px] font-semibold text-foreground",children:o("workbench.flow.matchStep")}),e.jsx(q,{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:s||o("workbench.flow.fallbackNote")})]})]})}function rs({entry:a,index:s,savingRoute:o,options:l,sourceListId:r,onRouteChange:g,onRemoveRoute:f}){const{t:m}=I(),{attributes:u,listeners:c,setNodeRef:b,setActivatorNodeRef:y,transform:R,transition:C,isDragging:p}=Nt({id:a.id});return e.jsxs("div",{ref:b,"data-testid":"route-rule-row","data-id":a.id,style:{transform:kt.Transform.toString(R),transition:C},className:je("grid grid-cols-[auto_auto_minmax(0,1fr)_auto] items-center gap-x-2 gap-y-1.5 border border-border bg-card p-2 sm:flex sm:gap-2",p&&"z-10 opacity-60 shadow-[var(--surface-shadow-lg)]"),children:[e.jsx("button",{ref:y,type:"button","data-testid":"route-rule-grip","aria-label":m("workbench.routing.dragHandle"),className:"row-span-2 flex h-7 w-4 shrink-0 cursor-grab touch-none items-center justify-center text-muted-foreground hover:text-foreground active:cursor-grabbing sm:row-span-1",...u,...c,children:e.jsx(wt,{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:s+1}),e.jsx(G,{"data-testid":"route-rule-source",value:a.source,onChange:w=>g(a.id,"source",w.target.value),placeholder:m("settings.routing.sourcePlaceholder"),list:r,disabled:o,className:"h-8 min-w-0 flex-1 text-xs"}),e.jsx(q,{className:"col-start-2 row-start-2 h-3.5 w-3.5 shrink-0 text-muted-foreground sm:col-auto sm:row-auto","aria-hidden":!0}),e.jsx("div",{"data-testid":"route-rule-target",className:"col-start-3 row-start-2 min-w-0 sm:col-auto sm:row-auto sm:flex-[1.15]",children:e.jsx(fe,{value:a.target,onChange:w=>g(a.id,"target",w),options:l,disabled:o,ariaLabel:m("workbench.routing.targetLabel"),placeholder:m("settings.routing.targetPlaceholder")})}),e.jsx(F,{variant:"ghost",size:"icon","data-testid":"route-rule-delete",className:"col-start-4 row-span-2 h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive sm:col-auto sm:row-span-1",onClick:()=>f(a.id),disabled:o,"aria-label":m("common.delete"),children:e.jsx(Ve,{className:"h-3.5 w-3.5","aria-hidden":!0})})]})}function os({routing:a,endpoint:s,tabInfo:o}){var w;const{t:l}=I(),r=a.routesByEndpoint[s]||[],g=a.routeError[s],f=a.savingRouteFor===s,m=a.isDirtyByEndpoint[s]??!1,u=a.writingEndpoint===s,c=a.providerModelOptions,b=`route-source-${s}`,y=Et(ze(Tt,{activationConstraint:{distance:6}}),ze(Pt,{coordinateGetter:Mt})),R=v=>{const{active:h,over:x}=v;!x||h.id===x.id||a.handleReorderRules(s,String(h.id),String(x.id))},p=((w=o==null?void 0:o.protocols)==null?void 0:w.includes("anthropic"))??s==="anthropic"?Xe:Ye;return e.jsx(ye,{"data-testid":"routing-rules-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(ve,{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:[l("workbench.routing.rulesTitle"),e.jsx(re,{variant:"outline",className:"text-[10.5px] font-normal tabular-nums",children:r.length})]}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:l("workbench.routing.rulesSubtitle")})]}),e.jsx(F,{variant:"outline",size:"sm","data-testid":"add-route",onClick:()=>a.handleAddRoute(s),disabled:f,children:l("settings.routing.add")})]}),g?e.jsx("p",{className:"text-xs text-destructive",children:g}):null,r.length===0?e.jsx(Ge,{compact:!0,title:l("workbench.routing.emptyTitle"),description:l("workbench.routing.emptyDescription"),action:e.jsx(F,{variant:"outline",size:"sm",onClick:()=>a.handleAddRoute(s),disabled:f,children:l("workbench.routing.addFirst")})}):e.jsx(Ct,{sensors:y,collisionDetection:St,onDragEnd:R,children:e.jsx(Rt,{items:r.map(v=>v.id),strategy:Dt,children:e.jsx("div",{className:"flex flex-col gap-1.5",children:r.map((v,h)=>e.jsx(rs,{entry:v,index:h,savingRoute:f,options:c,sourceListId:b,onRouteChange:(x,D,M)=>a.handleRouteChange(s,x,D,M),onRemoveRoute:x=>a.handleRemoveRoute(s,x)},v.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:l(m?"modelManagement.actions.footerDirtyHint":"modelManagement.actions.footerSavedHint")}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(F,{variant:"outline",size:"sm","data-testid":"reset-routes",onClick:()=>a.handleResetRoutes(s),disabled:f||!m,children:l("common.actions.reset")}),e.jsxs(F,{variant:"outline",size:"sm","data-testid":"save-routes",onClick:()=>void a.handleSaveRoutes(s),disabled:f||u,className:"relative",children:[l(f?"common.actions.saving":"modelManagement.actions.saveRoutes"),m?e.jsx("span",{className:"absolute -right-1 -top-1 h-2 w-2 rounded-full bg-warning"}):null]})]})]}),e.jsx("datalist",{id:b,children:p.map(v=>e.jsx("option",{value:v},`${b}-${v}`))})]})})}const is={simulateRequest(a){return{url:"/api/routing/simulate",method:"POST",data:a}}},ls=350;function ds(a,s){switch(a.kind){case"modelRoute":return{label:a.viaAlias?s("workbench.hitSim.reasonModelRouteAlias"):s("workbench.hitSim.reasonModelRoute"),tone:"hit"};case"directMatch":return{label:s("workbench.hitSim.reasonDirectMatch"),tone:"hit"};case"thinkingDefault":return{label:s("workbench.hitSim.reasonThinkingDefault"),tone:"hit"};case"completionDefault":return{label:s("workbench.hitSim.reasonCompletionDefault"),tone:"hit"};case"longContextDefault":return{label:s("workbench.hitSim.reasonLongContext"),tone:"hit",detail:s("workbench.hitSim.longContextDetail",{estimate:a.tokenEstimate.toLocaleString(),threshold:a.threshold.toLocaleString()})};case"fallback":return{label:s("workbench.hitSim.reasonFallback"),tone:"fallback"}}return{label:s("workbench.hitSim.reasonFallback"),tone:"fallback"}}function cs({tabs:a,endpoint:s,onEndpointChange:o,hasUnsavedChanges:l=!1}){var D;const{t:r}=I(),g=a.filter(M=>M.key!=="providers"),[f,m]=N.useState(((D=g[0])==null?void 0:D.key)??"anthropic"),u=s??f,c=M=>{s&&o?o(M):m(M)},[b,y]=N.useState(""),[R,C]=N.useState(!1),[p,w]=N.useState("");N.useEffect(()=>{const M=setTimeout(()=>w(b.trim()),ls);return()=>clearTimeout(M)},[b]);const{data:v,isFetching:h,error:x}=_t(["routing","simulate",u,p,R],is.simulateRequest({endpoint:u,model:p||void 0,thinking:R}),{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:r("workbench.hitSim.title")}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:r("workbench.hitSim.subtitle")})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-2",children:[s?null:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:r("workbench.hitSim.endpointLabel")}),e.jsxs(Pe,{value:u,onValueChange:c,children:[e.jsx(Te,{className:"h-8 w-[168px]",children:e.jsx(Oe,{})}),e.jsx(Be,{children:g.map(M=>e.jsx(Le,{value:M.key,children:M.label},M.key))})]})]}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Fe,{checked:R,onCheckedChange:C,"aria-label":r("workbench.hitSim.thinking")}),r("workbench.hitSim.thinking")]})]}),e.jsx(G,{value:b,onChange:M=>y(M.target.value),placeholder:r("workbench.hitSim.modelPlaceholder"),className:"h-9 text-xs",spellCheck:!1,autoComplete:"off","aria-label":r("workbench.hitSim.modelPlaceholder")}),l?e.jsx("p",{"data-testid":"simulator-unsaved-notice",className:"text-[11px] text-warning",children:r("workbench.hitSim.unsavedNotice")}):null,e.jsx(us,{result:v,loading:h,errorMessage:(x==null?void 0:x.message)??null,requestedModel:p})]})}function us({result:a,loading:s,errorMessage:o,requestedModel:l}){var u;const{t:r}=I();if(o)return e.jsxs("p",{className:"text-xs text-muted-foreground",children:[r("workbench.hitSim.errorPrefix"),": ",o]});if(!a)return s?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:r("workbench.hitSim.empty")});const g=ds(a.reason,r),f=g.tone==="fallback",m=l||r("workbench.hitSim.anyModel");return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:f?"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:f?"text-[11px] font-semibold text-warning":"text-[11px] font-semibold text-success",children:g.label}),e.jsx("div",{className:"mt-1 text-xs text-foreground",children:m}),e.jsxs("div",{className:"mt-1 text-xs text-muted-foreground",children:["→ ",a.providerLabel,":",a.modelId]}),g.detail?e.jsx("div",{className:"mt-1 text-[11px] text-muted-foreground",children:g.detail}):null]}),(((u=a.candidates)==null?void 0:u.length)??0)>1?e.jsxs("div",{className:"rounded-lg border border-border bg-secondary/50 px-3 py-2.5",children:[e.jsx("div",{className:"text-[11px] font-semibold text-muted-foreground",children:r("providers.aggregate.simulator.candidatesTitle")}),e.jsx("ol",{className:"mt-1.5 space-y-1",children:(a.candidates??[]).map((c,b)=>e.jsxs("li",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"w-4 shrink-0 text-center text-[10.5px] tabular-nums text-muted-foreground",children:b+1}),e.jsxs("span",{className:"min-w-0 truncate font-mono text-foreground",children:[c.providerLabel,":",c.modelId]}),b===0?e.jsx("span",{className:"shrink-0 text-[10px] font-medium text-muted-foreground",children:r("providers.aggregate.simulator.primaryBadge")}):null]},`${c.providerId}:${c.modelId}`))})]}):null,f?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:r("workbench.hitSim.fallbackHint")}):null]})}function ms({routing:a,config:s,customEndpoints:o,routeCounts:l,selectedEndpointId:r,onSelectEndpoint:g,onEditEndpoint:f,onDeleteEndpoint:m}){var C;I();const u=r??((C=a.endpointTabs[0])==null?void 0:C.key)??"anthropic",c=a.endpointTabs.find(p=>p.key===u),b=a.defaultsByEndpoint[u],y=!!a.isDirtyByEndpoint[u]||!!a.isDefaultsDirtyByEndpoint[u],R=(()=>{var w;if(u==="anthropic")return"/anthropic";if(u==="openai")return"/openai";const p=o.find(v=>v.id===u);return(w=p==null?void 0:p.paths)!=null&&w.length?p.paths[0].path:p!=null&&p.path?p.path:`/${u}`})();return e.jsxs("div",{"data-testid":"routing-workspace",className:"flex flex-col gap-3.5",children:[e.jsx(as,{endpointPath:R,defaultTarget:(b==null?void 0:b.completion)??null}),e.jsxs("div",{className:"grid items-start gap-3.5 lg:grid-cols-[210px_minmax(0,2fr)_minmax(0,1fr)]",children:[e.jsx(ns,{tabs:a.endpointTabs,customEndpoints:o,routeCounts:l,selectedEndpointId:r,onSelect:g,onEditEndpoint:f,onDeleteEndpoint:m}),e.jsxs("div",{className:"flex flex-col gap-3.5",children:[e.jsx(ss,{routing:a,endpoint:u}),e.jsx(os,{routing:a,endpoint:u,tabInfo:c})]}),e.jsxs("div",{className:"flex flex-col gap-3.5 lg:sticky lg:top-4",children:[e.jsx(cs,{tabs:a.endpointTabs,endpoint:u,onEndpointChange:g,hasUnsavedChanges:y}),e.jsx(ts,{routing:a,endpoint:u,tabInfo:c,config:s,customEndpoints:o})]})]})]})}function Bs(){var he,ee,_,pe,te,H;const{t:a}=I(),s=Kt(),o=Wt(s),[l,r]=N.useState(!1),[g,f]=N.useState(void 0),[m,u]=N.useState(!1),[c,b]=N.useState(null),[y,R]=N.useState(!1),C=Object.values(o.isDirtyByEndpoint).some(Boolean)||Object.values(o.isDefaultsDirtyByEndpoint).some(Boolean),p=Lt(({currentLocation:k,nextLocation:T})=>C&&k.pathname!==T.pathname);N.useEffect(()=>{if(!C)return;const k=T=>{T.preventDefault(),T.returnValue=""};return window.addEventListener("beforeunload",k),()=>window.removeEventListener("beforeunload",k)},[C]);const[w,v]=Ft(),h=w.get("endpoint"),[x,D]=N.useState(h),[M,z]=N.useState(null);N.useEffect(()=>{D(h)},[h]);const U=N.useRef(!1);N.useEffect(()=>{if(!U.current){if(h){U.current=!0;return}o.endpointTabs.length!==0&&(U.current=!0,v(k=>{const T=new URLSearchParams(k);return T.set("endpoint",o.endpointTabs[0].key),T},{replace:!0}))}},[h,o.endpointTabs,v]);const V=N.useCallback(k=>{v(T=>{const Y=new URLSearchParams(T);return Y.set("endpoint",k),Y},{replace:!0})},[v]),oe=N.useCallback(()=>{v(k=>{const T=new URLSearchParams(k);return T.delete("endpoint"),T},{replace:!0})},[v]);N.useEffect(()=>{M&&o.endpointTabs.some(k=>k.key===M)&&(z(null),V(M))},[M,o.endpointTabs,V]),N.useEffect(()=>{x&&(s.customEndpointsQuery.isPending||o.endpointTabs.some(k=>k.key===x)||oe())},[x,o.endpointTabs,s.customEndpointsQuery.isPending,oe]);const ie=()=>{f(void 0),r(!0)},le=k=>{f(k),r(!0)},de=async()=>{if(c){R(!0);try{c.kind==="preset"?await o.handleDeletePreset(c.endpoint,c.preset):c.kind==="endpoint"&&await o.handleDeleteEndpoint(c.endpoint.id),b(null)}finally{R(!1)}}},Ne=(c==null?void 0:c.kind)==="preset"?a("modelManagement.presets.delete"):(c==null?void 0:c.kind)==="endpoint"?a("common.delete"):"",ce=(c==null?void 0:c.kind)==="preset"?a("modelManagement.confirm.deletePreset",{name:c.preset.name}):(c==null?void 0:c.kind)==="endpoint"?[a("modelManagement.deleteEndpointConfirm",{label:c.endpoint.label}),(((he=o.routesByEndpoint[c.endpoint.id])==null?void 0:he.length)??0)>0?a("modelManagement.deleteEndpointImpactRoutes",{count:((ee=o.routesByEndpoint[c.endpoint.id])==null?void 0:ee.length)??0}):"",(((_=o.presetsByEndpoint[c.endpoint.id])==null?void 0:_.length)??0)>0?a("modelManagement.deleteEndpointImpactPresets",{count:((pe=o.presetsByEndpoint[c.endpoint.id])==null?void 0:pe.length)??0}):""].filter(Boolean).join(" "):"",ue=(c==null?void 0:c.kind)==="preset"?c.preset.name:(c==null?void 0:c.kind)==="endpoint"?c.endpoint.label:"",me=Object.fromEntries(Object.entries(o.routesByEndpoint).map(([k,T])=>[k,(T==null?void 0:T.length)??0])),W=x??((te=o.endpointTabs[0])==null?void 0:te.key)??"anthropic",X=(k,T)=>{b({kind:"preset",endpoint:k,preset:T})};return e.jsxs("div",{className:"flex flex-col gap-6",children:[e.jsx(At,{actions:e.jsxs(e.Fragment,{children:[e.jsx(Xt,{tabs:o.endpointTabs,customEndpoints:s.customEndpoints,routeCounts:me,selectedEndpointId:W,onSelect:V,onEditEndpoint:le,onDeleteEndpoint:k=>b({kind:"endpoint",endpoint:k})}),e.jsxs(F,{variant:"outline",size:"sm",onClick:()=>u(!0),children:[e.jsx(Ot,{className:"h-4 w-4","aria-hidden":!0}),a("workbench.templates")]}),e.jsxs(F,{size:"sm",onClick:ie,children:[e.jsx(Ue,{className:"h-4 w-4","aria-hidden":!0}),a("workbench.endpoints.create")]})]})}),!s.config&&s.configQuery.isError?e.jsx(Ge,{tone:"danger",icon:e.jsx(Bt,{className:"h-5 w-5","aria-hidden":"true"}),title:a("common.status.error"),description:((H=s.configQuery.error)==null?void 0:H.message)??a("common.status.error"),action:e.jsx(F,{variant:"outline",onClick:()=>void s.configQuery.refetch(),children:a("common.actions.refresh")})}):e.jsx(ms,{routing:o,config:s.config,customEndpoints:s.customEndpoints,routeCounts:me,selectedEndpointId:x,onSelectEndpoint:V,onEditEndpoint:le,onDeleteEndpoint:k=>b({kind:"endpoint",endpoint:k})}),e.jsx(es,{open:m,onOpenChange:u,routing:o,endpoint:W,onRequestDeletePreset:X}),e.jsx(Gt,{open:l,endpoint:g,onClose:()=>{r(!1),f(void 0)},onSuccess:k=>{s.configQuery.refetch(),k&&z(k)}}),e.jsx(Yt,{dialog:o.presetDiffDialog,currentRoutes:o.presetDiffDialog?o.routesByEndpoint[o.presetDiffDialog.endpoint]||[]:[],onConfirm:(k,T)=>{o.setPresetDiffDialog(null),o.handleApplyPreset(k,T)},onClose:()=>o.setPresetDiffDialog(null)}),e.jsx(Qe,{open:!!c,onOpenChange:k=>{!k&&!y&&b(null)},title:Ne,description:ce,confirmLabel:a(y?"common.actions.loading":"common.delete"),cancelLabel:a("common.actions.cancel"),loading:y,onConfirm:de,children:ue?e.jsx("div",{className:"rounded-xl border border-destructive/20 bg-destructive/5 px-3 py-2 font-mono text-xs text-foreground",children:ue}):null}),e.jsx(Qe,{open:p.state==="blocked",onOpenChange:k=>{!k&&p.state==="blocked"&&p.reset()},title:a("providers.masterDetail.unsavedTitle"),description:a("providers.masterDetail.unsavedBody"),confirmLabel:a("providers.masterDetail.unsavedConfirm"),cancelLabel:a("common.actions.cancel"),onConfirm:()=>{p.state==="blocked"&&p.proceed()}})]})}export{Bs as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{j as e,b5 as he,b0 as Tt,r as m,aY as Ft,a_ as Ot,av as Mt}from"./vendor-JUtelXU0.js";import{C as xe}from"./ConfirmDialog-CRSbmgE7.js";import{P as Se}from"./PageState-XybOeENt.js";import{P as Ht}from"./PageToolbar-CnLp4aWt.js";import{C as F,c as H,b as X,B as T,q as Y,r as G,e as Kt,d as qt,u as Bt,t as Ut}from"./app-CRxPj2SJ.js";import{B as I}from"./badge-eRkhnmCs.js";import{L as f,I as P}from"./label-CdbE1ezd.js";import{S as Z}from"./switch-CZn1nypU.js";import{S as je,a as Ne,b as Ce,c as we,d as z,D as Yt}from"./disclosure-CU-KJc8C.js";import{c as V}from"./global-BLUcvOa8.js";import{u as E}from"./i18n-v60Yn7Ls.js";import{a as Vt}from"./query-CvboQrUT.js";import{u as W}from"./useAppMutation-B29oVzxS.js";import{g as st}from"./gateway-DyhqzHSh.js";import{c as It}from"./clipboard-DqvcglYs.js";import{c as Qt}from"./types-BT3gK5lJ.js";import{g as _t}from"./router-CqUBCAsx.js";import"./DialogShell-DxWKa5oR.js";import"./radix-d0BukFWM.js";const zt={pricesRequest(){return{url:"/api/billing/prices",method:"GET"}}},$t=[{value:"fatal",labelKey:"fatal"},{value:"error",labelKey:"error"},{value:"warn",labelKey:"warn"},{value:"info",labelKey:"info"},{value:"debug",labelKey:"debug"},{value:"trace",labelKey:"trace"}],Pe="7.2";function Jt(){return{key:"",currency:"CNY",input:"",output:"",cacheRead:"",cacheCreation:"",label:""}}function ge(s){const t=s.billing,o=(t==null?void 0:t.displayCurrency)==="USD"?"USD":"CNY",c=(t==null?void 0:t.rates)??{};let a=Pe;o==="CNY"&&typeof c.USD=="number"&&c.USD>0?a=String(c.USD):o==="USD"&&typeof c.CNY=="number"&&c.CNY>0&&(a=String(1/c.CNY));const i=Object.entries((t==null?void 0:t.modelPrices)??{}).map(([u,n])=>{var l;return{key:u,currency:((l=n.currency)==null?void 0:l.toUpperCase())==="USD"?"USD":"CNY",input:String(n.input??0),output:String(n.output??0),cacheRead:String(n.cacheRead??0),cacheCreation:String(n.cacheCreation??0),label:n.label??""}});return{displayCurrency:o,usdCnyRate:a,overrides:i.length>0?i:[Jt()]}}function at(s){return!!(s.key.trim()||s.input.trim()||s.output.trim()||s.cacheRead.trim()||s.cacheCreation.trim()||s.label.trim())}function Gt(s){const t=Number(s.usdCnyRate),o=s.displayCurrency==="CNY"?{USD:Number.isFinite(t)&&t>0?t:Number(Pe)}:{CNY:Number.isFinite(t)&&t>0?1/t:1/Number(Pe)},c={};for(const a of s.overrides){if(!at(a))continue;const i=a.key.trim();i&&(c[i]={currency:a.currency,input:Number(a.input)||0,output:Number(a.output)||0,cacheRead:Number(a.cacheRead)||0,cacheCreation:Number(a.cacheCreation)||0,...a.label.trim()?{label:a.label.trim()}:{}})}return{displayCurrency:s.displayCurrency,rates:o,...Object.keys(c).length>0?{modelPrices:c}:{}}}const ke=[{id:"section-basics",labelKey:"settings.sections.basics"},{id:"section-protocol",labelKey:"settings.sections.protocol"},{id:"section-security",labelKey:"settings.sections.security"},{id:"section-billing",labelKey:"settings.sections.billing"},{id:"section-config-file",labelKey:"settings.sections.configFile"},{id:"section-cleanup",labelKey:"settings.sections.cleanup"}];function be(s){var c,a,i,u,n,l,g,O,L;const t=s.storePayloads,o=w=>typeof w=="boolean"?w:typeof t=="boolean"?t:!0;return{logRetentionDays:String(s.logRetentionDays??30),logExportTimeoutSeconds:String(s.logExportTimeoutSeconds??60),storeRequestPayloads:o(s.storeRequestPayloads),storeResponsePayloads:o(s.storeResponsePayloads),logLevel:s.logLevel??"info",bodyLimitMb:(()=>{const w=s.bodyLimit;return typeof w=="number"&&Number.isFinite(w)&&w>0?String(Math.max(1,Math.round(w/(1024*1024)))):"10"})(),enableRoutingFallback:s.enableRoutingFallback===!0,httpEnabled:((c=s.http)==null?void 0:c.enabled)!==!1,httpPort:String(((a=s.http)==null?void 0:a.port)??s.port??4100),httpHost:((i=s.http)==null?void 0:i.host)??s.host??"127.0.0.1",httpsEnabled:((u=s.https)==null?void 0:u.enabled)===!0,httpsPort:String(((n=s.https)==null?void 0:n.port)??4443),httpsHost:((l=s.https)==null?void 0:l.host)??s.host??"127.0.0.1",httpsKeyPath:((g=s.https)==null?void 0:g.keyPath)??"",httpsCertPath:((O=s.https)==null?void 0:O.certPath)??"",httpsCaPath:((L=s.https)==null?void 0:L.caPath)??""}}function fe(s){return{enabled:s.enabled,username:s.username??"",password:"",confirmPassword:""}}function Wt({activeSection:s,onSelectSection:t}){const{t:o}=E();return e.jsxs(e.Fragment,{children:[e.jsx("nav",{className:"hidden xl:block",children:e.jsxs(F,{className:"sticky top-20 p-3.5",children:[e.jsx("p",{className:"mb-2.5 px-2 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground",children:o("settings.sections.jump")}),e.jsx("div",{className:"space-y-1.5",children:ke.map((c,a)=>e.jsxs("button",{type:"button",onClick:()=>t(c.id),className:V("flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-left text-sm font-semibold transition-all duration-200",s===c.id?"bg-secondary text-foreground":"text-muted-foreground hover:text-foreground"),children:[e.jsx("span",{className:V("flex h-7 w-7 items-center justify-center rounded-lg text-[11px] font-semibold",s===c.id?"bg-foreground text-background":"bg-secondary text-muted-foreground"),children:a+1}),e.jsx("span",{children:o(c.labelKey)})]},c.id))})]})}),e.jsx("div",{className:"min-w-0 xl:hidden",children:e.jsx("div",{className:"overflow-x-auto pb-1",children:e.jsx("div",{className:"flex w-max gap-2 px-1",children:ke.map(c=>e.jsx("button",{type:"button",onClick:()=>t(c.id),className:V("rounded-lg px-4 py-2 text-xs font-semibold transition-all duration-150",s===c.id?"bg-secondary text-foreground font-medium":"text-muted-foreground hover:text-foreground hover:bg-secondary/50"),children:o(c.labelKey)},c.id))})})})]})}function Xt({defaultsSummary:s,errors:t,form:o,onInputChange:c,onSetForm:a,sectionRef:i}){const{t:u}=E();return e.jsx(F,{id:"section-basics",ref:i,className:"bg-card shadow-[var(--surface-shadow)]",children:e.jsxs(H,{className:"pt-6",children:[e.jsx("h3",{className:"mb-4 text-sm font-semibold",children:u("settings.sections.basics")}),e.jsxs("div",{className:"grid gap-5 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:u("settings.fields.port")}),e.jsx(P,{type:"number",min:1,max:65535,value:o.httpPort,"data-visual-volatile":"text",onChange:n=>a(l=>({...l,httpPort:n.target.value})),"aria-invalid":!!t.httpPort}),t.httpPort?e.jsx("p",{className:"text-xs text-destructive",children:t.httpPort}):null]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:u("settings.fields.host")}),e.jsx(P,{value:o.httpHost,onChange:n=>a(l=>({...l,httpHost:n.target.value})),placeholder:u("settings.fields.hostPlaceholder")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:u("settings.fields.retention")}),e.jsx(P,{type:"number",min:1,max:365,value:o.logRetentionDays,onChange:n=>c("logRetentionDays")(n.target.value),"aria-invalid":!!t.logRetentionDays}),t.logRetentionDays?e.jsx("p",{className:"text-xs text-destructive",children:t.logRetentionDays}):null]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:u("settings.fields.logExportTimeout")}),e.jsx(P,{type:"number",min:5,max:600,value:o.logExportTimeoutSeconds,onChange:n=>c("logExportTimeoutSeconds")(n.target.value),"aria-invalid":!!t.logExportTimeoutSeconds}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u("settings.fields.logExportTimeoutHint")}),t.logExportTimeoutSeconds?e.jsx("p",{className:"text-xs text-destructive",children:t.logExportTimeoutSeconds}):null]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:u("settings.fields.bodyLimit")}),e.jsx(P,{type:"number",min:1,max:2048,value:o.bodyLimitMb,onChange:n=>c("bodyLimitMb")(n.target.value),"aria-invalid":!!t.bodyLimitMb}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u("settings.fields.bodyLimitHint")}),t.bodyLimitMb?e.jsx("p",{className:"text-xs text-destructive",children:t.bodyLimitMb}):null]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:u("settings.fields.logLevel")}),e.jsxs(je,{value:o.logLevel,onValueChange:n=>a(l=>({...l,logLevel:n})),children:[e.jsx(Ne,{children:e.jsx(Ce,{})}),e.jsx(we,{children:$t.map(n=>e.jsx(z,{value:n.value,children:u(`settings.fields.logLevelOption.${n.labelKey}`)},n.value))})]})]}),e.jsxs("div",{className:"grid gap-4 md:col-span-2 sm:grid-cols-2",children:[e.jsx(ye,{label:u("settings.fields.storeRequestPayloads"),hint:u("settings.fields.storeRequestPayloadsHint"),checked:o.storeRequestPayloads,onCheckedChange:n=>a(l=>({...l,storeRequestPayloads:n}))}),e.jsx(ye,{label:u("settings.fields.storeResponsePayloads"),hint:u("settings.fields.storeResponsePayloadsHint"),checked:o.storeResponsePayloads,onCheckedChange:n=>a(l=>({...l,storeResponsePayloads:n}))}),e.jsx(ye,{label:u("settings.fields.enableRoutingFallback"),hint:u("settings.fields.enableRoutingFallbackHint"),checked:o.enableRoutingFallback,onCheckedChange:n=>a(l=>({...l,enableRoutingFallback:n}))})]}),e.jsxs("div",{className:"rounded-xl bg-secondary px-4 py-5 md:col-span-2",children:[e.jsx(f,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:u("settings.fields.defaults")}),e.jsx("p",{className:"mt-2 text-sm",children:s??u("settings.defaults.none")})]})]})]})})}function Zt({errors:s,form:t,onSetForm:o,protocolChangesPending:c,sectionRef:a}){const{t:i}=E();return e.jsx(F,{id:"section-protocol",ref:a,className:"bg-card shadow-[var(--surface-shadow)]",children:e.jsxs(H,{className:"space-y-6 pt-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:i("settings.sections.protocol")}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:i("settings.protocol.description")})]}),c?e.jsx("div",{className:"rounded-xl bg-warning-bg ring-1 ring-warning/30 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(he,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-warning"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:i("settings.protocol.restartWarning")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i("settings.protocol.restartHint")}),e.jsx("code",{className:"block rounded-lg border border-border bg-secondary px-3 py-2 text-xs font-mono text-foreground",children:"cc-gw restart --daemon"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i("settings.protocol.restartTip")})]})]})}):null,s.protocol?e.jsxs("div",{className:"rounded-xl bg-destructive/10 ring-1 ring-destructive/30 p-4 text-sm text-destructive",children:[e.jsx(he,{className:"mr-2 inline h-4 w-4"}),s.protocol]}):null,e.jsxs("div",{className:"rounded-xl bg-secondary p-5",children:[e.jsxs("div",{className:"mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(f,{className:"text-sm font-medium text-foreground",children:i("settings.protocol.http.enable")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i("settings.protocol.http.hint")})]}),e.jsx(Z,{checked:t.httpEnabled,onCheckedChange:u=>o(n=>({...n,httpEnabled:u}))})]}),t.httpEnabled?e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:i("settings.protocol.http.listener",{address:`${t.httpHost||"127.0.0.1"}:${t.httpPort||"4100"}`})})}):null]}),e.jsxs("div",{className:"rounded-xl bg-secondary p-5",children:[e.jsxs("div",{className:"mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(f,{className:"text-sm font-medium text-foreground",children:i("settings.protocol.https.enable")}),e.jsx(Tt,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i("settings.protocol.https.hint")})]}),e.jsx(Z,{checked:t.httpsEnabled,onCheckedChange:u=>o(n=>({...n,httpsEnabled:u}))})]}),t.httpsEnabled?e.jsxs("div",{className:"mt-4 space-y-4 border-t border-border pt-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:i("settings.protocol.https.port")}),e.jsx(P,{type:"number",min:1,max:65535,value:t.httpsPort,onChange:u=>o(n=>({...n,httpsPort:u.target.value})),"aria-invalid":!!s.httpsPort}),s.httpsPort?e.jsx("p",{className:"text-xs text-destructive",children:s.httpsPort}):null]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:i("settings.protocol.https.host")}),e.jsx(P,{value:t.httpsHost,onChange:u=>o(n=>({...n,httpsHost:u.target.value})),placeholder:"127.0.0.1"})]})]}),e.jsx(ve,{label:i("settings.protocol.https.keyPath"),value:t.httpsKeyPath,onChange:u=>o(n=>({...n,httpsKeyPath:u})),placeholder:"~/.cc-gw/certs/key.pem"}),e.jsx(ve,{label:i("settings.protocol.https.certPath"),value:t.httpsCertPath,onChange:u=>o(n=>({...n,httpsCertPath:u})),placeholder:"~/.cc-gw/certs/cert.pem"}),e.jsx(ve,{label:i("settings.protocol.https.caPath"),value:t.httpsCaPath,onChange:u=>o(n=>({...n,httpsCaPath:u})),placeholder:"留空则不使用"}),e.jsx("div",{className:"rounded-xl bg-warning-bg ring-1 ring-warning/30 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(he,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-warning"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx("p",{className:"text-sm font-medium text-warning",children:i("settings.protocol.https.warning")}),e.jsx("p",{className:"text-xs leading-relaxed text-warning",children:i("settings.protocol.https.tip")})]})]})})]}):null]})]})})}function es({authErrors:s,authForm:t,authLoading:o,authSettings:c,needsPassword:a,onSetAuthForm:i,sectionRef:u}){const{t:n}=E();return e.jsx(F,{id:"section-security",ref:u,className:"bg-card shadow-[var(--surface-shadow)]",children:e.jsxs(H,{className:"space-y-5 pt-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:n("settings.sections.security")}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:n("settings.auth.description")})]}),o&&!c?e.jsx(Se,{compact:!0,label:n("common.loading")}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-4 rounded-xl bg-secondary p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{className:"text-sm font-medium",children:n("settings.auth.enable")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:n("settings.auth.enableHint")}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-xs font-medium text-muted-foreground",children:[e.jsx("span",{className:"rounded-lg bg-secondary px-3 py-1 text-[11px] tracking-[0.08em]",children:"/ui"}),e.jsx("span",{className:"rounded-lg bg-secondary px-3 py-1 text-[11px] tracking-[0.08em]",children:"/api/*"}),e.jsx("span",{className:"rounded-lg bg-secondary px-3 py-1 text-[11px] tracking-[0.08em]",children:"Cookie Session"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 self-start sm:self-auto",children:[e.jsx(I,{variant:t.enabled?"success":"secondary",children:t.enabled?n("settings.auth.statusEnabled"):n("settings.auth.statusDisabled")}),e.jsx(Z,{checked:t.enabled,onCheckedChange:l=>i(g=>({...g,enabled:l}))})]})]}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,0.85fr)]",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(f,{children:n("settings.auth.username")}),e.jsx(P,{value:t.username,onChange:l=>i(g=>({...g,username:l.target.value})),placeholder:n("settings.auth.usernamePlaceholder")}),s.username?e.jsx("p",{className:"text-xs text-destructive",children:s.username}):null]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:n("settings.auth.password")}),e.jsx(P,{type:"password",value:t.password,disabled:!t.enabled,onChange:l=>i(g=>({...g,password:l.target.value})),placeholder:n("settings.auth.passwordPlaceholder")}),s.password?e.jsx("p",{className:"text-xs text-destructive",children:s.password}):e.jsx("p",{className:"text-xs text-muted-foreground",children:n(a?"settings.auth.passwordHintRequired":"settings.auth.passwordHintOptional")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:n("settings.auth.confirmPassword")}),e.jsx(P,{type:"password",value:t.confirmPassword,disabled:!t.enabled,onChange:l=>i(g=>({...g,confirmPassword:l.target.value})),placeholder:n("settings.auth.confirmPasswordPlaceholder")}),s.confirmPassword?e.jsx("p",{className:"text-xs text-destructive",children:s.confirmPassword}):null]})]}),e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"rounded-xl bg-secondary p-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.34em] text-muted-foreground",children:n("settings.auth.status")}),e.jsx("p",{className:"mt-2 text-base font-semibold",children:c!=null&&c.enabled?n("settings.auth.statusEnabled"):n("settings.auth.statusDisabled")}),c!=null&&c.username?e.jsxs("div",{className:"mt-3 rounded-lg bg-background px-3 py-2 text-xs font-medium text-foreground",children:[n("settings.auth.username"),": ",c.username]}):null]}),e.jsx("div",{className:"rounded-xl bg-secondary px-4 py-3 text-xs text-muted-foreground",children:n(a?"settings.auth.passwordHintRequired":"settings.auth.passwordHintOptional")})]})]})]})]})})}function ts({errors:s,form:t,onSetForm:o,sectionRef:c}){var K;const{t:a}=E(),[i,u]=m.useState(""),n=X(Y.billing.prices(),zt.pricesRequest()),l=(h,d)=>{o(y=>({...y,overrides:y.overrides.map((k,R)=>R===h?{...k,...d}:k)}))},g=h=>{o(d=>({...d,overrides:d.overrides.filter((y,k)=>k!==h)}))},O=()=>{o(h=>({...h,overrides:[...h.overrides,{key:"",currency:"CNY",input:"",output:"",cacheRead:"",cacheCreation:"",label:""}]}))},L=m.useMemo(()=>{var y;const h=((y=n.data)==null?void 0:y.entries)??[],d=i.trim().toLowerCase();return d?h.filter(k=>k.key.toLowerCase().includes(d)):h},[n.data,i]),w=h=>h.toLocaleString(void 0,{maximumFractionDigits:4});return e.jsx(F,{id:"section-billing",ref:c,className:"bg-card shadow-[var(--surface-shadow)]",children:e.jsxs(H,{className:"space-y-6 pt-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:a("settings.sections.billing")}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:a("billing.description")})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:a("billing.displayCurrency")}),e.jsxs(je,{value:t.displayCurrency,onValueChange:h=>o(d=>({...d,displayCurrency:h==="USD"?"USD":"CNY"})),children:[e.jsx(Ne,{"aria-label":a("billing.displayCurrency"),children:e.jsx(Ce,{})}),e.jsxs(we,{children:[e.jsx(z,{value:"CNY",children:"CNY(¥)"}),e.jsx(z,{value:"USD",children:"USD($)"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:a("billing.displayCurrencyHint")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:a("billing.rateLabel")}),e.jsx(P,{type:"number",min:"0",step:"0.0001",value:t.usdCnyRate,onChange:h=>o(d=>({...d,usdCnyRate:h.target.value})),"aria-invalid":!!s.usdCnyRate}),s.usdCnyRate?e.jsx("p",{className:"text-xs text-destructive",children:s.usdCnyRate}):e.jsx("p",{className:"text-xs text-muted-foreground",children:a("billing.rateHint",{value:(1/(Number(t.usdCnyRate)||1)).toFixed(4)})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:a("billing.overrides.title")}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:a("billing.overrides.description")})]}),e.jsxs(T,{type:"button",variant:"outline",size:"sm",onClick:O,children:[e.jsx(Ft,{className:"mr-1.5 h-3.5 w-3.5","aria-hidden":"true"}),a("billing.overrides.add")]})]}),e.jsx("div",{className:"space-y-3",children:t.overrides.map((h,d)=>{var k;const y=(k=s.overrides)==null?void 0:k[d];return e.jsxs("div",{"data-testid":`billing-override-row-${d}`,className:"grid gap-3 rounded-xl bg-secondary/60 p-3 lg:grid-cols-[minmax(0,1.4fr)_auto_repeat(4,minmax(0,0.8fr))_auto] lg:items-end",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(f,{className:"text-xs text-muted-foreground",children:a("billing.overrides.key")}),e.jsx(P,{value:h.key,onChange:R=>l(d,{key:R.target.value}),placeholder:"claude-sonnet-4-5 / acme:internal-model","aria-invalid":!!(y!=null&&y.key)}),y!=null&&y.key?e.jsx("p",{className:"text-xs text-destructive",children:y.key}):e.jsx("p",{className:"text-xs text-muted-foreground/70",children:a("billing.overrides.keyHint")})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(f,{className:"text-xs text-muted-foreground",children:a("billing.overrides.currency")}),e.jsxs(je,{value:h.currency,onValueChange:R=>l(d,{currency:R}),children:[e.jsx(Ne,{className:"w-[92px]","aria-label":a("billing.overrides.currency"),children:e.jsx(Ce,{})}),e.jsxs(we,{children:[e.jsx(z,{value:"CNY",children:"CNY"}),e.jsx(z,{value:"USD",children:"USD"})]})]})]}),[["input","priceInput"],["output","priceOutput"],["cacheRead","priceCacheRead"],["cacheCreation","priceCacheCreation"]].map(([R,p])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(f,{className:"text-xs text-muted-foreground",children:a(`billing.overrides.${p}`)}),e.jsx(P,{type:"number",min:"0",step:"0.0001",value:h[R],onChange:q=>l(d,{[R]:q.target.value})})]},R)),e.jsx(T,{type:"button",variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>g(d),disabled:t.overrides.length===1,"aria-label":a("billing.overrides.remove"),children:e.jsx(Ot,{className:"h-4 w-4","aria-hidden":"true"})}),y!=null&&y.prices?e.jsx("p",{className:"text-xs text-destructive lg:col-span-7",children:y.prices}):null]},d)})})]}),e.jsx(Yt,{summary:e.jsx("span",{className:"text-sm font-medium",children:a("billing.builtin.title")}),badge:e.jsx(I,{variant:"secondary",className:"text-[10px]",children:L.length}),contentClassName:"border-t border-border p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:a("billing.builtin.description")}),e.jsx(P,{value:i,onChange:h=>u(h.target.value),placeholder:a("billing.builtin.filterPlaceholder"),className:"max-w-xs"}),n.isPending?e.jsx(Se,{compact:!0,label:a("common.loadingShort")}):n.isError?e.jsx("p",{className:"text-xs text-destructive",children:a("billing.builtin.loadError",{message:((K=n.error)==null?void 0:K.message)??""})}):e.jsx("div",{className:"max-h-[320px] overflow-auto rounded-lg border border-border bg-card",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"sticky top-0 bg-secondary text-left uppercase tracking-wider text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2 font-semibold",children:a("billing.builtin.columns.key")}),e.jsx("th",{className:"px-3 py-2 font-semibold",children:a("billing.builtin.columns.source")}),e.jsx("th",{className:"px-3 py-2 text-right font-semibold",children:a("billing.builtin.columns.input")}),e.jsx("th",{className:"px-3 py-2 text-right font-semibold",children:a("billing.builtin.columns.output")}),e.jsx("th",{className:"px-3 py-2 text-right font-semibold",children:a("billing.builtin.columns.cacheRead")}),e.jsx("th",{className:"px-3 py-2 text-right font-semibold",children:a("billing.builtin.columns.cacheCreation")})]})}),e.jsxs("tbody",{className:"divide-y divide-border/60",children:[L.map(h=>e.jsxs("tr",{className:"tabular-nums",children:[e.jsx("td",{className:"px-3 py-1.5 font-mono",children:h.key}),e.jsx("td",{className:"px-3 py-1.5",children:e.jsx(I,{variant:h.source==="override"?"default":"secondary",className:"text-[10px]",children:h.source})}),e.jsx("td",{className:"px-3 py-1.5 text-right",children:w(h.input)}),e.jsx("td",{className:"px-3 py-1.5 text-right",children:w(h.output)}),e.jsx("td",{className:"px-3 py-1.5 text-right",children:w(h.cacheRead)}),e.jsx("td",{className:"px-3 py-1.5 text-right",children:w(h.cacheCreation)})]},`${h.source}:${h.key}`)),L.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-3 py-4 text-center text-muted-foreground",children:a("billing.builtin.empty")})}):null]})]})}),e.jsx("p",{className:"text-xs text-muted-foreground/70",children:a("billing.builtin.footnote")})]})}),e.jsx("div",{className:"rounded-xl bg-secondary px-4 py-3 text-xs text-muted-foreground",children:a("billing.estimateNote")})]})})}function ss({configPath:s,onCopyPath:t,sectionRef:o}){const{t:c}=E();return e.jsx(F,{id:"section-config-file",ref:o,className:"bg-card shadow-[var(--surface-shadow)]",children:e.jsxs(H,{className:"space-y-3 pt-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:c("settings.sections.configFile")}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:c("settings.file.description")})]}),e.jsxs(T,{variant:"outline",size:"sm",onClick:t,className:"w-full sm:w-auto",children:[e.jsx(Mt,{className:"mr-2 h-4 w-4"}),c("common.actions.copy")]})]}),e.jsx("code",{"data-visual-volatile":"true",className:"block break-all rounded-lg bg-secondary px-4 py-3 text-xs font-mono text-muted-foreground",children:s||c("settings.file.unknown")}),e.jsx("div",{className:"rounded-lg bg-secondary px-4 py-3 text-xs text-muted-foreground",children:c("help.note")})]})})}function as({cleaning:s,clearingAll:t,compacting:o,dbSizeDisplay:c,onCompact:a,onOpenCleanup:i,onOpenClearAll:u,sectionRef:n}){const{t:l}=E();return e.jsx(F,{id:"section-cleanup",ref:n,className:"bg-card shadow-[var(--surface-shadow)]",children:e.jsxs(H,{className:"space-y-4 pt-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:l("settings.sections.cleanup")}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:l("settings.cleanup.description")})]}),e.jsxs("div",{className:"rounded-lg bg-secondary px-3 py-1.5 text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:[l("settings.cleanup.dbSizeLabel"),": "]}),e.jsx("span",{className:"font-semibold tabular-nums text-foreground",children:c})]})]}),e.jsx("div",{className:"rounded-lg bg-secondary px-4 py-3 text-xs text-muted-foreground",children:l("settings.cleanup.confirmCleanup")}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsx("div",{className:"rounded-xl border border-warning/30 bg-warning-bg p-5",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{variant:"warning",children:l("settings.cleanup.softLabel")}),e.jsx("p",{className:"text-sm font-medium",children:l("settings.cleanup.softTitle")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l("settings.cleanup.softDescription")}),e.jsx(T,{variant:"outline",onClick:i,disabled:s,className:"w-full sm:w-auto",children:l(s?"common.actions.cleaning":"common.actions.cleanup")})]})}),e.jsx("div",{className:"rounded-xl border border-destructive/30 bg-destructive/10 p-5 text-destructive",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{variant:"outline",className:"border-destructive/40 bg-destructive/10 text-destructive",children:l("settings.cleanup.hardLabel")}),e.jsx("p",{className:"text-sm font-medium",children:l("settings.cleanup.hardTitle")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l("settings.cleanup.clearAllWarning")}),e.jsx(T,{variant:"destructive",onClick:u,disabled:t,className:"w-full sm:w-auto",children:l(t?"settings.cleanup.clearingAll":"settings.cleanup.clearAll")})]})})]}),e.jsx("div",{className:"rounded-xl border border-border bg-secondary/40 p-5",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium",children:l("settings.cleanup.compactTitle")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l("settings.cleanup.compactDescription")})]}),e.jsx(T,{variant:"outline",onClick:a,disabled:o,className:"w-full sm:w-auto",children:l(o?"common.actions.compacting":"common.actions.compact")})]})})]})})}function ns({dirtyCount:s,protocolChangesPending:t,onReset:o,onSave:c,saving:a}){const{t:i}=E();return s===0?null:e.jsxs("div",{className:"sticky bottom-4 z-20 flex flex-col gap-3 rounded-xl bg-card border border-border px-6 py-5 shadow-[var(--surface-shadow-lg)] md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(I,{variant:"secondary",children:i("settings.overview.unsavedCount",{count:s})}),e.jsx("p",{className:"text-sm text-muted-foreground",children:i(t?"settings.toast.protocolRestartRequired":"modelManagement.actions.footerDirtyHint")})]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2 lg:flex lg:flex-wrap lg:items-center",children:[e.jsx(T,{variant:"outline",onClick:o,disabled:a,className:"w-full lg:w-auto",children:i("common.actions.reset")}),e.jsx(T,{onClick:c,disabled:a,className:"w-full lg:w-auto",children:i(a?"common.actions.saving":"common.actions.save")})]})]})}function ye({checked:s,className:t,hint:o,hintClassName:c,label:a,labelClassName:i,onCheckedChange:u}){return e.jsxs("div",{className:V("flex flex-col gap-3 rounded-xl bg-secondary p-4 sm:flex-row sm:items-center sm:justify-between",t),children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(f,{className:V("text-sm font-semibold text-foreground",i),children:a}),e.jsx("p",{className:V("text-xs text-muted-foreground",c),children:o})]}),e.jsx(Z,{checked:s,onCheckedChange:u,className:"self-start sm:self-auto"})]})}function ve({label:s,onChange:t,placeholder:o,value:c}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:s}),e.jsx(P,{value:c,onChange:a=>t(a.target.value),placeholder:o,className:"font-mono text-xs"})]})}const _={authStatusRequest(){return{url:"/api/auth/web",method:"GET"}},saveWebAuth:async s=>Kt(qt.post("/api/auth/web",s)),cleanupLogs:async()=>G({url:"/api/logs/cleanup",method:"POST"}),clearLogs:async()=>G({url:"/api/logs/clear",method:"POST"}),dbInfo:async()=>G({url:"/api/db/info",method:"GET"}),compactDb:async()=>G({url:"/api/db/compact",method:"POST"})};function is(){const{t:s}=E(),{pushToast:t}=Bt(),o=Vt(),[c,a]=m.useState(ke[0].id),i=m.useRef(new Map),u=m.useCallback(r=>{const x=i.current.get(r);x&&x.scrollIntoView({behavior:"smooth",block:"start"})},[]),n=m.useCallback(r=>x=>{x?i.current.set(r,x):i.current.delete(r)},[]),l=X(Y.config.info(),st.configInfoRequest()),g=X(Y.auth.web(),_.authStatusRequest()),O=W({mutationFn:_.saveWebAuth,successToast:()=>({title:s("settings.auth.toast.success")}),errorToast:r=>({title:s("settings.auth.toast.failure",{message:r.message})}),invalidateKeys:[Y.auth.web()]}),L=W({mutationFn:_.cleanupLogs,successToast:r=>({title:r.deleted>0?s("settings.toast.cleanupSuccess",{count:r.deleted}):s("settings.toast.cleanupNone")}),errorToast:r=>({title:s("settings.toast.cleanupFailure",{message:r.message})}),invalidateKeys:[["logs"],["dashboard"],["db"]]}),w=W({mutationFn:_.clearLogs,successToast:r=>({title:s("settings.toast.clearAllSuccess",{logs:r.deleted,metrics:r.metricsCleared})}),errorToast:r=>({title:s("settings.toast.clearAllFailure",{message:r.message})}),invalidateKeys:[["logs"],["stats"],["dashboard"],["db"]]}),K=X(Y.db.info(),{url:"/api/db/info",method:"GET"}),h=W({mutationFn:_.compactDb,successToast:()=>({title:s("settings.toast.compactSuccess.title"),description:s("settings.toast.compactSuccess.desc")}),errorToast:r=>({title:s("settings.toast.compactFailure",{message:r.message})}),invalidateKeys:[Y.db.info(),["dashboard"]]}),[d,y]=m.useState(null),[k,R]=m.useState(""),[p,q]=m.useState({logRetentionDays:"",logExportTimeoutSeconds:"60",storeRequestPayloads:!0,storeResponsePayloads:!0,logLevel:"info",bodyLimitMb:"10",enableRoutingFallback:!1,httpEnabled:!0,httpPort:"4100",httpHost:"127.0.0.1",httpsEnabled:!1,httpsPort:"4443",httpsHost:"127.0.0.1",httpsKeyPath:"",httpsCertPath:"",httpsCaPath:""}),[nt,ee]=m.useState({}),[it,Re]=m.useState(!1),[lt,Ee]=m.useState(!1),[rt,Le]=m.useState(!1),[ot,ct]=m.useState(!1),[dt,ut]=m.useState(!1),[N,Ae]=m.useState(null),[b,$]=m.useState({enabled:!1,username:"",password:"",confirmPassword:""}),[mt,J]=m.useState({}),[pt,De]=m.useState(!1),[D,te]=m.useState({displayCurrency:"CNY",usdCnyRate:"7.2",overrides:[{key:"",currency:"CNY",input:"",output:"",cacheRead:"",cacheCreation:"",label:""}]}),[ht,se]=m.useState({}),xt=m.useMemo(()=>{if(!(d!=null&&d.defaults))return null;const r=[];return d.defaults.completion&&r.push(s("settings.defaults.completion",{model:d.defaults.completion})),d.defaults.reasoning&&r.push(s("settings.defaults.reasoning",{model:d.defaults.reasoning})),d.defaults.background&&r.push(s("settings.defaults.background",{model:d.defaults.background})),r.length>0?r.join(" | "):s("settings.defaults.none")},[d,s]),gt=m.useMemo(()=>p.httpEnabled&&p.httpsEnabled?s("settings.overview.values.httpAndHttps"):p.httpsEnabled?s("settings.overview.values.httpsOnly"):s("settings.overview.values.httpOnly"),[p.httpEnabled,p.httpsEnabled,s]),bt=m.useMemo(()=>b.enabled?N!=null&&N.hasPassword?b.username.trim()!==(N.username??""):!0:!1,[b.enabled,b.username,N]),B=m.useMemo(()=>d?be(d):null,[d]),ae=m.useMemo(()=>B?JSON.stringify(p)!==JSON.stringify(B):!1,[p,B]),ne=m.useMemo(()=>N?fe(N):null,[N]),ie=m.useMemo(()=>ne?JSON.stringify(b)!==JSON.stringify(ne):!1,[b,ne]),le=m.useMemo(()=>d?ge(d):null,[d]),U=m.useMemo(()=>le?JSON.stringify(D)!==JSON.stringify(le):!1,[D,le]),ft=m.useMemo(()=>B?["httpEnabled","httpPort","httpHost","httpsEnabled","httpsPort","httpsHost","httpsKeyPath","httpsCertPath","httpsCaPath"].some(x=>p[x]!==B[x]):!1,[p,B]);m.useEffect(()=>{l.data&&(y(l.data.config),R(l.data.path),q(be(l.data.config)),te(ge(l.data.config)),se({}))},[l.data]),m.useEffect(()=>{g.data&&(Ae(g.data),$(fe(g.data)),J({}))},[g.data]),m.useEffect(()=>{!l.isError||!l.error||t({title:s("settings.toast.loadFailure",{message:l.error.message}),variant:"error"})},[l.error,l.isError,t,s]),m.useEffect(()=>{!g.isError||!g.error||t({title:s("settings.toast.authLoadFailure",{message:g.error.message}),variant:"error"})},[g.error,g.isError,t,s]);const yt=m.useCallback(r=>x=>{q(C=>({...C,[r]:x}))},[]),Te=m.useCallback(()=>{const r={};!p.httpEnabled&&!p.httpsEnabled&&(r.protocol=s("settings.validation.protocolRequired"));const x=Number(p.httpPort);if((!Number.isFinite(x)||x<1||x>65535)&&(r.httpPort=s("settings.validation.httpPort")),p.httpsEnabled){const M=Number(p.httpsPort);(!Number.isFinite(M)||M<1||M>65535)&&(r.httpsPort=s("settings.validation.httpsPort")),(!p.httpsKeyPath||!p.httpsCertPath)&&(r.protocol=s("settings.validation.httpsCertificate"))}const C=Number(p.logRetentionDays);(!Number.isFinite(C)||C<1||C>365)&&(r.logRetentionDays=s("settings.validation.retention"));const v=Number(p.logExportTimeoutSeconds);(!Number.isFinite(v)||v<5||v>600)&&(r.logExportTimeoutSeconds=s("settings.validation.logExportTimeout"));const S=Number(p.bodyLimitMb);return(!Number.isFinite(S)||S<1||S>2048)&&(r.bodyLimitMb=s("settings.validation.bodyLimit")),ee(r),Object.keys(r).length===0},[p,s]),Fe=m.useCallback(()=>{const r={},x=b.username.trim(),C=N?x!==(N.username??""):!0,v=b.enabled&&(!(N!=null&&N.hasPassword)||C);return b.enabled&&!x&&(r.username=s("settings.auth.validation.username")),b.password&&b.password.length<6&&(r.password=s("settings.auth.validation.minLength")),v&&!b.password&&(r.password=s("settings.auth.validation.passwordRequired")),(b.password||b.confirmPassword)&&b.password!==b.confirmPassword&&(r.confirmPassword=s("settings.auth.validation.confirmMismatch")),J(r),Object.keys(r).length===0},[b,N,s]),Oe=m.useCallback(()=>{const r={},x=Number(D.usdCnyRate);(!Number.isFinite(x)||x<=0||x>1e4)&&(r.usdCnyRate=s("billing.validation.rate")),r.overrides=D.overrides.map(v=>{if(!at(v))return;const S={};if(!v.key.trim())S.key=s("billing.validation.keyRequired");else{const A=v.key.trim(),Q=A.indexOf(":");(Q===0||Q===A.length-1)&&(S.key=s("billing.validation.keyFormat"))}return[v.input,v.output,v.cacheRead,v.cacheCreation].some(A=>A.trim()!==""&&(!Number.isFinite(Number(A))||Number(A)<0))&&(S.prices=s("billing.validation.prices")),Object.keys(S).length>0?S:void 0});const C=r.overrides.some(Boolean);return se(r),!r.usdCnyRate&&!C},[D,s]),re=m.useCallback(async()=>{var r,x,C,v,S,M,A,Q,Me,He,Ke,qe,Be,Ue,Ye,Ve,Ie,Qe,_e,ze,$e,Je,Ge,We,Xe,Ze;if(!d){t({title:s("settings.toast.loadFailure",{message:s("settings.toast.missingConfig")}),variant:"error"});return}if(Te()&&Oe()){Re(!0);try{const me=Number(p.logRetentionDays),kt=Number(p.logExportTimeoutSeconds),St=Number(p.bodyLimitMb),j={...d,http:{enabled:p.httpEnabled,port:Number(p.httpPort),host:p.httpHost.trim()||"127.0.0.1"},https:{enabled:p.httpsEnabled,port:Number(p.httpsPort),host:p.httpsHost.trim()||"127.0.0.1",keyPath:p.httpsKeyPath.trim(),certPath:p.httpsCertPath.trim(),caPath:p.httpsCaPath.trim()||void 0},port:Number(p.httpPort),host:p.httpHost.trim()||void 0,logRetentionDays:me,logExportTimeoutSeconds:Math.min(Math.max(Math.round(kt),5),600),storeRequestPayloads:p.storeRequestPayloads,storeResponsePayloads:p.storeResponsePayloads,logLevel:p.logLevel,bodyLimit:Math.max(1,Math.floor(St*1024*1024)),enableRoutingFallback:p.enableRoutingFallback,...U?{billing:Gt(D)}:{}};delete j.requestLogging,delete j.responseLogging;const et={...j};delete et.webAuth,await st.saveConfig(et),y({...j,webAuth:d.webAuth});const tt=pe=>(pe==null?void 0:pe.trim())||void 0,Rt=d.port??((r=d.http)==null?void 0:r.port)??4100,Et=j.port??((x=j.http)==null?void 0:x.port)??4100,Lt=((C=d.host)==null?void 0:C.trim())||((S=(v=d.http)==null?void 0:v.host)==null?void 0:S.trim())||"127.0.0.1",At=((M=j.host)==null?void 0:M.trim())||((Q=(A=j.http)==null?void 0:A.host)==null?void 0:Q.trim())||"127.0.0.1",Dt=Rt!==Et||Lt!==At||((Me=d.http)==null?void 0:Me.enabled)!==((He=j.http)==null?void 0:He.enabled)||((Ke=d.http)==null?void 0:Ke.port)!==((qe=j.http)==null?void 0:qe.port)||(((Be=d.http)==null?void 0:Be.host)??d.host??"127.0.0.1")!==(((Ue=j.http)==null?void 0:Ue.host)??j.host??"127.0.0.1")||((Ye=d.https)==null?void 0:Ye.enabled)!==((Ve=j.https)==null?void 0:Ve.enabled)||((Ie=d.https)==null?void 0:Ie.port)!==((Qe=j.https)==null?void 0:Qe.port)||(((_e=d.https)==null?void 0:_e.host)??d.host??"127.0.0.1")!==(((ze=j.https)==null?void 0:ze.host)??j.host??"127.0.0.1")||(($e=d.https)==null?void 0:$e.keyPath)!==((Je=j.https)==null?void 0:Je.keyPath)||((Ge=d.https)==null?void 0:Ge.certPath)!==((We=j.https)==null?void 0:We.certPath)||tt((Xe=d.https)==null?void 0:Xe.caPath)!==tt((Ze=j.https)==null?void 0:Ze.caPath);t({title:s(Dt?"settings.toast.protocolRestartRequired":"settings.toast.saveSuccess"),variant:"success"}),U&&(o.invalidateQueries({queryKey:["stats"]}),o.invalidateQueries({queryKey:["dashboard"]}),o.invalidateQueries({queryKey:["logs"]}),o.invalidateQueries({queryKey:["billing"]}),o.invalidateQueries({queryKey:["api-keys"]})),l.refetch()}catch(me){t({title:s("settings.toast.saveFailure",{message:Ut(me).message}),variant:"error"})}finally{Re(!1)}}},[D,d,l,p,U,t,o,s,Te,Oe]),oe=m.useCallback(()=>{d&&(q(be(d)),te(ge(d)),ee({}),se({}))},[d]),ce=m.useCallback(async()=>{if(Fe()){De(!0);try{const r={enabled:b.enabled,username:b.username.trim()||void 0};b.password&&(r.password=b.password);const x=await O.mutateAsync(r);x.auth&&(Ae(x.auth),$({enabled:x.auth.enabled,username:x.auth.username??"",password:"",confirmPassword:""}),J({})),g.refetch()}catch{}finally{De(!1)}}},[b,g,O,Fe]),de=m.useCallback(()=>{N&&($(fe(N)),J({}))},[N]),vt=m.useCallback(async()=>{(ae||U)&&await re(),ie&&await ce()},[ce,re,ie,U,ae]),jt=m.useCallback(()=>{oe(),de()},[de,oe]),Nt=m.useCallback(async()=>{if(!k){t({title:s("settings.toast.copyFailure",{message:s("settings.file.unknown")}),variant:"error"});return}try{await It(k),t({title:s("settings.toast.copySuccess"),variant:"success"})}catch(r){t({title:s("settings.toast.copyFailure",{message:r instanceof Error?r.message:"unknown"}),variant:"error"})}},[k,t,s]),Ct=m.useCallback(async()=>{Ee(!0);try{await L.mutateAsync()}catch{}finally{Ee(!1)}},[L]),wt=m.useCallback(async()=>{Le(!0);try{await w.mutateAsync()}catch{}finally{Le(!1)}},[w]),Pt=K.data?Qt(K.data.totalBytes??K.data.sizeBytes):"-",ue=l.isPending||!d&&l.isFetching;return m.useEffect(()=>{if(ue)return;const r=Array.from(i.current.values());if(r.length===0)return;const x=new IntersectionObserver(C=>{for(const v of C)if(v.isIntersecting){a(v.target.id);break}},{rootMargin:"-80px 0px -60% 0px",threshold:0});for(const C of r)x.observe(C);return()=>x.disconnect()},[ue]),{activeSection:c,authErrors:mt,authForm:b,authQuery:g,authSettings:N,billingErrors:ht,billingForm:D,clearingAll:rt,cleaning:lt,compacting:h.isPending,config:d,configPath:k,configQuery:l,confirmCleanupOpen:ot,confirmClearAllOpen:dt,dbSizeDisplay:Pt,defaultsSummary:xt,errors:nt,form:p,handleAuthReset:de,handleAuthSave:ce,handleCleanupLogs:Ct,handleClearAllLogs:wt,handleCompact:h.mutate,handleCopyPath:Nt,handleInputChange:yt,handleReset:oe,handleResetAll:jt,handleSave:re,handleSaveAll:vt,handleSectionClick:u,isAuthDirty:ie,isBillingDirty:U,isConfigDirty:ae,isLoading:ue,needsPassword:bt,protocolSummaryLabel:gt,protocolChangesPending:ft,saving:it,savingAuth:pt,sectionRefs:i,setAuthForm:$,setConfirmCleanupOpen:ct,setConfirmClearAllOpen:ut,setErrors:ee,setForm:q,setBillingForm:te,setSectionRef:n,t:s}}function Ps(){const{t:s}=E(),t=is(),o=Number(t.isConfigDirty)+Number(t.isAuthDirty)+Number(t.isBillingDirty),c=o>0,a=_t(({currentLocation:i,nextLocation:u})=>c&&i.pathname!==u.pathname);return m.useEffect(()=>{if(!c)return;const i=u=>{u.preventDefault(),u.returnValue=""};return window.addEventListener("beforeunload",i),()=>window.removeEventListener("beforeunload",i)},[c]),e.jsxs("div",{className:"flex flex-col gap-6",children:[e.jsx(Ht,{info:o>0?e.jsx("span",{className:"rounded-lg bg-warning-bg px-2.5 py-1 text-xs font-medium text-warning",children:s("settings.overview.unsavedCount",{count:o})}):null,status:t.protocolChangesPending?e.jsx("span",{className:"text-xs text-muted-foreground",children:s("settings.protocol.restartWarning")}):null,actions:null}),t.isLoading?e.jsx(Se,{label:s("common.loading")}):t.config?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-6 xl:grid-cols-[200px_minmax(0,1fr)]",children:[e.jsx(Wt,{activeSection:t.activeSection,onSelectSection:t.handleSectionClick}),e.jsxs("div",{className:"flex min-w-0 flex-col gap-6",children:[e.jsx(Xt,{defaultsSummary:t.defaultsSummary,errors:t.errors,form:t.form,onInputChange:t.handleInputChange,onSetForm:t.setForm,sectionRef:t.setSectionRef("section-basics")}),e.jsx(Zt,{errors:t.errors,form:t.form,onSetForm:t.setForm,protocolChangesPending:t.protocolChangesPending,sectionRef:t.setSectionRef("section-protocol")}),e.jsx(es,{authErrors:t.authErrors,authForm:t.authForm,authLoading:t.authQuery.isPending||!t.authSettings&&t.authQuery.isFetching,authSettings:t.authSettings,needsPassword:t.needsPassword,onSetAuthForm:t.setAuthForm,sectionRef:t.setSectionRef("section-security")}),e.jsx(ts,{errors:t.billingErrors,form:t.billingForm,onSetForm:t.setBillingForm,sectionRef:t.setSectionRef("section-billing")}),e.jsx(ss,{configPath:t.configPath,onCopyPath:()=>void t.handleCopyPath(),sectionRef:t.setSectionRef("section-config-file")}),e.jsx(as,{cleaning:t.cleaning,clearingAll:t.clearingAll,compacting:t.compacting,dbSizeDisplay:t.dbSizeDisplay,onCompact:t.handleCompact,onOpenCleanup:()=>t.setConfirmCleanupOpen(!0),onOpenClearAll:()=>t.setConfirmClearAllOpen(!0),sectionRef:t.setSectionRef("section-cleanup")})]})]}),e.jsx(ns,{dirtyCount:o,protocolChangesPending:t.protocolChangesPending,onReset:t.handleResetAll,onSave:()=>void t.handleSaveAll(),saving:t.saving||t.savingAuth})]}):e.jsx(F,{children:e.jsx(H,{className:"pt-6",children:e.jsx("p",{className:"text-sm font-medium text-destructive",children:s("settings.toast.missingConfig")})})}),e.jsx(xe,{open:t.confirmCleanupOpen,onOpenChange:i=>{!i&&!t.cleaning&&t.setConfirmCleanupOpen(!1)},title:s("settings.cleanup.confirmTitle"),description:s("settings.cleanup.confirmDescription"),confirmLabel:t.cleaning?s("common.actions.cleaning"):s("common.actions.cleanup"),cancelLabel:s("common.actions.cancel"),loading:t.cleaning,onConfirm:async()=>{await t.handleCleanupLogs(),t.setConfirmCleanupOpen(!1)}}),e.jsx(xe,{open:t.confirmClearAllOpen,onOpenChange:i=>{!i&&!t.clearingAll&&t.setConfirmClearAllOpen(!1)},title:s("settings.cleanup.clearAllTitle"),description:s("settings.cleanup.clearAllWarning"),confirmLabel:t.clearingAll?s("settings.cleanup.clearingAll"):s("settings.cleanup.clearAll"),cancelLabel:s("common.actions.cancel"),loading:t.clearingAll,onConfirm:async()=>{await t.handleClearAllLogs(),t.setConfirmClearAllOpen(!1)}}),e.jsx(xe,{open:a.state==="blocked",onOpenChange:i=>{!i&&a.state==="blocked"&&a.reset()},title:s("settings.unsaved.title"),description:s("settings.unsaved.body"),confirmLabel:s("settings.unsaved.confirm"),cancelLabel:s("common.actions.cancel"),onConfirm:()=>{a.state==="blocked"&&a.proceed()}})]})}export{Ps as default};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{j as e,a4 as Q,av as W,r as l}from"./vendor-JUtelXU0.js";import{B as g,t as S,L as ve,C as fe,l as ye,m as je,n as be,c as Ne}from"./app-CRxPj2SJ.js";import{c as K}from"./global-BLUcvOa8.js";import{L as N,I as P}from"./label-CdbE1ezd.js";import{u as Ce,E as Se}from"./shared-zfHsnBTk.js";import{u as C}from"./i18n-v60Yn7Ls.js";import{S as ke,a as Re,b as Ke,c as Pe,d as Te}from"./disclosure-CU-KJc8C.js";import{u as we,B as Me,M as Ie,T as Ae}from"./useProviderForm-DIuM3Z2u.js";import{C as Ee,u as He,g as Oe,m as Fe}from"./modelManagement-DwdbGu0o.js";import{a as Le}from"./apiKeys-CMk2nxB_.js";import{g as G}from"./gateway-DyhqzHSh.js";import{c as Ue}from"./clipboard-DqvcglYs.js";import{a as $e}from"./router-CqUBCAsx.js";import"./query-CvboQrUT.js";import"./radix-d0BukFWM.js";import"./switch-CZn1nypU.js";import"./badge-eRkhnmCs.js";const Be={complete:"border-foreground bg-foreground text-background",current:"border-foreground bg-card text-foreground ring-2 ring-foreground/15",error:"border-destructive bg-card text-destructive ring-2 ring-destructive/20",upcoming:"border-border bg-card text-muted-foreground"},De={complete:"text-foreground",current:"text-foreground font-medium",error:"text-destructive font-medium",upcoming:"text-muted-foreground"};function _e({steps:o,current:t,onSelect:n,className:r}){return e.jsx("nav",{"aria-label":"steps",className:K("flex items-start",r),children:o.map((s,d)=>{const m=n&&(s.status==="complete"||s.status==="current"),x=d===o.length-1,h=s.status==="complete"?"bg-foreground/30":"bg-border",u=e.jsx("span",{className:K("motion-surface flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border text-xs font-semibold",Be[s.status]),"aria-current":s.id===t?"step":void 0,children:s.status==="complete"?e.jsx(Q,{className:"h-3.5 w-3.5","aria-hidden":!0}):d+1}),p=`stepnav-${s.id}-label`;return e.jsxs("div",{className:"flex flex-1 items-start",children:[e.jsxs("div",{className:"flex min-w-0 flex-col items-center gap-1.5",children:[m?e.jsx("button",{type:"button",onClick:()=>n==null?void 0:n(s.id),"aria-labelledby":p,className:"rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-background motion-surface",children:u}):u,e.jsx("span",{id:p,className:K("text-center text-[11px] leading-tight",De[s.status]),children:s.label})]}),x?null:e.jsx("span",{"aria-hidden":!0,className:K("mx-1.5 mt-3.5 h-px flex-1",h)})]},s.id)})})}function Ve({state:o}){const{t}=C(),n=Ce(),{keyName:r,setKeyName:s,keyEndpoints:d,setKeyEndpoints:m,keyMaxConcurrency:x,setKeyMaxConcurrency:h,creatingKey:u,createdKey:p,createApiKey:v,copyCreatedKey:i}=o;return p?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-lg bg-success-bg text-success",children:e.jsx(Q,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsx("p",{className:"text-sm font-semibold",children:t("apiKeys.keyCreated")})]}),e.jsx("p",{className:"text-sm font-medium text-warning",children:t("apiKeys.saveKeyWarning")}),e.jsx("div",{className:"break-all rounded-lg border border-border bg-secondary px-4 py-3 font-mono text-sm",children:p.key}),e.jsx("div",{children:e.jsxs(g,{type:"button",variant:"outline",onClick:()=>void i(p.key),children:[e.jsx(W,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),t("common.actions.copy")]})})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(N,{htmlFor:"setupKeyName",children:[t("apiKeys.keyNamePlaceholder")," *"]}),e.jsx(P,{id:"setupKeyName",value:r,onChange:f=>s(f.target.value),placeholder:t("apiKeys.keyNamePlaceholder")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(N,{children:t("apiKeys.allowedEndpoints")}),e.jsx(Se,{available:n,selected:d,onChange:m,hint:t("apiKeys.selectEndpoints")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(N,{htmlFor:"setupMaxConcurrency",children:t("apiKeys.maxConcurrency")}),e.jsx(P,{id:"setupMaxConcurrency",type:"number",min:"0",value:x,onChange:f=>h(f.target.value),placeholder:t("apiKeys.maxConcurrencyPlaceholder")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t("apiKeys.maxConcurrencyHelper")})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(g,{type:"button",onClick:()=>void v(),disabled:u||r.trim().length===0,children:t(u?"setup.steps.apiKey.creating":"setup.steps.apiKey.create")})})]})}function qe({existingProviderIds:o,saving:t,onSave:n}){const{t:r}=C(),s=we({mode:"create",existingProviderIds:o}),d={form:s.form,errors:s.errors,isCreate:!0,advancedOpen:s.advancedOpen,onAdvancedOpenChange:s.setAdvancedOpen,idInputRef:s.providerIdRef,onProviderIdChange:s.handleProviderIdChange,onFieldChange:s.handleFieldChange,onTypeChange:s.handleTypeChange,onAuthModeChange:s.handleAuthModeChange,onNonStreamViaStreamChange:s.handleProviderNonStreamViaStreamChange,onUseAbsoluteUrlChange:s.handleUseAbsoluteUrlChange,onStreamUsageChange:s.handleStreamUsageChange,onAddHeader:s.handleAddHeader,onRemoveHeader:s.handleRemoveHeader,onHeaderChange:s.handleHeaderChange,onModelIdChange:s.handleModelIdChange,onModelChange:s.handleModelChange,onAddModel:s.handleAddModel,onRemoveModel:s.handleRemoveModel,onModelNonStreamViaStreamChange:s.handleModelNonStreamViaStreamChange,onSetDefaultModel:s.handleSetDefaultModel},m=()=>{s.validate()&&n(s.serialize())};return e.jsxs("div",{className:"space-y-8",children:[e.jsx(Me,{...d}),e.jsx(Ie,{...d}),e.jsx("div",{className:"flex justify-end",children:e.jsx(g,{type:"button",onClick:m,disabled:t,children:r(t?"common.actions.saving":"setup.steps.provider.saveAndContinue")})})]})}function ze({state:o,onSaved:t}){const{t:n}=C(),{providers:r,setupProvider:s,setSetupProviderId:d,savingProvider:m,saveProvider:x}=o,[h,u]=l.useState(null),p=h??r.length===0,v=i=>{x(i).then(f=>{f&&t()})};return e.jsxs("div",{className:"space-y-6",children:[r.length>0?e.jsxs("div",{className:"space-y-3 rounded-xl bg-secondary/50 p-4",children:[e.jsx("p",{className:"text-sm font-semibold",children:n("setup.steps.provider.existingTitle",{count:r.length})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:n("setup.steps.provider.existingHint")}),e.jsxs(N,{className:"flex flex-col gap-2 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:n("setup.steps.provider.chooseLabel")}),e.jsxs(ke,{value:(s==null?void 0:s.id)??"",onValueChange:d,children:[e.jsx(Re,{children:e.jsx(Ke,{})}),e.jsx(Pe,{children:r.map(i=>e.jsx(Te,{value:i.id,children:i.label||i.id},i.id))})]})]})]}):null,p?e.jsx(qe,{existingProviderIds:r.map(i=>i.id),saving:m,onSave:v}):e.jsx("div",{children:e.jsx(g,{type:"button",variant:"outline",onClick:()=>u(!0),children:n("setup.steps.provider.addAnother")})}),p&&r.length>0?e.jsx("div",{children:e.jsx(g,{type:"button",variant:"ghost",size:"sm",onClick:()=>u(!1),children:n("setup.steps.provider.backToList")})}):null]})}const Ge=Ee.slice(0,3);function Qe({state:o}){const{t}=C(),{setupProvider:n,anthropicRoutes:r,routeSource:s,setRouteSource:d,routeTarget:m,setRouteTarget:x,savingRoute:h,saveDefaultRoute:u}=o,p=Object.entries(r),v=!!n&&s.trim().length>0&&m.trim().length>0&&!h;return e.jsxs("div",{className:"space-y-6",children:[p.length>0?e.jsxs("section",{className:"space-y-3","aria-labelledby":"setup-existing-routes",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{id:"setup-existing-routes",className:"text-sm font-semibold",children:t("setup.steps.routing.existingTitle")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t("setup.steps.routing.existingHint")})]}),e.jsx("div",{className:"divide-y divide-border rounded-xl border border-border",children:p.map(([i,f])=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 px-4 py-2.5 text-xs",children:[e.jsx("code",{className:"font-mono text-foreground",children:i}),e.jsxs("code",{className:"font-mono text-muted-foreground",children:["→ ",f]})]},i))})]}):e.jsx("p",{className:"rounded-xl bg-secondary/50 px-4 py-3 text-xs text-muted-foreground",children:t("setup.steps.routing.emptyHint")}),e.jsxs("section",{className:"space-y-4","aria-labelledby":"setup-new-route",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs(N,{className:"flex flex-col gap-2 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:t("setup.steps.routing.sourceLabel")}),e.jsx(P,{value:s,onChange:i=>d(i.target.value)})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:Ge.map(i=>e.jsx(g,{type:"button",variant:"outline",size:"sm",className:"h-7 rounded-md px-2.5 text-[11px] font-normal",onClick:()=>d(i),children:i},i))}),e.jsx("p",{className:"text-xs leading-5 text-muted-foreground",children:t("setup.steps.routing.sourceHint")})]}),e.jsxs(N,{className:"flex flex-col gap-2 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:t("setup.steps.routing.targetLabel")}),e.jsx(P,{value:m,onChange:i=>x(i.target.value)})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(g,{type:"button",onClick:()=>void u(),disabled:!v,children:t(h?"setup.steps.routing.saving":"setup.steps.routing.save")})})]})]})}function We({state:o}){const{t}=C(),{setupProvider:n,testingProvider:r,testResult:s,testSetupProvider:d,anthropicBaseUrl:m,createdKey:x,copyCreatedKey:h}=o;if(!n)return e.jsx("p",{className:"rounded-xl bg-secondary/50 px-4 py-3 text-xs text-muted-foreground",children:t("setup.steps.verify.noProvider")});const u=[`export ANTHROPIC_BASE_URL=${m}`,`export ANTHROPIC_API_KEY=${(x==null?void 0:x.key)??"<your-api-key>"}`].join(`
|
|
2
|
+
`);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("section",{className:"space-y-3","aria-labelledby":"setup-verify-connection",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{id:"setup-verify-connection",className:"text-sm font-semibold",children:t("workbench.drawer.verifyTitle")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t("setup.steps.verify.testingProvider",{name:n.label||n.id})})]}),e.jsxs("div",{className:"space-y-3 rounded-xl border border-transparent bg-card p-4 shadow-[var(--surface-shadow)]",children:[e.jsx(g,{type:"button",variant:"outline",size:"sm",onClick:()=>void d(),disabled:r,children:t(r?"common.actions.testingConnection":"workbench.drawer.verifyRun")}),s?e.jsx(Ae,{result:s}):null]})]}),e.jsxs("section",{className:"space-y-3","aria-labelledby":"setup-verify-first-request",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{id:"setup-verify-first-request",className:"text-sm font-semibold",children:t("setup.steps.verify.envTitle")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t("setup.steps.verify.envHint")})]}),e.jsx("pre",{className:"overflow-x-auto rounded-lg border border-border bg-secondary px-4 py-3 font-mono text-xs",children:u}),e.jsx("div",{children:e.jsxs(g,{type:"button",variant:"outline",size:"sm",onClick:()=>void h(u),children:[e.jsx(W,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),t("common.actions.copy")]})})]})]})}const k=["provider","routing","apiKey","verify"];function Ye(){var D;const o=He(),{t,pushToast:n,config:r,setConfig:s,configQuery:d,customEndpoints:m,ensureConfig:x}=o,h=$e(),[u,p]=l.useState(0),[v,i]=l.useState(null),[f,A]=l.useState(!1),[E,Y]=l.useState(""),[J,X]=l.useState(null),[Z,H]=l.useState(!1),[T,ee]=l.useState(""),[w,te]=l.useState(["anthropic"]),[O,se]=l.useState(""),[re,F]=l.useState(!1),[L,ae]=l.useState(null),[ne,U]=l.useState(!1),[oe,M]=l.useState(null),b=l.useMemo(()=>(r==null?void 0:r.providers)??[],[r]),y=l.useMemo(()=>b.find(a=>a.id===v)??b[0]??null,[b,v]),I=l.useMemo(()=>r?Oe(r,m,"anthropic"):{},[r,m]),$=Object.keys(I).length,ie=l.useMemo(()=>{var c,j;if(!y)return"";const a=y.defaultModel??((j=(c=y.models)==null?void 0:c.find(R=>R.id.trim().length>0))==null?void 0:j.id);return a?`${y.id}:${a}`:`${y.id}:*`},[y]),B=J??ie,ce=async a=>{if(!r||!x())return!1;const c={...r,providers:[...b,a]};A(!0);try{return await G.saveConfig(c),s(c),d.refetch(),i(a.id),n({title:t("providers.toast.createSuccess",{name:a.label||a.id}),variant:"success"}),!0}catch(j){return n({title:t("providers.drawer.toast.saveFailure",{message:S(j).message}),variant:"error"}),!1}finally{A(!1)}},de=async()=>{var _,V,q,z;if(!r||!x())return;const a=E.trim(),c=B.trim();if(!a||!c)return;const j={...I,[a]:c},R={...r,endpointRouting:{...r.endpointRouting??{},anthropic:{defaults:((V=(_=r.endpointRouting)==null?void 0:_.anthropic)==null?void 0:V.defaults)??r.defaults,modelRoutes:j,compatibility:(z=(q=r.endpointRouting)==null?void 0:q.anthropic)==null?void 0:z.compatibility}},modelRoutes:j};H(!0);try{await G.saveConfig(R),s(R),d.refetch(),n({title:t("modelManagement.toast.routesSaved"),variant:"success"})}catch(ge){n({title:t("modelManagement.toast.routesSaveFailure",{message:S(ge).message}),variant:"error"})}finally{H(!1)}},le=async()=>{if(!T.trim()){n({title:t("apiKeys.errors.nameRequired"),variant:"error"});return}const a=O.trim();if(a&&(!Number.isInteger(Number(a))||Number(a)<0)){n({title:t("apiKeys.errors.maxConcurrencyInvalid"),variant:"error"});return}F(!0);try{const c=await Le.create({name:T.trim(),allowedEndpoints:w.length>0?w:void 0,maxConcurrency:Number(a)>0?Number(a):null});ae(c)}catch(c){const j=S(c);n({title:t("setup.steps.apiKey.createFailed",{message:j.message}),variant:"error"})}finally{F(!1)}},ue=async a=>{try{await Ue(a),n({title:t("apiKeys.toast.keyCopied"),variant:"success"})}catch(c){n({title:t("apiKeys.toast.copyFailure"),description:S(c).message,variant:"error"})}},pe=async()=>{if(y){U(!0);try{const a=await Fe.testProvider(y.id);if(a.ok){M({ok:!0,status:a.status,statusText:a.statusText,durationMs:a.durationMs,testedAt:Date.now()});return}M({ok:!1,status:a.status,statusText:a.statusText,durationMs:a.durationMs,message:`${a.status} ${a.statusText}`,testedAt:Date.now()})}catch(a){const c=S(a);M({ok:!1,status:c.status,message:c.status?`${c.status} ${c.message}`:c.message,testedAt:Date.now()})}finally{U(!1)}}},me=`http://127.0.0.1:${((D=r==null?void 0:r.http)==null?void 0:D.port)??(r==null?void 0:r.port)??4100}/anthropic`,xe=k[u],he={provider:b.length>0,routing:$>0,apiKey:L!==null,verify:!0};return{...o,stepIndex:u,activeStep:xe,canProceed:he,goNext:()=>{p(a=>Math.min(a+1,k.length-1))},goBack:()=>{p(a=>Math.max(a-1,0))},goToStep:a=>{const c=k.indexOf(a);c>=0&&c<=u&&p(c)},finish:()=>{h("/")},providers:b,setupProvider:y,setupProviderId:v,setSetupProviderId:i,savingProvider:f,saveProvider:ce,anthropicRoutes:I,anthropicRouteCount:$,routeSource:E,setRouteSource:Y,routeTarget:B,setRouteTarget:X,savingRoute:Z,saveDefaultRoute:de,keyName:T,setKeyName:ee,keyEndpoints:w,setKeyEndpoints:te,keyMaxConcurrency:O,setKeyMaxConcurrency:se,creatingKey:re,createdKey:L,createApiKey:le,copyCreatedKey:ue,testingProvider:ne,testResult:oe,testSetupProvider:pe,anthropicBaseUrl:me}}function yt(){const{t:o}=C(),t=Ye();if(t.configQuery.isPending&&!t.config)return e.jsx(ve,{});const n=k.map((s,d)=>({id:s,label:o(`setup.steps.${s}.navLabel`),status:d<t.stepIndex?"complete":d===t.stepIndex?"current":"upcoming"})),r=t.stepIndex===k.length-1;return e.jsxs("div",{className:"mx-auto flex w-full max-w-3xl flex-col gap-6",children:[e.jsxs("header",{className:"space-y-1.5",children:[e.jsx("h1",{className:"text-xl font-semibold tracking-[-0.02em]",children:o("setup.title")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:o("setup.description")})]}),e.jsx(_e,{steps:n,current:t.activeStep,onSelect:t.goToStep}),e.jsxs(fe,{children:[e.jsxs(ye,{children:[e.jsx(je,{children:o(`setup.steps.${t.activeStep}.title`)}),e.jsx(be,{children:o(`setup.steps.${t.activeStep}.description`)})]}),e.jsxs(Ne,{children:[t.activeStep==="provider"?e.jsx(ze,{state:t,onSaved:t.goNext}):null,t.activeStep==="routing"?e.jsx(Qe,{state:t}):null,t.activeStep==="apiKey"?e.jsx(Ve,{state:t}):null,t.activeStep==="verify"?e.jsx(We,{state:t}):null]})]}),e.jsxs("footer",{className:"flex items-center justify-between",children:[e.jsx(g,{type:"button",variant:"outline",onClick:t.goBack,disabled:t.stepIndex===0,children:o("common.actions.previous")}),r?e.jsx(g,{type:"button",onClick:t.finish,children:o("setup.actions.finish")}):e.jsx(g,{type:"button",onClick:t.goNext,disabled:!t.canProceed[t.activeStep],children:o("common.actions.next")})]})]})}export{yt as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as l,j as s,a3 as J}from"./vendor-JUtelXU0.js";import{P as Q,c as U,b as V}from"./popover-CuM9b3U7.js";import{I as S}from"./label-CdbE1ezd.js";import{B}from"./badge-eRkhnmCs.js";import{a as W,s as X}from"./app-CRxPj2SJ.js";import{c as h}from"./global-BLUcvOa8.js";import{u as Y}from"./i18n-v60Yn7Ls.js";const P=3;function oe({value:v,onChange:C,options:c,disabled:F,placeholder:G,ariaLabel:A}){const{t:a}=Y(),I=l.useId(),[m,d]=l.useState(!1),[p,u]=l.useState(""),[$,L]=l.useState(null),R=l.useRef(null),f=l.useRef(!1),[g,K]=W(X.modelManagement.recentRouteTargets,[]),b=l.useMemo(()=>{const e=new Map;for(const t of c)e.set(t.value,t);return e},[c]),T=(e,t)=>t?[e.label,e.value,e.providerId??"",e.providerLabel??"",e.modelId??"",e.modelLabel??""].join(" ").toLowerCase().includes(t):!0,{providerGroups:H,customOptions:k}=l.useMemo(()=>{const e=new Map,t=[];for(const r of c){if(r.kind==="custom"||!r.providerId){t.push(r);continue}const o=`provider:${r.providerId}`,i=e.get(o);i?i.options.push(r):e.set(o,{key:o,label:r.providerLabel??r.providerId,options:[r]})}return{providerGroups:[...e.values()],customOptions:t}},[c]),y=p.trim().length>0,E=l.useMemo(()=>{const e=p.trim().toLowerCase(),t=c.filter(n=>T(n,e)),r=g.map(n=>b.get(n)??(e?void 0:{value:n,label:n,kind:"custom"})).filter(n=>!!n).filter(n=>T(n,e)).slice(0,P),o=[];r.length>0&&o.push({key:"recent",label:a("modelManagement.targetPicker.recent"),options:r});const i=[],N=new Map;for(const n of t){if(n.kind==="custom"||!n.providerId){i.push(n);continue}const M=`provider:${n.providerId}`,D=N.get(M);D?D.options.push(n):N.set(M,{key:M,label:n.providerLabel??n.providerId,options:[n]})}return o.push(...N.values()),i.length>0&&o.push({key:"custom",label:a("modelManagement.targetPicker.custom"),options:i,muted:!0}),o},[b,c,g,p,a]),O=E.reduce((e,t)=>e+t.options.length,0),q=e=>{C(e),K(t=>[e,...t.filter(r=>r!==e)].slice(0,P)),u(""),f.current=!0,typeof document<"u"&&document.activeElement instanceof HTMLElement&&document.activeElement.blur(),d(!1),typeof window<"u"?window.requestAnimationFrame(()=>{f.current=!1}):f.current=!1},z=e=>e.kind==="passthrough"?a("modelManagement.targetPicker.passthrough"):e.kind==="custom"?a("modelManagement.targetPicker.customValue"):a("modelManagement.targetPicker.model"),_=e=>e.kind==="passthrough"||e.kind==="custom"?e.label:e.modelLabel??e.label,x=(e,t,r=!1)=>s.jsxs("button",{type:"button",role:"option","aria-selected":t.value===v.trim(),className:h("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",r&&"pl-7",t.value===v.trim()&&"bg-accent text-accent-foreground"),onMouseDown:o=>{o.preventDefault()},onClick:()=>q(t.value),children:[s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block truncate font-medium",children:_(t)}),s.jsx("span",{className:"block truncate text-xs text-muted-foreground",children:t.value})]}),s.jsxs("span",{className:"flex shrink-0 items-center gap-1",children:[t.isDefault?s.jsx(B,{variant:"secondary",className:"text-[10px]",children:a("modelManagement.targetPicker.default")}):null,s.jsx(B,{variant:t.kind==="passthrough"?"outline":"secondary",className:"text-[10px]",children:z(t)})]})]},`${e.key}-${t.value}`),j=e=>s.jsxs("div",{className:h("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",e.muted&&"opacity-80"),children:[s.jsx("span",{className:"truncate",children:e.label}),s.jsx("span",{children:e.options.length})]}),w=g.map(e=>b.get(e)??{value:e,label:e,kind:"custom"}).slice(0,P);return s.jsxs(Q,{open:m,onOpenChange:e=>{e&&f.current||(d(e),e&&(u(""),L(null)))},children:[s.jsx(U,{asChild:!0,children:s.jsx(S,{value:v,onChange:e=>{C(e.target.value),u(e.target.value),m||d(!0)},onFocus:()=>{u(""),d(!0)},onClick:()=>{m||d(!0)},placeholder:G,disabled:F,autoComplete:"off",role:"combobox","aria-label":A,"aria-expanded":m,"aria-controls":I,"aria-autocomplete":"list"})}),s.jsxs(V,{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:e=>{var t;e.preventDefault(),(t=R.current)==null||t.focus()},onCloseAutoFocus:e=>{e.preventDefault()},children:[s.jsxs("div",{className:"space-y-2 border-b border-border px-3 py-3",children:[s.jsx(S,{ref:R,value:p,onChange:e=>u(e.target.value),placeholder:a("modelManagement.targetPicker.searchPlaceholder"),className:"h-9",autoComplete:"off"}),s.jsx("div",{className:"text-xs text-muted-foreground",children:y?a("modelManagement.targetPicker.matchCount",{count:O}):a("modelManagement.targetPicker.helper")})]}),y&&O===0?s.jsx("div",{className:"px-3 py-4 text-center text-xs text-muted-foreground",children:a("common.noMatches")}):s.jsx("div",{id:I,role:"listbox",className:"min-h-0 flex-1 overflow-y-auto p-1.5",children:y?E.map(e=>s.jsxs("div",{className:"py-1",children:[j(e),s.jsx("div",{className:"space-y-1",children:e.options.map(t=>x(e,t))})]},e.key)):s.jsxs(s.Fragment,{children:[w.length>0?s.jsxs("div",{className:"py-1",children:[j({label:a("modelManagement.targetPicker.recent"),options:w}),s.jsx("div",{className:"space-y-1",children:w.map(e=>x({key:"recent"},e))})]}):null,s.jsx("div",{className:"py-1",children:H.map(e=>{const t=$===e.key;return s.jsxs("div",{children:[s.jsxs("button",{type:"button","aria-expanded":t,className:h("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",t&&"bg-accent text-accent-foreground"),onMouseDown:r=>{r.preventDefault()},onClick:()=>L(t?null:e.key),children:[s.jsx(J,{className:h("h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform",t&&"rotate-90"),"aria-hidden":!0}),s.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:e.label}),s.jsx("span",{className:"shrink-0 text-xs tabular-nums text-muted-foreground",children:a("modelManagement.targetPicker.modelCount",{count:e.options.length})})]}),t?s.jsx("div",{className:"space-y-1 pb-1",children:e.options.map(r=>x(e,r,!0))}):null]},e.key)})}),k.length>0?s.jsxs("div",{className:"py-1",children:[j({label:a("modelManagement.targetPicker.custom"),options:k,muted:!0}),s.jsx("div",{className:"space-y-1",children:k.map(e=>x({key:"custom"},e))})]}):null]})})]})]})}export{oe as T};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as p,e as s,d as t}from"./app-CRxPj2SJ.js";const u={listRequest(){return{url:"/api/keys",method:"GET"}},overviewRequest(e){return{url:"/api/stats/api-keys/overview",method:"GET",params:{days:e}}},usageRequest(e,a=10,r){return{url:"/api/stats/api-keys/usage",method:"GET",params:{days:e,limit:a,...r?{endpoint:r}:{}}}},customEndpointOptionsRequest(){return{url:"/api/custom-endpoints",method:"GET"}},create:async e=>s(t.post("/api/keys",e)),update:async(e,a)=>{await s(t.patch(`/api/keys/${e}`,a))},delete:async e=>{await s(t.delete(`/api/keys/${e}`))},reveal:async e=>p({url:`/api/keys/${e}/reveal`,method:"GET"})};export{u as a};
|