@chenpu17/cc-gw 0.9.1 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +5 -5
- package/src/web/dist/assets/{About-BSEe89Db.js → About-BxrAYtQE.js} +1 -1
- package/src/web/dist/assets/{ApiKeys-BSd06Z1F.js → ApiKeys-DNQRKCib.js} +1 -1
- package/src/web/dist/assets/{ConfirmDialog-MHzJAg_R.js → ConfirmDialog-Bcxn6dph.js} +1 -1
- package/src/web/dist/assets/{Dashboard-BTnS3Joq.js → Dashboard-B6ICHOzw.js} +1 -1
- package/src/web/dist/assets/{Events-DbCJcwIJ.js → Events-C2uIO71I.js} +1 -1
- package/src/web/dist/assets/{Help-BsB7et-K.js → Help-DNYnXBdr.js} +1 -1
- package/src/web/dist/assets/{Login-C8phChBf.js → Login-BG51iO51.js} +1 -1
- package/src/web/dist/assets/Logs-DFsyxG6w.js +1 -0
- package/src/web/dist/assets/{ProvidersWorkbench-Bb3ZnLKq.js → ProvidersWorkbench-CQs_hU5D.js} +1 -1
- package/src/web/dist/assets/{Settings-DE727ml-.js → Settings-BxLEMKHc.js} +1 -1
- package/src/web/dist/assets/{Setup-DPWSztq9.js → Setup-xJZtt7MZ.js} +1 -1
- package/src/web/dist/assets/{apiKeys-Ysiv6YG4.js → apiKeys-CdpEo7b1.js} +1 -1
- package/src/web/dist/assets/app-yrdXegKB.js +61 -0
- package/src/web/dist/assets/{gateway-D48923x2.js → gateway-BGQ7-G-T.js} +1 -1
- package/src/web/dist/assets/{landing-CXAblwjd.js → landing-CYc---DE.js} +1 -1
- package/src/web/dist/assets/package-CR4pXT18.js +1 -0
- package/src/web/dist/assets/{shared-BzrM3juK.js → shared-Cj-4uVgO.js} +1 -1
- package/src/web/dist/assets/{useAppMutation-B4G9utID.js → useAppMutation-CaROpU2i.js} +1 -1
- package/src/web/dist/assets/useProviderForm-BDM7-9ut.js +1 -0
- package/src/web/dist/index.html +1 -1
- package/src/web/dist/landing.html +2 -2
- package/src/web/dist/assets/Logs-Cj6iucOs.js +0 -1
- package/src/web/dist/assets/app-ClWj0qTa.js +0 -61
- package/src/web/dist/assets/package-C1LS7ceb.js +0 -1
- package/src/web/dist/assets/useProviderForm-Bh-rUNZP.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as x,j as e,o as cs,ar as us,aj as ms,as as ps,ak as De,at as Te,aq as xs,au as gs,Z as fs,T as hs,P as ys}from"./vendor-CITafuNQ.js";import{P as bs}from"./PageToolbar-BdMtFJ0X.js";import{c as E}from"./global-CHsQhrWl.js";import{B as R,d as js,a as fe,c as G,q as H,s as P,t as vs,b as A}from"./app-yrdXegKB.js";import{B as V}from"./badge-BYKFKxPI.js";import{C as Fe,a as Ke}from"./card-BzBD4ugM.js";import{L as B,I as xe}from"./label-D10XnuKJ.js";import{S as te,a as le,b as ae,c as re,d as $}from"./select-Csn9x4DW.js";import{u as I}from"./i18n-PeX9kBVO.js";import{D as ws,A as Ns,a as ks,b as Ss,c as Cs,d as Ls}from"./DialogShell-Dadn4IyM.js";import{P as _s,a as Y}from"./PageState-BfMFsTrq.js";import{T as Es,a as Rs,b as Ds,c as Ts}from"./tabs-BkwWF2Pt.js";import{c as Fs}from"./clipboard-BnAnBk_-.js";import{a as Ks,g as he,b as Me,f as O,c as ye,d as Ms,e as q,h as Pe,i as qe,j as Ps,T as qs}from"./utils-CERcr-xC.js";import{P as zs,a as As,b as Os}from"./popover-CVazrITd.js";import{S as Is}from"./segmented-control-BDDSq6CX.js";import{S as $s}from"./switch-CgcoKdbt.js";import{L as ze}from"./router-BoBrmro7.js";import{a as Qs}from"./query-DZF7K6hv.js";import{g as _e}from"./gateway-BGQ7-G-T.js";import"./radix-Bux_1C5J.js";function Us({apiKeys:s,selected:l,onChange:p,disabled:a,className:o}){const{t}=I(),i=x.useId(),[b,h]=x.useState(!1),[d,v]=x.useState(null),y=x.useRef(null),w=x.useRef(null),m=x.useRef(null),N=()=>{const f=w.current;if(!f)return;const j=f.getBoundingClientRect(),S=Math.max(j.width,256),n=window.innerWidth-12;v({left:Math.min(j.left,n-S),top:j.bottom+8,width:S})};x.useEffect(()=>{if(!b)return;const f=S=>{var C,D;const n=S.target;!((C=y.current)!=null&&C.contains(n))&&!((D=m.current)!=null&&D.contains(n))&&h(!1)},j=S=>{var n;S.key==="Escape"&&(h(!1),(n=w.current)==null||n.focus())};return window.addEventListener("mousedown",f),window.addEventListener("keydown",j),()=>{window.removeEventListener("mousedown",f),window.removeEventListener("keydown",j)}},[b]),x.useEffect(()=>{if(b)return N(),window.addEventListener("resize",N),window.addEventListener("scroll",N,!0),()=>{window.removeEventListener("resize",N),window.removeEventListener("scroll",N,!0)}},[b]);const r=x.useMemo(()=>{if(l.length===0)return[];const f=new Map;for(const j of s)f.set(j.id,j);return l.map(j=>{const S=f.get(j);return S?S.isWildcard?t("apiKeys.wildcard"):S.name:null}).filter(j=>!!j)},[s,l,t]),g=l.length===0?t("logs.filters.apiKeyAll"):t("logs.filters.apiKeySelected",{count:l.length}),L=f=>{l.includes(f)?p(l.filter(j=>j!==f)):p([...l,f])};return e.jsxs("div",{className:E("relative space-y-2",o),ref:y,children:[e.jsx(B,{htmlFor:i,children:t("logs.filters.apiKey")}),e.jsxs("button",{ref:w,id:i,type:"button",onClick:()=>{N(),h(f=>!f)},disabled:a||s.length===0,title:t("logs.filters.apiKeyHint"),className:E("flex h-10 w-full items-center justify-between rounded-lg border border-input bg-background px-3 text-sm ring-offset-background transition-all focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",l.length>0&&"border-primary",b&&"ring-2 ring-ring ring-offset-2"),children:[e.jsxs("span",{className:"truncate",children:[g,r.length>0&&e.jsx("span",{className:"ml-1 text-xs text-muted-foreground",children:r.join(", ")})]}),e.jsx("svg",{className:E("h-4 w-4 opacity-50 transition-transform",b&&"rotate-180"),viewBox:"0 0 20 20",fill:"currentColor",children:e.jsx("path",{fillRule:"evenodd",d:"M5.23 7.21a.75.75 0 011.06.02L10 10.94l3.71-3.71a.75.75 0 111.06 1.06l-4.24 4.25a.75.75 0 01-1.06 0L5.21 8.29a.75.75 0 01.02-1.08z",clipRule:"evenodd"})})]}),b&&d&&cs.createPortal(e.jsxs("div",{ref:m,className:"fixed z-50 rounded-lg border bg-popover p-2 shadow-[var(--surface-shadow-lg)]",style:d,children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg bg-secondary px-3 py-2 text-xs",children:[e.jsx("span",{children:g}),e.jsx("button",{type:"button",onClick:()=>p([]),disabled:l.length===0,className:"text-primary hover:underline disabled:opacity-40",children:t("common.actions.reset")})]}),e.jsxs("div",{className:"max-h-56 overflow-y-auto py-2",children:[s.map(f=>{const j=f.isWildcard?t("apiKeys.wildcard"):f.name,S=l.includes(f.id);return e.jsxs("label",{className:E("flex cursor-pointer items-center gap-3 rounded-xl px-3 py-2 text-sm transition hover:bg-primary/5",S&&"bg-primary/10 text-primary"),children:[e.jsx("input",{type:"checkbox",className:"h-4 w-4 rounded border-border",checked:S,onChange:()=>L(f.id)}),e.jsx("span",{className:"truncate",children:j})]},f.id)}),s.length===0&&e.jsx("p",{className:"px-2 py-2 text-xs text-muted-foreground",children:t("logs.filters.apiKeyAll")})]})]}),document.body)]})}function Vs(s){const{t:l}=I(),{activeFilters:p,filtersExpanded:a,setFiltersExpanded:o,handleResetFilters:t,activeQuickView:i,applyQuickView:b,providerFilter:h,setProviderFilter:d,endpointFilter:v,setEndpointFilter:y,selectedApiKeys:w,setSelectedApiKeys:m,modelFilter:N,setModelFilter:r,statusFilter:g,setStatusFilter:L,fromDate:f,setFromDate:j,toDate:S,setToDate:n,providerOptions:C,apiKeys:D,apiKeysLoading:F,customEndpoints:T}=s;return e.jsx(Fe,{"data-testid":"logs-filters-card",className:"overflow-hidden",children:e.jsxs(Ke,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:l("logs.filtersTitle")}),p.length>0&&e.jsx(V,{variant:"outline",className:"rounded-full border-transparent bg-primary/10 px-2.5 py-0.5 text-[11px] font-semibold text-primary",children:l("common.filters.activeCount",{count:p.length})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l("logs.filtersDescription")})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[p.length>0&&e.jsx(R,{variant:"ghost",size:"sm",onClick:t,className:"h-8 rounded-full px-3 text-xs",children:l("common.actions.reset")}),e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>o(c=>!c),className:"h-8 rounded-full px-3 text-xs",children:a?e.jsxs(e.Fragment,{children:[l("common.filters.collapse"),e.jsx(us,{className:"ml-1 h-4 w-4"})]}):e.jsxs(e.Fragment,{children:[l("common.filters.expand"),e.jsx(ms,{className:"ml-1 h-4 w-4"})]})})]})]}),e.jsxs("div",{className:"grid gap-2 lg:grid-cols-[minmax(0,1fr)_auto]",children:[e.jsx("div",{className:"flex min-h-10 items-center rounded-lg bg-secondary px-3 py-2",children:p.length>0?e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:p.map(c=>e.jsxs(V,{variant:"outline",role:"button",tabIndex:0,className:"flex cursor-pointer items-center gap-1 rounded-full border border-border bg-card px-2.5 py-1 text-[11px] font-semibold text-foreground/90 transition hover:bg-secondary",onClick:c.onRemove,onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),c.onRemove())},children:[c.label,e.jsx(ps,{className:"h-3 w-3","aria-hidden":"true"})]},c.key))}):e.jsx("span",{className:"text-xs text-muted-foreground",children:l("common.filters.allRequests")})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 lg:justify-end",children:[e.jsx(ge,{label:l("logs.filters.apiKey"),value:w.length.toString()}),e.jsx(ge,{label:l("logs.filters.provider"),value:h==="all"?"0":"1"}),e.jsx(ge,{label:l("logs.filters.endpoint"),value:v==="all"?"0":"1"})]})]}),e.jsx("div",{className:"flex flex-wrap items-center gap-1.5 rounded-lg bg-secondary px-2 py-1.5",children:["all","errors","today","anthropic","openai"].map(c=>e.jsx(R,{variant:"ghost",size:"sm",className:E("h-7 rounded-full px-3 text-[11px] font-semibold transition-colors",i===c?"bg-card text-foreground shadow-[var(--surface-shadow)]":"text-muted-foreground"),onClick:()=>b(c),children:l(`logs.quickViews.${c}`)},c))})]}),a&&e.jsxs("div",{className:"mt-3 grid gap-3 rounded-xl bg-secondary p-3 md:grid-cols-2 xl:grid-cols-4 animate-in fade-in slide-in-from-top-2 duration-200",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{children:l("logs.filters.provider")}),e.jsxs(te,{value:h,onValueChange:d,children:[e.jsx(le,{children:e.jsx(ae,{})}),e.jsxs(re,{children:[e.jsx($,{value:"all",children:l("logs.filters.providerAll")}),C.map(c=>e.jsx($,{value:c.id,children:c.label??c.id},c.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{children:l("logs.filters.endpoint")}),e.jsxs(te,{value:v,onValueChange:y,children:[e.jsx(le,{children:e.jsx(ae,{})}),e.jsxs(re,{children:[e.jsx($,{value:"all",children:l("logs.filters.endpointAll")}),e.jsx($,{value:"anthropic",children:l("logs.filters.endpointAnthropic")}),e.jsx($,{value:"openai",children:l("logs.filters.endpointOpenAI")}),T==null?void 0:T.map(c=>e.jsx($,{value:c.id,children:c.label||c.id},c.id))]})]})]}),e.jsx(Us,{className:"md:col-span-2",apiKeys:D,selected:w,disabled:F,onChange:m}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{children:l("logs.filters.modelId")}),e.jsx(xe,{value:N,onChange:c=>r(c.target.value),placeholder:l("logs.filters.modelPlaceholder")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{children:l("logs.filters.status")}),e.jsxs(te,{value:g,onValueChange:c=>L(c),children:[e.jsx(le,{children:e.jsx(ae,{})}),e.jsxs(re,{children:[e.jsx($,{value:"all",children:l("logs.filters.statusAll")}),e.jsx($,{value:"success",children:l("logs.filters.statusSuccess")}),e.jsx($,{value:"error",children:l("logs.filters.statusError")})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{children:l("logs.filters.startDate")}),e.jsx(xe,{type:"date",value:f,onChange:c=>j(c.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{children:l("logs.filters.endDate")}),e.jsx(xe,{type:"date",value:S,onChange:c=>n(c.target.value)})]})]})]})})}function ge({label:s,value:l}){return e.jsxs("div",{className:"inline-flex items-center gap-1.5 rounded-full border border-border/60 bg-card px-2.5 py-1 text-[11px] text-muted-foreground",children:[e.jsx("span",{children:s}),e.jsx("span",{className:"metric-number font-semibold text-foreground",children:l})]})}const be={listRequest(s){return{url:"/api/logs",method:"GET",params:s}},detailRequest(s){return{url:s===null?"":`/api/logs/${s}`,method:"GET"}},async exportArchive(s,l){const p=await js.post("/api/logs/export",s,{responseType:"blob",timeout:l});return new Blob([p.data],{type:"application/zip"})}};function Ae({apiKeyMap:s,logId:l,open:p,providerLabelMap:a}){var N;const{t:o}=I(),{pushToast:t}=fe(),i=G(H.logs.detail(l),be.detailRequest(l),{enabled:p&&l!==null,staleTime:3e4,gcTime:15e3,placeholderData:void 0});x.useEffect(()=>{!i.isError||!i.error||t({title:o("logs.detail.loadError"),description:i.error.message,variant:"error"})},[i.error,i.isError,t,o]);const b=x.useCallback(async(r,g,L)=>{if(!g){t({title:o("logs.detail.copy.empty",{label:r}),variant:"info"});return}try{await Fs(g),t({title:o(L),variant:"success"})}catch(f){t({title:o("logs.detail.copy.failure"),description:f instanceof Error?f.message:o("logs.detail.copy.failureFallback"),variant:"error"})}},[t,o]),h=x.useCallback((r,g)=>{if(!g){t({title:o("logs.detail.copy.empty",{label:r}),variant:"info"});return}const L=new Blob([g],{type:"application/json;charset=utf-8"}),f=URL.createObjectURL(L),j=document.createElement("a"),S=new Date().toISOString().replace(/[:.]/g,"-"),n=r.trim().toLowerCase().replace(/[^a-z0-9\u4e00-\u9fa5]+/gi,"-").replace(/^-+|-+$/g,"")||"payload";j.href=f,j.download=`cc-gw-log-${l??"payload"}-${n}-${S}.json`,document.body.appendChild(j),j.click(),document.body.removeChild(j),URL.revokeObjectURL(f)},[l,t,o]),d=i.data,v=d?a.get(d.provider)??d.provider:"",y=d&&d.api_key_id!=null?s.get(d.api_key_id):void 0,w=d?Ks(d,o):null,m=d?he(d,o):null;return{apiKeyMeta:y,errorSourceMeta:w,errorMessage:i.isError?((N=i.error)==null?void 0:N.message)??null:null,handleCopy:b,handleDownloadPayload:h,isError:i.isError,isPending:i.isPending,providerLabel:v,refetch:i.refetch,record:d,statusMeta:m}}function Hs({open:s,logId:l,onClose:p,providerLabelMap:a,apiKeyMap:o}){var f,j,S;const{t}=I(),{apiKeyMeta:i,errorSourceMeta:b,errorMessage:h,handleCopy:d,handleDownloadPayload:v,isError:y,isPending:w,providerLabel:m,refetch:N,record:r,statusMeta:g}=Ae({apiKeyMap:o,logId:l,open:s,providerLabelMap:a}),L=x.useMemo(()=>{var C,D,F,T;return r?[{key:"client-request",title:t("logs.detail.payload.clientRequest"),value:((C=r.payload)==null?void 0:C.client_request)??null,emptyLabel:t("logs.detail.payload.emptyRequest"),copyToast:"logs.detail.copy.requestSuccess"},...(D=r.payload)!=null&&D.upstream_request?[{key:"upstream-request",title:t("logs.detail.payload.upstreamRequest"),value:r.payload.upstream_request,emptyLabel:t("logs.detail.payload.emptyRequest"),copyToast:"logs.detail.copy.requestSuccess"}]:[],...(F=r.payload)!=null&&F.upstream_response?[{key:"upstream-response",title:t("logs.detail.payload.upstreamResponse"),value:r.payload.upstream_response,emptyLabel:t("logs.detail.payload.emptyResponse"),copyToast:"logs.detail.copy.responseSuccess"}]:[],{key:"client-response",title:t("logs.detail.payload.clientResponse"),value:((T=r.payload)==null?void 0:T.client_response)??null,emptyLabel:t("logs.detail.payload.emptyResponse"),copyToast:"logs.detail.copy.responseSuccess"}].map(c=>({...c,display:Me(c.value,c.emptyLabel)})):[]},[r,t]);return e.jsx(ws,{open:s,onOpenChange:n=>{n||p()},children:e.jsxs(Ns,{className:"w-[min(96vw,1200px)] max-w-[1200px]",children:[e.jsxs(ks,{className:"pr-14",children:[e.jsx(Ss,{children:t("logs.detail.title")}),e.jsx(Cs,{children:r?t("logs.detail.id",{id:r.id}):t("logs.detail.loadError")})]}),e.jsx(Ls,{className:"max-h-[78vh]",children:w?e.jsx(_s,{compact:!0,className:"min-h-[240px]",label:t("common.loading")}):y?e.jsx(Y,{compact:!0,className:"min-h-[240px]",tone:"danger",title:t("logs.detail.loadError"),description:h??t("common.unknownError"),action:e.jsx(R,{variant:"outline",onClick:()=>void N(),children:t("common.actions.refresh")})}):r?e.jsxs("div",{className:"space-y-6 text-sm",children:[e.jsxs("section",{className:"space-y-4 rounded-lg border bg-card p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:t("logs.detail.infoSection")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 rounded-lg border bg-secondary p-3 text-xs",children:[e.jsx("span",{className:"font-medium",children:t("logs.detail.summary.route",{from:r.client_model??t("logs.detail.info.noRequestedModel"),to:r.model})}),e.jsx("span",{className:"text-muted-foreground",children:t("logs.detail.summary.latency",{value:O(r.latency_ms,t("common.units.ms"))})}),r.ttft_ms!==null?e.jsxs("span",{className:"text-muted-foreground",children:["TTFT: ",O(r.ttft_ms,t("common.units.ms"))]}):null]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(V,{variant:g==null?void 0:g.variant,children:(g==null?void 0:g.label)??"-"}),e.jsx(V,{variant:"outline",children:r.stream?t("logs.stream.streaming"):t("logs.stream.single")})]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-5",children:[e.jsx(U,{label:t("logs.detail.info.latency"),value:O(r.latency_ms,t("common.units.ms"))}),e.jsx(U,{label:t("logs.detail.info.ttft"),value:O(r.ttft_ms,t("common.units.ms"))}),e.jsx(U,{label:t("logs.detail.info.tpot"),value:O(r.tpot_ms,t("common.units.msPerToken"))}),e.jsx(U,{label:t("logs.detail.info.status"),value:(g==null?void 0:g.label)??"-"}),e.jsx(U,{label:t("logs.detail.info.errorSource"),value:(b==null?void 0:b.label)??"-"})]}),e.jsxs("dl",{className:"grid gap-x-4 gap-y-3 md:grid-cols-2 xl:grid-cols-4",children:[e.jsx(M,{label:t("logs.detail.info.time"),value:ye(r.timestamp)}),e.jsx(M,{label:t("logs.detail.info.sessionId"),value:r.session_id??"-"}),e.jsx(M,{label:t("logs.detail.info.endpoint"),value:r.endpoint||"-"}),e.jsx(M,{label:t("logs.detail.info.provider"),value:m}),e.jsx(M,{label:t("logs.detail.info.requestedModel"),value:r.client_model??t("logs.detail.info.noRequestedModel")}),e.jsx(M,{label:t("logs.detail.info.model"),value:r.model}),e.jsx(M,{label:t("logs.detail.info.stream"),value:Ms(r.stream)}),e.jsx(M,{label:t("logs.detail.info.status"),value:(g==null?void 0:g.label)??"-"}),e.jsx(M,{label:t("logs.detail.info.errorSource"),value:(b==null?void 0:b.label)??"-"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsx(U,{label:t("logs.detail.info.inputTokens"),value:q(r.input_tokens)}),e.jsx(U,{label:t("logs.detail.info.cacheReadTokens"),value:q(r.cache_read_tokens)}),e.jsx(U,{label:t("logs.detail.info.cacheCreationTokens"),value:q(r.cache_creation_tokens)}),e.jsx(U,{label:t("logs.detail.info.outputTokens"),value:q(r.output_tokens)})]}),r.error?e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:t("logs.detail.info.error")}),e.jsx("p",{className:"rounded-xl border border-destructive/50 bg-destructive/10 p-3 text-xs text-destructive",children:r.error})]}):null]}),e.jsxs("div",{className:"grid gap-6 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]",children:[e.jsxs("section",{className:"space-y-3 rounded-lg border bg-card p-4",children:[e.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:t("logs.detail.apiKey.title")}),e.jsxs("dl",{className:"grid gap-x-4 gap-y-3 sm:grid-cols-2",children:[e.jsx(M,{label:t("logs.detail.apiKey.name"),value:r.api_key_id==null&&!r.api_key_name?t("logs.detail.apiKey.missing"):i!=null&&i.isWildcard?t("apiKeys.wildcard"):(i==null?void 0:i.name)??r.api_key_name??t("logs.detail.apiKey.missing")}),e.jsx(M,{label:t("logs.detail.apiKey.identifier"),value:r.api_key_id??t("common.noData")}),e.jsx(M,{label:t("logs.detail.apiKey.masked"),value:i!=null&&i.isWildcard?t("apiKeys.wildcard"):(i==null?void 0:i.maskedKey)??r.api_key_name??t("logs.detail.apiKey.maskedUnavailable")}),e.jsx(M,{label:t("logs.detail.apiKey.lastUsed"),value:i!=null&&i.lastUsedAt?new Date(i.lastUsedAt).toLocaleString():t("common.noData")})]}),e.jsxs("div",{className:"rounded-lg border bg-secondary p-3 text-xs",children:[e.jsx("p",{className:"font-medium",children:t("logs.detail.apiKey.rawMasked")}),e.jsx("p",{className:"mt-1 break-all font-mono",children:r.api_key_value_available?r.api_key_value_masked??t("logs.detail.apiKey.rawUnavailable"):t("logs.detail.apiKey.rawUnavailable")}),e.jsx("p",{className:"mt-2 text-[11px] text-muted-foreground",children:t("logs.detail.apiKey.rawMaskedHint")})]})]}),e.jsxs("section",{className:"space-y-4 rounded-lg border bg-card p-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:t("logs.detail.payload.title")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(f=r.payload)!=null&&f.upstream_request||(j=r.payload)!=null&&j.upstream_response?t("logs.detail.payload.helperWithUpstream"):t("logs.detail.payload.helperClientOnly")})]}),e.jsxs(Es,{defaultValue:(S=L[0])==null?void 0:S.key,children:[e.jsx(Rs,{className:"w-full justify-start overflow-x-auto",children:L.map(n=>e.jsx(Ds,{value:n.key,children:n.title},n.key))}),L.map(n=>e.jsx(Ts,{value:n.key,children:e.jsx(Bs,{title:n.title,display:n.display,onCopy:()=>d(n.title,n.value,n.copyToast),onDownload:()=>v(n.title,n.value),panelKey:n.key,t})},n.key))]})]})]})]}):e.jsx(Y,{compact:!0,className:"min-h-[240px]",title:t("logs.detail.loadError"),description:t("common.noData")})})]})})}function U({label:s,value:l}){return e.jsxs("div",{className:"min-w-0 rounded-lg border bg-secondary px-3 py-3",children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-wider text-muted-foreground",children:s}),e.jsx("p",{className:"mt-2 break-all text-sm font-semibold leading-6",children:l})]})}function M({label:s,value:l}){return e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsx("dt",{className:"text-xs text-muted-foreground",children:s}),e.jsx("dd",{className:"min-w-0 break-all whitespace-pre-wrap text-sm font-medium leading-6 text-foreground",children:l??"-"})]})}function Bs({display:s,onCopy:l,onDownload:p,panelKey:a,title:o,t}){return e.jsxs("div",{className:"space-y-3 rounded-lg border bg-secondary/40 p-4","data-testid":`log-payload-${a}`,children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:o}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(R,{variant:"outline",size:"sm",onClick:l,children:[e.jsx(De,{className:"mr-2 h-3.5 w-3.5"}),t("common.actions.copy")]}),e.jsxs(R,{variant:"outline",size:"sm",onClick:p,children:[e.jsx(Te,{className:"mr-2 h-3.5 w-3.5"}),t("common.actions.download")]})]})]}),s.isTruncated?e.jsx("p",{className:"rounded-lg border border-warning/30 bg-warning-bg px-3 py-2 text-xs text-warning",children:t("logs.detail.payload.truncated",{shown:s.displayedLength.toLocaleString(),total:s.originalLength.toLocaleString()})}):null,e.jsx("pre",{className:"max-h-72 overflow-auto whitespace-pre rounded-lg border bg-secondary p-3 text-xs",children:s.text})]})}const X=[20,50,100],J=["endpoint","provider","requestedModel","routedModel","apiKey","tokens","duration","status","error"],oe=["endpoint","provider","requestedModel","routedModel","apiKey","tokens","duration","status","error"];function Ws(){return typeof window>"u"?"comfortable":window.localStorage.getItem(P.logs.density)==="compact"?"compact":"comfortable"}function Gs(){if(typeof window>"u")return X[0];const s=window.localStorage.getItem(P.logs.pageSize),l=Number(s);return X.includes(l)?l:X[0]}function Ee(s,l=!1){if(!s)return;const p=l?`${s}T23:59:59.999`:`${s}T00:00:00.000`,a=Date.parse(p);return Number.isFinite(a)?a:void 0}function Js(s,l,p){return s===p&&l===p}function Xs({autoRefresh:s,columnOptions:l,exporting:p,onExport:a,onRefresh:o,onResetColumns:t,onSetDensity:i,onToggleAutoRefresh:b,onToggleColumn:h,refreshing:d,rowDensity:v,visibleColumns:y,visibleColumnSet:w}){const{t:m}=I(),N=JSON.stringify(y)===JSON.stringify(J);return e.jsxs("div",{className:"flex w-full flex-col gap-3 xl:w-auto xl:flex-row xl:items-center",children:[e.jsxs("div",{className:"flex w-full flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center xl:w-auto xl:flex-nowrap",children:[e.jsx(Is,{block:!0,className:"w-full overflow-x-auto sm:w-auto",value:v,onChange:i,options:[{value:"comfortable",label:m("logs.table.density.comfortable")},{value:"compact",label:m("logs.table.density.compact")}]}),e.jsxs(zs,{children:[e.jsx(As,{asChild:!0,children:e.jsx(R,{variant:"outline",size:"sm",className:"w-full sm:w-auto",children:m("logs.actions.columns")})}),e.jsxs(Os,{align:"end",className:"w-64 p-3",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:m("logs.actions.columns")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:m("logs.actions.visibleCount",{count:y.length})})]}),e.jsx(R,{variant:"ghost",size:"sm",onClick:t,disabled:N,children:m("common.actions.reset")})]}),e.jsx("div",{className:"grid gap-1.5",children:l.map(r=>{const g=w.has(r.id);return e.jsxs("label",{className:E("flex cursor-pointer items-center gap-3 rounded-xl px-3 py-2 text-sm transition hover:bg-accent",g&&"bg-primary/10 text-primary"),children:[e.jsx("input",{type:"checkbox",checked:g,onChange:()=>h(r.id),className:"h-4 w-4 rounded border-border"}),e.jsx("span",{children:r.label})]},r.id)})})]})]}),e.jsxs(R,{onClick:a,disabled:p,className:"w-full sm:w-auto",children:[e.jsx(Te,{className:"mr-2 h-4 w-4"}),m(p?"logs.actions.exporting":"logs.actions.export")]})]}),e.jsxs("div",{className:"flex w-full items-center gap-3 xl:w-auto",children:[e.jsxs("label",{className:"flex shrink-0 cursor-pointer items-center gap-2 text-sm text-muted-foreground",children:[e.jsx($s,{checked:s,onCheckedChange:b,"aria-label":m("logs.actions.autoRefresh")}),m("logs.actions.autoRefresh")]}),e.jsxs(R,{variant:"outline",size:"sm",onClick:o,disabled:d,className:"shrink-0",children:[e.jsx(xs,{className:E("mr-2 h-4 w-4",d&&"animate-spin")}),m(d?"common.actions.refreshing":"logs.actions.manualRefresh")]})]})]})}function Ys({record:s,providerLabelMap:l,onSelect:p}){const{t:a}=I(),o=he(s,a),t=l.get(s.provider)??s.provider,i=Pe(s.session_id),b=i==null?void 0:i.accentStyle;return e.jsxs("button",{type:"button","data-session-id":i==null?void 0:i.sessionId,"data-session-color":i==null?void 0:i.colorKey,style:b,onClick:()=>p(s.id),className:"w-full space-y-2 border-b border-border/50 px-4 py-3 text-left transition-colors hover:bg-muted/50",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:ye(s.timestamp)}),e.jsx(V,{variant:o.variant,className:"text-xs",children:o.label})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[e.jsx("span",{className:"min-w-0 truncate font-medium",title:t,children:t}),e.jsx("span",{className:"min-w-0 truncate text-muted-foreground",title:s.model,children:s.model})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-xs tabular-nums text-muted-foreground",children:[e.jsx("span",{children:O(s.latency_ms,a("common.units.ms"))}),s.ttft_ms!=null?e.jsxs("span",{children:[a("logs.table.columns.latencyTtft")," ",q(s.ttft_ms)]}):null]})]})}const Re={accent:"bg-primary",ok:"bg-success",warn:"bg-warning",error:"bg-destructive"};function Zs({logId:s,providerLabelMap:l,apiKeyMap:p}){const{t:a}=I(),{record:o,isPending:t,isError:i,errorMessage:b,statusMeta:h,providerLabel:d,handleCopy:v,refetch:y}=Ae({apiKeyMap:p,logId:s,open:!0,providerLabelMap:l}),w=x.useMemo(()=>{var C,D,F,T;if(!o)return[];const n=[{key:"client-request",title:a("logs.detail.payload.clientRequest"),value:((C=o.payload)==null?void 0:C.client_request)??null,emptyLabel:a("logs.detail.payload.emptyRequest"),copyToast:"logs.detail.copy.requestSuccess"}];return(D=o.payload)!=null&&D.upstream_request&&n.push({key:"upstream-request",title:a("logs.detail.payload.upstreamRequest"),value:o.payload.upstream_request,emptyLabel:a("logs.detail.payload.emptyRequest"),copyToast:"logs.detail.copy.requestSuccess"}),(F=o.payload)!=null&&F.upstream_response&&n.push({key:"upstream-response",title:a("logs.detail.payload.upstreamResponse"),value:o.payload.upstream_response,emptyLabel:a("logs.detail.payload.emptyResponse"),copyToast:"logs.detail.copy.responseSuccess"}),n.push({key:"client-response",title:a("logs.detail.payload.clientResponse"),value:((T=o.payload)==null?void 0:T.client_response)??null,emptyLabel:a("logs.detail.payload.emptyResponse"),copyToast:"logs.detail.copy.responseSuccess"}),n.map(c=>({...c,display:Me(c.value,c.emptyLabel)}))},[o,a]),[m,N]=x.useState("client-request"),r=w.find(n=>n.key===m)??w[0];if(t)return e.jsx("div",{className:"py-3",children:e.jsx(qe,{className:"h-28 w-full"})});if(i)return e.jsx(Y,{compact:!0,tone:"danger",title:a("logs.detail.loadError"),description:b??a("common.unknownError"),action:e.jsx(R,{variant:"outline",size:"sm",onClick:()=>void y(),children:a("common.actions.refresh")})});if(!o)return e.jsx(Y,{compact:!0,title:a("logs.detail.loadError"),description:a("common.noData")});const g=Ps(o,d,a),L=a("common.units.ms"),f=[{label:a("logs.detail.info.status"),value:(h==null?void 0:h.label)??"-"},{label:a("logs.detail.info.latency"),value:O(o.latency_ms,L)},{label:a("logs.detail.info.ttft"),value:O(o.ttft_ms,L)},{label:a("logs.detail.info.inputTokens"),value:q(o.input_tokens)},{label:a("logs.detail.info.outputTokens"),value:q(o.output_tokens)},{label:a("logs.detail.info.cacheReadTokens"),value:q(o.cache_read_tokens)}],j=o.ttft_ms!=null,S=o.session_id;return e.jsxs("div",{"data-testid":"log-row-expanded",className:"grid gap-5 py-1 xl:grid-cols-[minmax(0,1.15fr)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"mb-3 text-[10.5px] font-semibold uppercase tracking-[0.06em] text-muted-foreground",children:a("logs.detail.trace.title")}),e.jsx("ol",{"data-testid":"log-trace-timeline",className:"flex flex-col",children:g.map((n,C)=>e.jsxs("li",{className:"grid grid-cols-[14px_1fr] gap-3",children:[e.jsxs("div",{className:"flex flex-col items-center","aria-hidden":"true",children:[e.jsx("span",{className:E("mt-1 h-[9px] w-[9px] rounded-full",Re[n.tone])}),C<g.length-1?e.jsx("span",{className:"mt-[3px] w-px flex-1 bg-border"}):null]}),e.jsxs("div",{className:"pb-3.5",children:[e.jsxs("div",{className:"flex items-baseline gap-2.5",children:[e.jsx("span",{className:"text-xs font-semibold",children:n.title}),n.atLabel?e.jsx("span",{className:"text-[10.5px] tabular-nums text-muted-foreground",children:n.atLabel}):null,n.durLabel?e.jsx("span",{className:"ml-auto text-[10.5px] tabular-nums text-muted-foreground",children:n.durLabel}):null]}),n.detail?e.jsx("div",{className:"mt-1 text-[11px] leading-[1.55] text-muted-foreground",children:n.detail}):null,e.jsx("div",{className:"mt-1.5 h-1 w-full max-w-[220px] bg-secondary",children:e.jsx("div",{className:E("h-full",Re[n.tone]),style:{width:`${n.barPct}%`}})})]})]},n.id))}),j?null:e.jsx("p",{className:"mt-1 text-[10.5px] text-muted-foreground/70",children:a("logs.detail.trace.degraded")})]}),e.jsxs("div",{className:"flex min-w-0 flex-col gap-3",children:[e.jsx("div",{className:"grid grid-cols-3 gap-2",children:f.map(n=>e.jsxs("div",{className:"border border-border bg-card px-2.5 py-2",children:[e.jsx("div",{className:"text-[10.5px] text-muted-foreground",children:n.label}),e.jsx("div",{className:"mt-0.5 text-[13px] font-semibold tabular-nums",children:n.value})]},n.label))}),e.jsxs("div",{className:"border border-border bg-card",children:[e.jsx("div",{className:"flex gap-0.5 border-b border-border bg-secondary/50 p-1.5",role:"tablist",children:w.map(n=>{const C=n.key===(r==null?void 0:r.key);return e.jsx("button",{type:"button",role:"tab","aria-selected":C,onClick:()=>N(n.key),className:E("px-2.5 py-1 text-[10.5px] font-medium transition-colors",C?"bg-card text-foreground":"text-muted-foreground hover:text-foreground"),children:n.title},n.key)})}),e.jsx("pre",{"data-testid":`log-payload-${(r==null?void 0:r.key)??"none"}`,className:"m-0 max-h-[172px] overflow-auto whitespace-pre-wrap p-3 font-mono text-[10.5px] leading-[1.65] text-muted-foreground",children:(r==null?void 0:r.display.text)||a("logs.detail.payload.emptyRequest")})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(R,{variant:"outline",size:"sm",className:"h-[30px] flex-1",onClick:()=>{r&&v(r.title,r.value,r.copyToast)},children:[e.jsx(De,{className:"mr-1.5 h-3.5 w-3.5","aria-hidden":"true"}),a("logs.detail.inline.copyRequest")]}),S?e.jsx(R,{variant:"outline",size:"sm",className:"h-[30px] flex-1",onClick:()=>v(a("logs.detail.inline.copySession"),S,"logs.detail.inline.sessionCopied"),children:a("logs.detail.inline.copySession")}):null,e.jsx(R,{asChild:!0,variant:"outline",size:"sm",className:"h-[30px] flex-1",children:e.jsxs(ze,{to:"/providers?tab=routing",children:[a("logs.detail.inline.viewRule"),e.jsx(gs,{className:"ml-1.5 h-3.5 w-3.5","aria-hidden":"true"})]})})]})]})]})}function et({record:s,providerLabelMap:l,apiKeyMap:p,onSelect:a,isExpanded:o,onToggleExpand:t,isEven:i,density:b,visibleColumnSet:h}){const{t:d}=I(),v=l.get(s.provider)??s.provider,y=s.endpoint||"-",w=he(s,d),m=s.client_model??d("logs.table.requestedModelFallback"),N=s.api_key_id!=null?p.get(s.api_key_id):void 0,r=s.api_key_id==null?d("logs.table.apiKeyUnknown"):N!=null&&N.isWildcard?d("apiKeys.wildcard"):N!=null&&N.name?N.name:s.api_key_name?s.api_key_name:d("logs.table.apiKeyUnknown"),g=b==="compact"?"px-3 py-1.5":"px-3 py-2",L=i?"bg-muted/30":"bg-background",f=Pe(s.session_id),j=f==null?void 0:f.accentStyle,S=h.size+2,n=d(o?"logs.detail.inline.collapse":"logs.detail.inline.expand");return e.jsxs(e.Fragment,{children:[e.jsxs("tr",{"data-log-id":s.id,"data-session-id":f==null?void 0:f.sessionId,"data-session-color":f==null?void 0:f.colorKey,className:E("transition-colors duration-160 ease-surface",i?"bg-muted/30":"",o?"bg-muted/50":"hover:bg-muted/50"),children:[e.jsx("td",{className:E("sticky left-0 z-10 text-xs",g,L),style:j,children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{type:"button","aria-expanded":o,"aria-label":n,onClick:()=>t(s.id),className:"-ml-0.5 inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:e.jsx(fs,{className:E("h-3.5 w-3.5 transition-transform duration-160 ease-surface",o&&"rotate-90"),"aria-hidden":"true"})}),e.jsx("span",{className:"metric-number",children:ye(s.timestamp)})]})}),h.has("endpoint")&&e.jsx("td",{className:E(g,"text-xs"),children:y}),h.has("provider")&&e.jsx("td",{className:E(g,"text-xs"),children:e.jsx("div",{className:"max-w-[100px] truncate",title:v,children:v})}),h.has("requestedModel")&&e.jsx("td",{className:E(g,"text-xs text-muted-foreground"),children:e.jsx("div",{className:"max-w-[120px] truncate",title:m,children:m})}),h.has("routedModel")&&e.jsx("td",{className:E(g,"text-xs"),children:e.jsx("div",{className:"max-w-[120px] truncate",title:s.model,children:s.model})}),h.has("apiKey")&&e.jsx("td",{className:E(g,"text-xs text-muted-foreground"),children:e.jsx("div",{className:"max-w-[90px] truncate",title:r,children:r})}),h.has("tokens")&&e.jsx("td",{className:E(g,"text-right text-xs tabular-nums align-top"),children:e.jsxs("span",{className:"inline-flex flex-col items-end gap-0.5",children:[e.jsxs("span",{className:"whitespace-nowrap",children:[d("logs.table.columns.tokenIn")," ",q(s.input_tokens),e.jsx("span",{className:"mx-1 text-muted-foreground/50",children:"·"}),d("logs.table.columns.tokenOut")," ",q(s.output_tokens)]}),(()=>{const C=(s.cache_read_tokens??0)+(s.cache_creation_tokens??0);return C>0?e.jsxs("span",{className:"whitespace-nowrap text-[11px] text-muted-foreground/70",children:[d("logs.table.columns.tokenCache")," ",q(C)]}):null})()]})}),h.has("duration")&&e.jsx("td",{className:E(g,"text-right text-xs tabular-nums align-top"),children:e.jsxs("span",{className:"inline-flex flex-col items-end gap-0.5",children:[e.jsx("span",{className:"whitespace-nowrap",children:O(s.latency_ms,"ms")}),(s.ttft_ms!=null||s.tpot_ms!=null)&&e.jsxs("span",{className:"whitespace-nowrap text-[11px] text-muted-foreground/70",title:`${d("logs.table.columns.latencyTtft")} ${O(s.ttft_ms,"ms")} · ${d("logs.table.columns.latencyTpot")} ${O(s.tpot_ms,"ms/tk")}`,children:[d("logs.table.columns.latencyTtft")," ",q(s.ttft_ms),e.jsx("span",{className:"mx-1 text-muted-foreground/50",children:"·"}),d("logs.table.columns.latencyTpot")," ",q(s.tpot_ms)]})]})}),h.has("status")&&e.jsx("td",{className:E(g,"text-center"),children:e.jsx(V,{variant:w.variant,className:"text-xs",children:w.label})}),h.has("error")&&e.jsx("td",{className:E(g,"text-xs text-muted-foreground"),children:e.jsx("div",{className:"max-w-[100px] truncate",title:s.error??"",children:s.error?s.error:"-"})}),e.jsx("td",{className:E("sticky right-0 z-10 text-center",g,L),children:e.jsx(R,{variant:"outline",size:"sm",onClick:()=>a(s.id),children:d("logs.actions.detail")})})]}),o?e.jsx("tr",{"data-testid":`log-row-expanded-wrapper-${s.id}`,children:e.jsx("td",{colSpan:S,className:"border-t border-border bg-secondary/30 p-0",children:e.jsx("div",{className:"px-5 pb-5 pt-3",children:e.jsx(Zs,{logId:s.id,providerLabelMap:l,apiKeyMap:p})})})}):null]})}function st(s){const{t:l}=I(),{tableScrollRef:p,visibleColumnSet:a,visibleColumnCount:o,logsError:t,logsPending:i,items:b,activeFiltersCount:h,total:d,handleResetFilters:v,handleRetry:y,providerLabelMap:w,apiKeyMap:m,handleOpenDetail:N,expandedLogId:r,onToggleExpand:g,rowDensity:L,showScrollHint:f,pageSize:j,setPageSize:S,page:n,totalPages:C,setPage:D}=s,F=e.jsx(Y,{compact:!0,tone:"danger",icon:e.jsx(hs,{className:"h-5 w-5","aria-hidden":"true"}),title:l("logs.toast.listError.title"),description:t,action:e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-2",children:[e.jsx(R,{variant:"outline",size:"sm",onClick:y,children:l("common.actions.refresh")}),h>0?e.jsx(R,{variant:"ghost",size:"sm",onClick:v,children:l("common.actions.reset")}):null]})}),T=e.jsx(Y,{compact:!0,tone:"primary",icon:e.jsx(ys,{className:"h-5 w-5","aria-hidden":"true"}),title:h>0?l("logs.empty.filteredTitle"):l("logs.empty.title"),description:h>0?l("logs.empty.filteredSubtitle"):l("logs.empty.subtitle"),action:e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-2",children:[h>0?e.jsx(R,{variant:"outline",size:"sm",onClick:v,children:l("logs.empty.actions.reset")}):null,e.jsx(R,{asChild:!0,variant:"ghost",size:"sm",children:e.jsx(ze,{to:"/api-keys",children:l("logs.empty.actions.apiKeys")})})]})});return e.jsx(Fe,{className:"overflow-hidden bg-card shadow-[var(--surface-shadow)]",children:e.jsxs(Ke,{className:"p-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 bg-secondary/50 px-4 py-3 border-b border-border",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-semibold",children:l("logs.title")}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.jsx("span",{className:"metric-number",children:l("logs.summary.total",{value:d.toLocaleString()})}),e.jsx("span",{className:"mx-1.5 text-muted-foreground/50",children:"·"}),l("logs.actions.visibleCount",{count:o-2})]})]}),e.jsxs("div",{className:"hidden md:flex flex-wrap items-center gap-2",children:[e.jsx(V,{variant:"secondary",children:"Wide Table"}),e.jsx(V,{variant:"outline",className:"bg-background",children:l(L==="compact"?"logs.table.density.compact":"logs.table.density.comfortable")}),f?e.jsx(V,{variant:"warning",children:"Scroll for more"}):null]})]}),e.jsxs("div",{className:"relative hidden md:block",children:[e.jsx("div",{ref:p,className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full min-w-[1180px] text-sm",children:[e.jsx("thead",{className:"border-b border-border/50 bg-secondary/50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"sticky left-0 z-20 bg-secondary px-3 py-2.5 text-left text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:l("logs.table.columns.time")}),a.has("endpoint")&&e.jsx("th",{className:"px-3 py-2.5 text-left text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:l("logs.table.columns.endpoint")}),a.has("provider")&&e.jsx("th",{className:"px-3 py-2.5 text-left text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:l("logs.table.columns.provider")}),a.has("requestedModel")&&e.jsx("th",{className:"px-3 py-2.5 text-left text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:l("logs.table.columns.requestedModel")}),a.has("routedModel")&&e.jsx("th",{className:"px-3 py-2.5 text-left text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:l("logs.table.columns.routedModel")}),a.has("apiKey")&&e.jsx("th",{className:"px-3 py-2.5 text-left text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:l("logs.table.columns.apiKey")}),a.has("tokens")&&e.jsx("th",{className:"px-3 py-2.5 text-right text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:l("logs.table.columns.tokens")}),a.has("duration")&&e.jsx("th",{className:"px-3 py-2.5 text-right text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:l("logs.table.columns.duration")}),a.has("status")&&e.jsx("th",{className:"px-3 py-2.5 text-center text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:l("logs.table.columns.status")}),a.has("error")&&e.jsx("th",{className:"px-3 py-2.5 text-left text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:l("logs.table.columns.error")}),e.jsx("th",{className:"sticky right-0 z-20 bg-secondary px-3 py-2.5 text-center text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:l("logs.table.columns.actions")})]})}),e.jsx("tbody",{className:"divide-y divide-border/50",children:i?Array.from({length:8}).map((c,_)=>e.jsx(qs,{columns:o},_)):t&&b.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:o,className:"px-3 py-6",children:F})}):b.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:o,className:"px-3 py-8 text-center text-sm text-muted-foreground",children:T})}):b.map((c,_)=>e.jsx(et,{record:c,providerLabelMap:w,apiKeyMap:m,onSelect:N,isExpanded:c.id===r,onToggleExpand:g,isEven:_%2===0,density:L,visibleColumnSet:a},c.id))})]})}),f&&e.jsx("div",{className:"table-scroll-hint"})]}),e.jsx("div",{className:"md:hidden",children:i?e.jsx("div",{className:"space-y-3 p-4",children:Array.from({length:5}).map((c,_)=>e.jsx(qe,{className:"h-20 w-full"},_))}):t&&b.length===0?e.jsx("div",{className:"px-3 py-6",children:F}):b.length===0?e.jsx("div",{className:"px-3 py-8",children:T}):b.map(c=>e.jsx(Ys,{record:c,providerLabelMap:w,onSelect:N},c.id))}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4 bg-secondary/50 p-4 border-t border-border",children:[e.jsxs("div",{className:"flex items-center gap-2 rounded-full bg-secondary px-3 py-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:l("logs.table.pagination.perPage")}),e.jsxs(te,{value:j.toString(),onValueChange:c=>S(Number(c)),children:[e.jsx(le,{className:"h-8 w-[80px] bg-background",children:e.jsx(ae,{})}),e.jsx(re,{children:X.map(c=>e.jsx($,{value:c.toString(),children:c},c))})]})]}),e.jsxs("div",{className:"flex items-center gap-2 rounded-full bg-secondary px-2 py-2",children:[e.jsx(R,{variant:"outline",size:"sm",onClick:()=>D(c=>Math.max(c-1,1)),disabled:n<=1,children:l("logs.table.pagination.previous")}),e.jsx("span",{className:"metric-number px-1 text-sm text-muted-foreground",children:l("logs.table.pagination.pageLabel",{page:C===0?0:n,total:C})}),e.jsx(R,{variant:"outline",size:"sm",onClick:()=>D(c=>C===0?c:Math.min(c+1,C)),disabled:C===0||n>=C,children:l("logs.table.pagination.next")})]})]})]})})}function tt({exportTimeoutMs:s,queryParams:l,total:p}){const{t:a}=I(),{pushToast:o}=fe(),[t,i]=x.useState(!1),b=x.useCallback(async()=>{if(!t){i(!0);try{const h=p>0?Math.min(p,5e3):1e3,d={...l,limit:h,offset:0},v=await be.exportArchive(d,s),y=new Date().toISOString().replace(/[:.]/g,"-"),w=URL.createObjectURL(v),m=document.createElement("a");m.href=w,m.download=`cc-gw-logs-${y}.zip`,document.body.appendChild(m),m.click(),m.remove(),URL.revokeObjectURL(w),o({title:a("logs.toast.exportSuccess.title"),description:a("logs.toast.exportSuccess.desc"),variant:"success"})}catch(h){const d=vs(h);o({title:a("logs.toast.exportError.title"),description:a("logs.toast.exportError.desc",{message:d.message}),variant:"error"})}finally{i(!1)}}},[s,t,o,l,a,p]);return{exporting:t,handleExport:b}}function lt(){const s=x.useRef(null),[l,p]=x.useState(!1),a=x.useCallback(()=>{const o=s.current;if(!o)return;const t=o.scrollWidth-o.scrollLeft-o.clientWidth>1;p(t)},[]);return x.useEffect(()=>{const o=s.current;if(!o)return;a(),o.addEventListener("scroll",a,{passive:!0});const t=new ResizeObserver(a);return t.observe(o),()=>{o.removeEventListener("scroll",a),t.disconnect()}},[a]),{scrollRef:s,showScrollHint:l,updateScrollHint:a}}function at(){const[s,l]=A(P.logs.density,Ws,{serialize:v=>v,deserialize:v=>v==="compact"?"compact":"comfortable"}),[p,a]=A(P.logs.visibleColumns,J,{serialize:JSON.stringify,deserialize:v=>{try{const y=JSON.parse(v);if(!Array.isArray(y))return J;const w=y.filter(m=>oe.includes(m));return w.length>0?w:J}catch{return J}}}),{scrollRef:o,showScrollHint:t}=lt(),i=x.useMemo(()=>new Set(p),[p]),b=p.length+2,h=x.useCallback(v=>{a(y=>{if(y.includes(v))return y.length===1?y:y.filter(m=>m!==v);const w=[...y,v];return w.sort((m,N)=>oe.indexOf(m)-oe.indexOf(N)),w})},[]);return{resetVisibleColumns:x.useCallback(()=>{a(J)},[]),rowDensity:s,setRowDensity:l,showScrollHint:t,tableScrollRef:o,toggleColumn:h,visibleColumnCount:b,visibleColumns:p,visibleColumnSet:i}}const rt=3e3,ot=200;function nt(){var Ne,ke,Se,Ce,Le;const{t:s}=I(),{pushToast:l}=fe(),p=Qs(),[a,o]=A(P.logs.providerFilter,"all"),[t,i]=A(P.logs.endpointFilter,"all"),[b,h]=A(P.logs.modelFilter,""),[d,v]=A(P.logs.statusFilter,"all"),[y,w]=A(P.logs.fromDate,""),[m,N]=A(P.logs.toDate,""),[r,g]=x.useState(1),[L,f]=A(P.logs.autoRefresh,!0),[j,S]=A(P.logs.pageSize,Gs,{serialize:u=>String(u),deserialize:u=>{const k=Number(u);return X.includes(k)?k:X[0]}}),[n,C]=x.useState(null),[D,F]=x.useState(!1),[T,c]=x.useState(null),[_,ne]=A(P.logs.selectedApiKeys,[],{serialize:JSON.stringify,deserialize:u=>{try{const k=JSON.parse(u);return Array.isArray(k)?k.map(z=>Number(z)).filter(z=>Number.isInteger(z)&&z>0):[]}catch{return[]}}}),[Oe,Ie]=x.useState(!0),{resetVisibleColumns:$e,rowDensity:Qe,setRowDensity:Ue,showScrollHint:Ve,tableScrollRef:He,toggleColumn:Be,visibleColumnCount:We,visibleColumns:Ge,visibleColumnSet:Je}=at(),Xe=x.useDeferredValue(b),K=b===""?"":Xe;x.useEffect(()=>{g(1),c(null)},[a,t,K,d,y,m,j,_]);const ie=x.useMemo(()=>{const u={limit:j,offset:(r-1)*j};a!=="all"&&(u.provider=a),t!=="all"&&(u.endpoint=t),K.trim().length>0&&(u.model=K.trim()),d!=="all"&&(u.status=d);const k=Ee(y),z=Ee(m,!0);return k!==void 0&&(u.from=k),z!==void 0&&(u.to=z),_.length>0&&(u.apiKeys=_.join(",")),u},[K,t,y,r,j,a,_,d,m]),Q=G(H.logs.list(ie),be.listRequest(ie),{gcTime:6e4,refetchInterval:L&&r===1?rt:!1}),W=G(H.providers.all(),_e.providersRequest()),je=G(H.apiKeys.all(),{url:"/api/keys",method:"GET"}),de=G(H.customEndpoints.all(),{url:"/api/custom-endpoints",method:"GET"}),ve=G(H.config.exportTimeout(),_e.configRequest());x.useEffect(()=>{!Q.isError||!Q.error||l({title:s("logs.toast.listError.title"),description:s("logs.toast.listError.desc",{message:Q.error.message}),variant:"error"})},[Q.error,Q.isError,l,s]),x.useEffect(()=>{!L||r!==1||typeof window>"u"||window.scrollY>=ot||window.scrollTo({top:0,behavior:"smooth"})},[L,r,Q.dataUpdatedAt]),x.useEffect(()=>{!W.isError||!W.error||l({title:s("logs.toast.providerError.title"),description:s("logs.toast.providerError.desc",{message:W.error.message}),variant:"error"})},[W.error,W.isError,l,s]);const se=((Ne=Q.data)==null?void 0:Ne.total)??0,Z=se>0?Math.ceil(se/j):0,Ye=((ke=Q.data)==null?void 0:ke.items)??[],Ze=x.useMemo(()=>{var k;const u=(k=ve.data)==null?void 0:k.logExportTimeoutSeconds;return typeof u=="number"&&Number.isFinite(u)?Math.min(Math.max(Math.round(u),5),600)*1e3:6e4},[(Se=ve.data)==null?void 0:Se.logExportTimeoutSeconds]);x.useEffect(()=>{Z>0&&r>Z&&g(Z)},[r,Z]);const ce=W.data??[],ue=x.useMemo(()=>{const u=new Map;for(const k of ce)k.id&&u.set(k.id,k.label??k.id);return u},[ce]),we=x.useMemo(()=>{var k;const u=new Map;u.set("anthropic",s("logs.filters.endpointAnthropic")),u.set("openai",s("logs.filters.endpointOpenAI"));for(const z of((k=de.data)==null?void 0:k.endpoints)??[])u.set(z.id,z.label||z.id);return u},[(Ce=de.data)==null?void 0:Ce.endpoints,s]),es=x.useMemo(()=>{const u=[];if(a!=="all"){const k=ue.get(a)??a;u.push({key:"provider",label:`${s("logs.filters.provider")}: ${k}`,onRemove:()=>o("all")})}if(t!=="all"){const k=we.get(t)??t;u.push({key:"endpoint",label:`${s("logs.filters.endpoint")}: ${k}`,onRemove:()=>i("all")})}if(K.trim()&&u.push({key:"model",label:`${s("logs.filters.modelId")}: ${K.trim()}`,onRemove:()=>h("")}),d!=="all"){const k=s(d==="success"?"logs.filters.statusSuccess":"logs.filters.statusError");u.push({key:"status",label:`${s("logs.filters.status")}: ${k}`,onRemove:()=>v("all")})}return y&&u.push({key:"from",label:`${s("logs.filters.startDate")}: ${y}`,onRemove:()=>w("")}),m&&u.push({key:"to",label:`${s("logs.filters.endDate")}: ${m}`,onRemove:()=>N("")}),_.length>0&&u.push({key:"apiKeys",label:s("logs.filters.apiKeySelected",{count:_.length}),onRemove:()=>ne([])}),u},[K,t,we,y,a,ue,_.length,d,s,m]),me=je.data??[],ss=x.useMemo(()=>{const u=new Map;for(const k of me)u.set(k.id,k);return u},[me]),ts=x.useMemo(()=>oe.map(u=>({id:u,label:s(`logs.table.columns.${u}`)})),[s]),ee=x.useMemo(()=>{const u=new Date;return`${u.getFullYear()}-${String(u.getMonth()+1).padStart(2,"0")}-${String(u.getDate()).padStart(2,"0")}`},[]),ls=x.useMemo(()=>a==="all"&&t==="all"&&K.trim()===""&&d==="all"&&y===""&&m===""&&_.length===0?"all":d==="error"&&t==="all"&&a==="all"&&K.trim()===""&&y===""&&m===""&&_.length===0?"errors":Js(y,m,ee)&&t==="all"&&a==="all"&&K.trim()===""&&d==="all"&&_.length===0?"today":t==="anthropic"&&a==="all"&&K.trim()===""&&d==="all"&&y===""&&m===""&&_.length===0?"anthropic":t==="openai"&&a==="all"&&K.trim()===""&&d==="all"&&y===""&&m===""&&_.length===0?"openai":null,[K,t,y,a,_.length,d,m,ee]),pe=x.useCallback(()=>{o("all"),h(""),i("all"),v("all"),w(""),N(""),ne([])},[]),as=x.useCallback(u=>{if(g(1),pe(),u!=="all"){if(u==="errors"){v("error");return}if(u==="today"){w(ee),N(ee);return}if(u==="anthropic"){i("anthropic");return}u==="openai"&&i("openai")}},[pe,ee]),{exporting:rs,handleExport:os}=tt({exportTimeoutMs:Ze,queryParams:ie,total:se}),ns=x.useCallback(u=>{p.removeQueries({queryKey:["logs","detail"],type:"inactive"}),C(u),F(!0)},[p]),is=x.useCallback(()=>{F(!1)},[]),ds=x.useCallback(u=>{c(k=>k===u?null:u)},[]);return x.useEffect(()=>{D||n===null||(p.removeQueries({queryKey:H.logs.detail(n),exact:!0}),C(null))},[D,p,n]),{activeFilters:es,activeQuickView:ls,apiKeyMap:ss,apiKeys:me,apiKeysQuery:je,applyQuickView:as,autoRefresh:L,columnOptions:ts,customEndpoints:(Le=de.data)==null?void 0:Le.endpoints,endpointFilter:t,exporting:rs,expandedLogId:T,filtersExpanded:Oe,fromDate:y,handleCloseDetail:is,handleExport:os,handleOpenDetail:ns,handleResetFilters:pe,handleToggleExpand:ds,isDetailOpen:D,items:Ye,logsQuery:Q,modelFilter:b,page:r,pageSize:j,providerFilter:a,providerLabelMap:ue,providerOptions:ce,rowDensity:Qe,resetVisibleColumns:$e,selectedApiKeys:_,selectedLogId:n,setAutoRefresh:f,setEndpointFilter:i,setFiltersExpanded:Ie,setFromDate:w,setModelFilter:h,setPage:g,setPageSize:S,setProviderFilter:o,setRowDensity:Ue,setSelectedApiKeys:ne,setStatusFilter:v,setToDate:N,showScrollHint:Ve,statusFilter:d,tableScrollRef:He,toDate:m,toggleColumn:Be,total:se,totalPages:Z,visibleColumnCount:We,visibleColumns:Ge,visibleColumnSet:Je}}function Et(){var l;const s=nt();return e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx(bs,{actions:e.jsx(Xs,{autoRefresh:s.autoRefresh,columnOptions:s.columnOptions,exporting:s.exporting,onExport:()=>void s.handleExport(),onRefresh:()=>void s.logsQuery.refetch(),onResetColumns:s.resetVisibleColumns,onSetDensity:s.setRowDensity,onToggleAutoRefresh:s.setAutoRefresh,onToggleColumn:s.toggleColumn,refreshing:s.logsQuery.isFetching,rowDensity:s.rowDensity,visibleColumns:s.visibleColumns,visibleColumnSet:s.visibleColumnSet})}),e.jsx(Vs,{activeFilters:s.activeFilters,filtersExpanded:s.filtersExpanded,setFiltersExpanded:s.setFiltersExpanded,handleResetFilters:s.handleResetFilters,activeQuickView:s.activeQuickView,applyQuickView:s.applyQuickView,providerFilter:s.providerFilter,setProviderFilter:s.setProviderFilter,endpointFilter:s.endpointFilter,setEndpointFilter:s.setEndpointFilter,selectedApiKeys:s.selectedApiKeys,setSelectedApiKeys:s.setSelectedApiKeys,modelFilter:s.modelFilter,setModelFilter:s.setModelFilter,statusFilter:s.statusFilter,setStatusFilter:s.setStatusFilter,fromDate:s.fromDate,setFromDate:s.setFromDate,toDate:s.toDate,setToDate:s.setToDate,providerOptions:s.providerOptions,apiKeys:s.apiKeys,apiKeysLoading:s.apiKeysQuery.isLoading,customEndpoints:s.customEndpoints}),e.jsx(st,{tableScrollRef:s.tableScrollRef,visibleColumnSet:s.visibleColumnSet,visibleColumnCount:s.visibleColumnCount,logsError:s.logsQuery.isError?((l=s.logsQuery.error)==null?void 0:l.message)??null:null,logsPending:s.logsQuery.isPending,items:s.items,activeFiltersCount:s.activeFilters.length,total:s.total,handleResetFilters:s.handleResetFilters,handleRetry:()=>void s.logsQuery.refetch(),providerLabelMap:s.providerLabelMap,apiKeyMap:s.apiKeyMap,handleOpenDetail:s.handleOpenDetail,expandedLogId:s.expandedLogId,onToggleExpand:s.handleToggleExpand,rowDensity:s.rowDensity,showScrollHint:s.showScrollHint,pageSize:s.pageSize,setPageSize:s.setPageSize,page:s.page,totalPages:s.totalPages,setPage:s.setPage}),e.jsx(Hs,{open:s.isDetailOpen,logId:s.selectedLogId,onClose:s.handleCloseDetail,providerLabelMap:s.providerLabelMap,apiKeyMap:s.apiKeyMap})]})}export{Et as default};
|
package/src/web/dist/assets/{ProvidersWorkbench-Bb3ZnLKq.js → ProvidersWorkbench-CQs_hU5D.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as f,ax as Nt,j as e,ay as wt,as as ft,ab as ge,az as kt,aA as Ct,aB as St,aC as Mt,aD as Pt,aE as Et,aF as ct,aG as Dt,aH as Rt,aI as Tt,aJ as Ot,aK as Lt,aL as Ft,aM as It,aN as At,aO as Bt}from"./vendor-CITafuNQ.js";import{d as $t}from"./router-BoBrmro7.js";import{C as Ht}from"./ConfirmDialog-MHzJAg_R.js";import{P as qt}from"./PageToolbar-BdMtFJ0X.js";import{t as xe,q as Ee,e as $e,B as q,c as bt,b as zt,s as Ut,T as Vt,f as _t,g as Kt,h as Qt}from"./app-ClWj0qTa.js";import{B as oe}from"./badge-BYKFKxPI.js";import{c as Ne}from"./global-CHsQhrWl.js";import{d as ut,g as mt,a as pt,b as Gt,c as ht,e as xt,r as Wt,f as Be,m as Ve,h as Jt,u as Xt,P as lt,i as Yt,j as Oe,S as Zt,B as es,M as ts,k as ss,l as as,C as vt,O as jt,n as rs,o as ns}from"./useProviderForm-Bh-rUNZP.js";import{a as os}from"./query-DZF7K6hv.js";import{g as Le}from"./gateway-D48923x2.js";import{u as Ke}from"./useAppMutation-B4G9utID.js";import{D as Xe,A as Ye,a as Ze,b as et,c as tt,d as st,e as at}from"./DialogShell-Dadn4IyM.js";import{L as ye,I as fe}from"./label-D10XnuKJ.js";import{S as Qe,a as Ge,b as We,c as Je,d as Fe}from"./select-Csn9x4DW.js";import{S as rt}from"./switch-CgcoKdbt.js";import{u as W}from"./i18n-PeX9kBVO.js";import{C as He,a as qe}from"./card-BzBD4ugM.js";import{a as it}from"./PageState-BfMFsTrq.js";import{b as is}from"./types-DYz12j32.js";import{D as ls}from"./disclosure-DtTSMZlG.js";import{P as ds,c as cs,b as us}from"./popover-CVazrITd.js";import"./radix-Bux_1C5J.js";function ms(a){const{t,pushToast:i,config:s,setConfig:n,configQuery:p,customEndpoints:h,tabs:k,ensureConfig:g}=a,y=os(),[l,u]=f.useState({}),[d,w]=f.useState({}),[b,c]=f.useState(null),[v,N]=f.useState({}),[C,R]=f.useState({}),[Z,K]=f.useState({}),[T,j]=f.useState(null),[D,B]=f.useState(null),[z,V]=f.useState(null),[ae,A]=f.useState(!1),[ie,X]=f.useState(null),[M,I]=f.useState({}),[H,Ce]=f.useState(null),re=f.useRef(null),[Se,me]=f.useState(null),pe=r=>{re.current=r,me(r)},he=()=>{re.current=null,me(null)},be=f.useMemo(()=>k.filter(r=>r.key!=="providers"),[k]);f.useEffect(()=>{if(!p.data)return;const r=p.data;u(m=>{const o=ut(r,h);if(!m||Object.keys(m).length===0)return o;const x={...o};for(const[S,O]of Object.entries(m)){if(!(S in o))continue;const F=mt(r,h,S);if(pt(O,F))x[S]=O;else{const J=new Map(O.map(_=>[_.source,_.id]));x[S]=o[S].map(_=>({..._,id:J.get(_.source)??_.id}))}}return x}),I(m=>{const o=Gt(r,h);if(!m||Object.keys(m).length===0)return o;const x={...o};for(const[S,O]of Object.entries(m)){if(!(S in o))continue;const F=ht(r,h,S);JSON.stringify(O)!==JSON.stringify(F)&&(x[S]=O)}return x}),w({}),N(xt(r,h))},[p.data,h]);const we=(s==null?void 0:s.providers)??[],ke=f.useMemo(()=>{const r=[],m=new Set;for(const o of we){const x=o.label&&o.label!==o.id?`${o.label} (${o.id})`:o.id,S=o.models??[];if(S.length>0)for(const F of S){const J=`${o.id}:${F.id}`;m.has(J)||(m.add(J),r.push({value:J,label:`${x} · ${F.label??F.id}`,providerId:o.id,providerLabel:x,modelId:F.id,modelLabel:F.label??F.id,kind:"model",isDefault:o.defaultModel===F.id}))}else if(o.defaultModel){const F=`${o.id}:${o.defaultModel}`;m.has(F)||(m.add(F),r.push({value:F,label:`${x} · ${o.defaultModel}`,providerId:o.id,providerLabel:x,modelId:o.defaultModel,modelLabel:o.defaultModel,kind:"model",isDefault:!0}))}const O=`${o.id}:*`;m.has(O)||(m.add(O),r.push({value:O,label:t("settings.routing.providerPassthroughOption",{provider:x}),providerId:o.id,providerLabel:x,modelId:"*",modelLabel:"*",kind:"passthrough"}))}for(const o of Object.values(l).flat()){const x=o.target.trim();x&&!m.has(x)&&(m.add(x),r.push({value:x,label:x,modelId:x,modelLabel:x,kind:"custom"}))}return r},[we,l,t]),L=r=>s?mt(s,h,r):{},Y=f.useMemo(()=>{const r={};for(const m of be){const o=l[m.key]||[];r[m.key]=pt(o,L(m.key))}return r},[s,h,l,be]),ce=f.useMemo(()=>{const r={};if(!s)return r;for(const m of be){const o=M[m.key];if(!o){r[m.key]=!1;continue}const x=ht(s,h,m.key);r[m.key]=JSON.stringify(o)!==JSON.stringify(x)}return r},[s,h,M,be]),dt=(r,m,o)=>{I(x=>({...x,[r]:{...x[r]??{completion:null,reasoning:null,background:null,longContextThreshold:6e4},[m]:o}}))},P=async r=>{var x,S,O,F,J,_,Q,ne;if(!g()||re.current)return;const m=M[r];if(!m)return;const o={completion:(x=m.completion)!=null&&x.trim()?m.completion.trim():null,reasoning:(S=m.reasoning)!=null&&S.trim()?m.reasoning.trim():null,background:(O=m.background)!=null&&O.trim()?m.background.trim():null,longContextThreshold:Number.isFinite(m.longContextThreshold)&&m.longContextThreshold>0?Math.floor(m.longContextThreshold):s.defaults.longContextThreshold};Ce(r),pe(r);try{const te=h.find(G=>G.id===r);if(te){const G={...te.routing??{},defaults:o,modelRoutes:((F=te.routing)==null?void 0:F.modelRoutes)??{}};await $e.update(r,{routing:G}),n(de=>{if(!de)return de;const Ue=[...de.customEndpoints??[]],nt=Ue.findIndex(yt=>yt.id===r);return nt===-1?de:(Ue[nt]={...Ue[nt],routing:G},{...de,customEndpoints:Ue})}),await y.invalidateQueries({queryKey:Ee.customEndpoints.all()})}else{const G=r,de={...s,endpointRouting:{...s.endpointRouting??{},[G]:{defaults:o,modelRoutes:((_=(J=s.endpointRouting)==null?void 0:J[G])==null?void 0:_.modelRoutes)??(G==="anthropic"?s.modelRoutes??{}:{}),compatibility:(ne=(Q=s.endpointRouting)==null?void 0:Q[G])==null?void 0:ne.compatibility}}};await Le.saveConfig(de),n(de)}I(G=>({...G,[r]:o})),i({title:t("workbench.defaults.saveSuccess"),variant:"success"}),p.refetch()}catch(te){i({title:t("workbench.defaults.saveFailure",{message:xe(te).message}),variant:"error"})}finally{Ce(null),he()}},$=(r,m)=>{N(o=>({...o,[r]:m})),n(o=>{if(!o)return o;if(r==="anthropic"||r==="openai")return{...o,routingPresets:{...o.routingPresets,[r]:m}};const x=[...o.customEndpoints??[]],S=x.findIndex(O=>O.id===r);return S===-1?o:(x[S]={...x[S],routingPresets:m},{...o,customEndpoints:x})})},U=(r,m)=>{R(o=>({...o,[r]:m})),m.trim()&&K(o=>({...o,[r]:null}))},E=async r=>{if(!g()||re.current)return;const m=(C[r]??"").trim();if(!m){K(o=>({...o,[r]:t("modelManagement.validation.presetName")}));return}if((v[r]??[]).some(o=>o.name.toLowerCase()===m.toLowerCase())){K(o=>({...o,[r]:t("modelManagement.validation.presetDuplicate",{name:m})}));return}j(r),pe(r);try{const x=(await Ve.savePreset(r,m)).presets??[];$(r,x),R(S=>({...S,[r]:""})),K(S=>({...S,[r]:null})),i({title:t("modelManagement.toast.presetSaved",{name:m}),variant:"success"})}catch(o){i({title:t("modelManagement.toast.presetSaveFailure",{message:xe(o).message}),variant:"error"})}finally{j(null),he(),p.refetch()}},ee=async(r,m)=>{if(g()&&!re.current){B({endpoint:r,name:m.name}),pe(r);try{const x=(await Ve.applyPreset(r,m.name)).config;n(x);const S=ut(x,h);u(O=>({...O,[r]:S[r]??[]})),N(xt(x,h)),r!=="anthropic"&&r!=="openai"&&await y.invalidateQueries({queryKey:Ee.customEndpoints.all()}),i({title:t("modelManagement.toast.presetApplySuccess",{name:m.name}),variant:"success"})}catch(o){i({title:t("modelManagement.toast.presetApplyFailure",{message:xe(o).message}),variant:"error"})}finally{B(null),he(),p.refetch()}}},ve=async(r,m)=>{if(g()&&!re.current){V({endpoint:r,name:m.name}),pe(r);try{const o=await Ve.deletePreset(r,m.name);$(r,o.presets??[]),i({title:t("modelManagement.toast.presetDeleteSuccess",{name:m.name}),variant:"success"})}catch(o){i({title:t("modelManagement.toast.presetDeleteFailure",{message:xe(o).message}),variant:"error"})}finally{V(null),he(),p.refetch()}}},De=async r=>{const m=h.find(o=>o.id===r);if(!(!m||m.deletable===!1))try{await $e.delete(r),await y.invalidateQueries({queryKey:Ee.customEndpoints.all()}),n(o=>o&&{...o,customEndpoints:(o.customEndpoints??[]).filter(x=>x.id!==r)}),p.refetch(),i({title:t("modelManagement.deleteEndpointSuccess"),variant:"success"})}catch(o){const x=xe(o);i({title:t("modelManagement.deleteEndpointError",{error:x.message}),variant:"error"})}},Me=r=>{u(m=>({...m,[r]:[...m[r]||[],{id:Be(),source:"",target:""}]})),w(m=>({...m,[r]:null}))},se=async(r,m)=>{if(g()&&!re.current){A(!0),pe(r);try{if(r==="anthropic"||r==="openai"){const o=r,x=s.endpointRouting?{...s.endpointRouting}:{},S=x[o]??{defaults:s.defaults,modelRoutes:(o==="anthropic"?s.modelRoutes:{})??{}},O={defaults:S.defaults??s.defaults,modelRoutes:S.modelRoutes??{}},F={...s,endpointRouting:{...x,[o]:m?{...O,compatibility:{enabled:!0}}:{...O}}};await Le.saveConfig(F),n(F)}else{const o=[...s.customEndpoints??[]],x=o.findIndex(J=>J.id===r);if(x===-1)throw new Error(t("modelManagement.toast.endpointNotFound"));const S=o[x],O=S.routing??{defaults:s.defaults,modelRoutes:{}};o[x]={...S,routing:m?{...O,compatibility:{enabled:!0}}:{defaults:O.defaults,modelRoutes:O.modelRoutes}};const F={...s,customEndpoints:o};await Le.saveConfig(F),n(F)}i({title:t("modelManagement.toast.compatibilitySaved",{state:t(m?"common.status.enabled":"common.status.disabled")}),variant:"success"}),p.refetch()}catch(o){const x=xe(o);i({title:t("modelManagement.toast.compatibilitySaveFailure",{message:x.message}),variant:"error"})}finally{A(!1),he()}}},je=(r,m)=>{u(o=>{const x=o[r]||[];return x.some(S=>S.source.trim()===m.trim())?o:{...o,[r]:[...x,{id:Be(),source:m,target:""}]}}),w(o=>({...o,[r]:null}))},Re=(r,m,o,x)=>{u(S=>({...S,[r]:(S[r]||[]).map(O=>O.id===m?{...O,[o]:x}:O)})),w(S=>({...S,[r]:null}))},Pe=(r,m)=>{u(o=>({...o,[r]:(o[r]||[]).filter(x=>x.id!==m)})),w(o=>({...o,[r]:null}))},Te=(r,m,o)=>{m!==o&&(u(x=>{const S=x[r]||[],O=S.findIndex(J=>J.id===m),F=S.findIndex(J=>J.id===o);return O===-1||F===-1?x:{...x,[r]:Nt(S,O,F)}}),w(x=>({...x,[r]:null})))},ze=r=>{var o;if(!s)return;const m=(s.customEndpoints??h).find(x=>x.id===r);if(m)u(x=>{var S;return{...x,[r]:Object.entries(((S=m.routing)==null?void 0:S.modelRoutes)??{}).map(([O,F])=>({id:Be(),source:O,target:F}))}});else{const x=s.endpointRouting??{},S=r,O=S==="anthropic"?s.modelRoutes??{}:{},F=((o=x[S])==null?void 0:o.modelRoutes)??O;u(J=>({...J,[r]:Object.entries(F).map(([_,Q])=>({id:Be(),source:_,target:Q}))}))}w(x=>({...x,[r]:null}))},le=Ke({mutationFn:async r=>(await Le.saveConfig(r.nextConfig),r)}),ue=Ke({mutationFn:async r=>(await $e.update(r.endpoint,{routing:r.routing}),r)});return{endpointTabs:be,routesByEndpoint:l,setRoutesByEndpoint:u,routeError:d,savingRouteFor:b,presetsByEndpoint:v,presetNameByEndpoint:C,presetErrorByEndpoint:Z,savingPresetFor:T,applyingPreset:D,deletingPreset:z,savingCompatibilityPolicy:ae,writingEndpoint:Se,presetDiffDialog:ie,setPresetDiffDialog:X,providerModelOptions:ke,isDirtyByEndpoint:Y,defaultsByEndpoint:M,isDefaultsDirtyByEndpoint:ce,savingDefaultsFor:H,handleDefaultsChange:dt,handleSaveDefaults:P,handlePresetNameChange:U,handleSavePreset:E,handleApplyPreset:ee,handleDeletePreset:ve,handleDeleteEndpoint:De,handleAddRoute:Me,handleAddSuggestion:je,handleRouteChange:Re,handleRemoveRoute:Pe,handleReorderRules:Te,handleResetRoutes:ze,handleSaveRoutes:async r=>{var x,S,O,F,J;if(!g()||re.current)return;const m=l[r]||[],o={};for(const _ of m){const Q=_.source.trim(),ne=_.target.trim();if(!(!Q&&!ne)){if(!Q||!ne){w(te=>({...te,[r]:t("settings.validation.routePair")}));return}if(o[Q]){w(te=>({...te,[r]:t("settings.validation.routeDuplicate",{model:Q})}));return}o[Q]=ne}}w(_=>({..._,[r]:null})),c(r),pe(r);try{const _=h.find(Q=>Q.id===r);if(_){const Q={..._.routing??{},modelRoutes:o,defaults:((x=_.routing)==null?void 0:x.defaults)||s.defaults};await ue.mutateAsync({endpoint:r,routing:Q}),n(ne=>{if(!ne)return ne;const te=[...ne.customEndpoints??[]],G=te.findIndex(de=>de.id===r);return G===-1?ne:(te[G]={...te[G],routing:Q},{...ne,customEndpoints:te})}),await y.invalidateQueries({queryKey:Ee.customEndpoints.all()})}else{const Q={...s,endpointRouting:{...s.endpointRouting??{},[r]:{defaults:((O=(S=s.endpointRouting)==null?void 0:S[r])==null?void 0:O.defaults)??s.defaults,modelRoutes:o,compatibility:(J=(F=s.endpointRouting)==null?void 0:F[r])==null?void 0:J.compatibility}},modelRoutes:r==="anthropic"?o:s.modelRoutes??{}};await le.mutateAsync({endpoint:r,nextConfig:Q}),n(Q)}u(Q=>{const ne=Q[r]??[],te=new Map(ne.map(G=>[G.source.trim(),G.id]));return{...Q,[r]:Object.entries(o).map(([G,de])=>({id:te.get(G.trim())??Be(),source:G,target:de}))}}),i({title:t("modelManagement.toast.routesSaved"),variant:"success"}),p.refetch()}catch(_){i({title:t("modelManagement.toast.routesSaveFailure",{message:xe(_).message}),variant:"error"})}finally{c(null),he()}},handleCompatibilityEnabledChange:se,sanitizeDraftsForProvider:r=>{u(m=>{const o={};for(const[x,S]of Object.entries(m))o[x]=S.filter(O=>!Wt(O.target.trim(),r));return o})}}}function ps(a,t){const{t:i,pushToast:s,config:n,setConfig:p,configQuery:h,customEndpoints:k,ensureConfig:g}=a,{sanitizeDraftsForProvider:y}=t??{},[l,u]=f.useState(""),[d,w]=f.useState("all"),[b,c]=f.useState(!1),[v,N]=f.useState("create"),[C,R]=f.useState(void 0),[Z,K]=f.useState(null),[T,j]=f.useState({}),[D,B]=f.useState(!1),[z,V]=f.useState(null),[ae,A]=f.useState(!0),[ie,X]=f.useState({}),[M,I]=f.useState(null),H=(n==null?void 0:n.providers)??[],Ce=H.length,re=f.useMemo(()=>H.filter(P=>{var ee;if(!(d==="all"||(P.type??"custom")===d))return!1;const U=l.trim().toLowerCase();return U?[P.id,P.label??"",P.baseUrl,P.defaultModel??"",...((ee=P.models)==null?void 0:ee.map(ve=>ve.id))??[]].join(" ").toLowerCase().includes(U):!0}),[l,d,H]),Se=f.useMemo(()=>{const P=new Map;for(const $ of H){if(!$.defaultModel||!$.models)continue;const U=$.models.find(E=>E.id===$.defaultModel);U&&P.set($.id,Jt(U))}return P},[H]),me=f.useMemo(()=>[{key:"anthropic-beta",value:"claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14",label:i("providers.testDialog.options.beta.label"),description:i("providers.testDialog.options.beta.description")}],[i]),pe=()=>{g()&&(N("create"),R(void 0),c(!0))},he=P=>{g()&&(N("edit"),R(P),c(!0))},be=async P=>{if(!n)throw new Error(i("settings.toast.missingConfig"));const $=v==="create"?[...H,P]:H.map(E=>C&&E.id===C.id?{...P,id:C.id}:E),U={...n,providers:$};await Le.saveConfig(U),p(U),h.refetch(),s({title:v==="create"?i("providers.toast.createSuccess",{name:P.label||P.id}):i("providers.toast.updateSuccess",{name:P.label||P.id}),variant:"success"})},we=(P,$)=>{j(U=>({...U,[P]:$}))},ke=async(P,$)=>{K(P.id);try{const U=$&&($.headers||$.query)?{headers:$.headers&&Object.keys($.headers).length>0?$.headers:void 0,query:$.query&&$.query.trim().length>0?$.query.trim():void 0}:void 0,E=await Ve.testProvider(P.id,U);if(E.ok){we(P.id,{ok:!0,status:E.status,statusText:E.statusText,durationMs:E.durationMs,testedAt:Date.now()}),s({title:i("providers.toast.testSuccess"),description:i("providers.toast.testSuccessDesc",{status:E.status,duration:E.durationMs?`${E.durationMs} ms`:"—"}),variant:"success"});return}we(P.id,{ok:!1,status:E.status,statusText:E.statusText,durationMs:E.durationMs,message:`${E.status} ${E.statusText}`,testedAt:Date.now()}),s({title:i("providers.toast.testFailure",{message:`${E.status} ${E.statusText}`}),variant:"error"})}catch(U){const E=xe(U),ee=E.status?`${E.status} ${E.message}`:E.message;we(P.id,{ok:!1,status:E.status,message:ee,testedAt:Date.now()}),s({title:i("providers.toast.testFailure",{message:ee}),variant:"error"})}finally{K(null)}},L=P=>{var De,Me;if(!(!!((De=P.defaultModel)!=null&&De.trim())||!!((Me=P.models)!=null&&Me.some(se=>se.id.trim().length>0)))){I(P);return}if(P.type!=="anthropic"){ke(P);return}const U=P.extraHeaders??{},E=new Map(me.map(se=>[se.key.toLowerCase(),se])),ee={};let ve=!0;for(const se of me){const je=Object.entries(U).find(([Te])=>Te.toLowerCase()===se.key.toLowerCase());if(!je)continue;const[Re,Pe]=je;String(Pe??"")!==se.value&&(ve=!1,ee[Re]=String(Pe??""))}for(const[se,je]of Object.entries(U))E.has(se.toLowerCase())||(ee[se]=String(je??""));X(ee),A(ve),V(P),B(!0)},Y=()=>{B(!1),V(null),A(!0),X({})};return{providers:H,providerCount:Ce,filteredProviders:re,providerSearch:l,setProviderSearch:u,providerTypeFilter:d,setProviderTypeFilter:w,defaultLabels:Se,drawerOpen:b,setDrawerOpen:c,drawerMode:v,setDrawerMode:N,editingProvider:C,setEditingProvider:R,testingProviderId:Z,testResults:T,testDialogOpen:D,testDialogProvider:z,testDialogUsePreset:ae,setTestDialogUsePreset:A,testDialogPreservedExtras:ie,noModelDialogProvider:M,setNoModelDialogProvider:I,anthropicTestHeaderOptions:me,handleOpenCreate:pe,handleOpenEdit:he,handleProviderSubmit:be,handleDeleteProvider:async P=>{var se,je,Re,Pe,Te,ze;if(!g())return;const $=H.filter(le=>le.id!==P.id),U=le=>{const ue={};if(!le)return ue;for(const[Ie,Ae]of Object.entries(le)){if(!Ae)continue;const[r]=Ae.split(":");r&&r===P.id||Ae===P.id||(ue[Ie]=Ae)}return ue},E=(n==null?void 0:n.endpointRouting)??{},ee=U(((se=E.anthropic)==null?void 0:se.modelRoutes)??(n==null?void 0:n.modelRoutes)??{}),ve=U(((je=E.openai)==null?void 0:je.modelRoutes)??{}),De=((n==null?void 0:n.customEndpoints)??k).map(le=>{const ue=le.routing,Ie=ue==null?void 0:ue.modelRoutes;return Ie?{...le,routing:{...ue,defaults:ue.defaults??n.defaults,modelRoutes:U(Ie)}}:le}),Me={...n,providers:$,modelRoutes:ee,customEndpoints:De,endpointRouting:{anthropic:{defaults:((Re=E.anthropic)==null?void 0:Re.defaults)??n.defaults,modelRoutes:ee,compatibility:(Pe=E.anthropic)==null?void 0:Pe.compatibility},openai:{defaults:((Te=E.openai)==null?void 0:Te.defaults)??n.defaults,modelRoutes:ve,compatibility:(ze=E.openai)==null?void 0:ze.compatibility}}};try{await Le.saveConfig(Me),p(Me),y==null||y(P.id),(C==null?void 0:C.id)===P.id&&(c(!1),R(void 0),N("create")),s({title:i("providers.toast.deleteSuccess",{name:P.label||P.id}),variant:"success"}),h.refetch()}catch(le){s({title:i("providers.toast.deleteFailure",{message:xe(le).message}),variant:"error"})}},handleTestConnection:ke,initiateTestConnection:L,closeTestDialog:Y,confirmTestDialog:async()=>{if(!z)return;const P={};if(ae)for(const E of me)P[E.key]=E.value;const $=new Map(me.map(E=>[E.key.toLowerCase(),E]));for(const[E,ee]of Object.entries(ie))$.get(E.toLowerCase())&&ae||(P[E]=ee);const U=z;Y(),await ke(U,{headers:Object.keys(P).length>0?P:void 0})}}}const hs=["anthropic","openai-auto","openai-chat","openai-responses"];function xs({open:a,endpoint:t,onClose:i,onSuccess:s}){const{t:n}=W(),[p,h]=f.useState({id:"",label:"",paths:[{path:"",protocol:"openai-auto"}],enabled:!0});f.useEffect(()=>{if(a){if(t){const c=t.paths&&t.paths.length>0?t.paths:t.path&&t.protocol?[{path:t.path,protocol:t.protocol}]:[{path:"",protocol:"openai-auto"}];h({id:t.id,label:t.label,paths:c,enabled:t.enabled!==!1});return}h({id:"",label:"",paths:[{path:"",protocol:"openai-auto"}],enabled:!0})}},[t,a]);const k=Ke({mutationFn:$e.create,invalidateKeys:[Ee.customEndpoints.all()],successToast:()=>({title:n("modelManagement.createEndpointSuccess")}),errorToast:c=>({title:n("modelManagement.createEndpointError",{error:c.message})}),onSuccess:async()=>{s(),i()}}),g=Ke({mutationFn:c=>$e.update(c.id,c.updates),invalidateKeys:[Ee.customEndpoints.all()],successToast:()=>({title:n("modelManagement.updateEndpointSuccess")}),errorToast:c=>({title:n("modelManagement.updateEndpointError",{error:c.message})}),onSuccess:async()=>{s(),i()}}),y=()=>{h(c=>({...c,paths:[...c.paths,{path:"",protocol:"anthropic"}]}))},l=c=>{p.paths.length!==1&&h(v=>({...v,paths:v.paths.filter((N,C)=>C!==c)}))},u=(c,v,N)=>{h(C=>{const R=[...C.paths];return R[c]={...R[c],[v]:N},{...C,paths:R}})},d=c=>{if(c==null||c.preventDefault(),!p.id.trim()||!p.label.trim())return;for(const N of p.paths)if(!N.path.trim())return;const v=p.paths.map(N=>({path:N.path.trim(),protocol:N.protocol}));if(t){g.mutate({id:t.id,updates:{label:p.label.trim(),paths:v,enabled:p.enabled}});return}k.mutate({id:p.id.trim(),label:p.label.trim(),paths:v,enabled:p.enabled})},w=k.isPending||g.isPending,b=p.paths.length===0?n("modelManagement.atLeastOnePath"):!p.id.trim()||!p.label.trim()?n("modelManagement.endpointValidationError"):p.paths.some(c=>!c.path.trim())?n("modelManagement.pathValidationError"):null;return e.jsx(Xe,{open:a,onOpenChange:c=>!c&&i(),children:e.jsxs(Ye,{className:"max-w-lg",onInteractOutside:c=>c.preventDefault(),children:[e.jsxs(Ze,{children:[e.jsx(et,{children:n(t?"modelManagement.editEndpoint":"modelManagement.createEndpoint")}),e.jsx(tt,{className:"truncate font-mono text-xs",children:t?t.id:n("modelManagement.endpointRoutingHint")})]}),e.jsx(st,{children:e.jsxs("form",{id:"endpoint-form",onSubmit:d,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ye,{children:[n("modelManagement.endpointId")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(fe,{value:p.id,onChange:c=>h(v=>({...v,id:c.target.value})),placeholder:n("modelManagement.endpointIdPlaceholder"),disabled:!!t,required:!0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:n("modelManagement.endpointIdHint")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ye,{children:[n("modelManagement.endpointLabel")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(fe,{value:p.label,onChange:c=>h(v=>({...v,label:c.target.value})),placeholder:n("modelManagement.endpointLabelPlaceholder"),required:!0})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ye,{children:[n("modelManagement.endpointPaths")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsxs(q,{type:"button",variant:"ghost",size:"sm",onClick:y,children:[e.jsx(wt,{className:"mr-1 h-3 w-3"}),n("modelManagement.addPath")]})]}),e.jsx("div",{className:"space-y-3",children:p.paths.map((c,v)=>e.jsxs("div",{className:"space-y-2 rounded-xl border border-transparent bg-card p-3 shadow-[var(--surface-shadow)]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(fe,{value:c.path,onChange:N=>u(v,"path",N.target.value),placeholder:n("modelManagement.endpointPathPlaceholder"),required:!0}),e.jsxs(Qe,{value:c.protocol,onValueChange:N=>u(v,"protocol",N),children:[e.jsx(Ge,{children:e.jsx(We,{})}),e.jsx(Je,{children:hs.map(N=>e.jsx(Fe,{value:N,children:n(N==="anthropic"?"modelManagement.protocolAnthropic":N==="openai-auto"?"modelManagement.protocolOpenAI":N==="openai-chat"?"modelManagement.protocolOpenAIChat":"modelManagement.protocolOpenAIResponses")},N))})]})]}),p.paths.length>1?e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>l(v),className:"text-destructive",children:e.jsx(ft,{className:"h-4 w-4"})}):null]}),e.jsxs("div",{className:"space-y-1 text-xs text-muted-foreground",children:[v===0?e.jsx("p",{children:n("modelManagement.endpointPathHint")}):null,e.jsx("p",{children:n(`modelManagement.protocolHints.${c.protocol}`)})]})]},`${c.protocol}-${v}`))}),b?e.jsx("p",{className:"text-xs text-destructive",children:b}):null]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(rt,{id:"endpoint-enabled",checked:p.enabled,onCheckedChange:c=>h(v=>({...v,enabled:c}))}),e.jsx(ye,{htmlFor:"endpoint-enabled",children:n("modelManagement.endpointEnabled")})]}),t?null:e.jsx("div",{className:"rounded-xl bg-accent p-4",children:e.jsx("p",{className:"text-sm text-primary",children:n("modelManagement.endpointRoutingHint")})})]})}),e.jsxs(at,{children:[e.jsx(q,{variant:"outline",onClick:i,disabled:w,children:n("common.cancel")}),e.jsx(q,{type:"submit",form:"endpoint-form",disabled:w,children:n(w?"common.saving":t?"common.save":"common.create")})]})]})})}function gs({open:a,provider:t,onClose:i,onEdit:s}){const{t:n}=W();return t?e.jsx(Xe,{open:a,onOpenChange:p=>!p&&i(),children:e.jsxs(Ye,{className:"max-w-md",children:[e.jsxs(Ze,{children:[e.jsx(et,{children:n("providers.noModelDialog.title")}),e.jsx(tt,{children:n("providers.noModelDialog.subtitle",{name:t.label||t.id})})]}),e.jsxs(st,{className:"space-y-4",children:[e.jsx("div",{className:"rounded-xl bg-accent p-4 text-sm text-primary",children:n("providers.noModelDialog.description")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:n("providers.noModelDialog.hint")})]}),e.jsxs(at,{children:[e.jsx(q,{variant:"outline",onClick:i,children:n("common.actions.close")}),e.jsx(q,{onClick:()=>s(t),children:n("providers.noModelDialog.primary")})]})]})}):null}function fs({dialog:a,currentRoutes:t,onConfirm:i,onClose:s}){const{t:n}=W();if(!a)return null;const{endpoint:p,preset:h}=a,k=h.modelRoutes??{},g={};for(const b of t){const c=b.source.trim(),v=b.target.trim();c&&v&&(g[c]=v)}const y=new Set([...Object.keys(g),...Object.keys(k)]),l=[],u=[],d=[];for(const b of y){const c=b in g,v=b in k;v&&!c?l.push([b,k[b]]):c&&!v?u.push([b,g[b]]):c&&v&&g[b]!==k[b]&&d.push([b,g[b],k[b]])}const w=l.length>0||u.length>0||d.length>0;return e.jsx(Xe,{open:!0,onOpenChange:b=>!b&&s(),children:e.jsxs(Ye,{className:"max-w-2xl",children:[e.jsxs(Ze,{children:[e.jsx(et,{children:n("modelManagement.presets.diffTitle")}),e.jsx(tt,{children:n("modelManagement.presets.diffDescription",{name:h.name})})]}),e.jsx(st,{children:w?e.jsxs("div",{className:"max-h-80 space-y-2 rounded-xl bg-secondary/50 p-3 text-sm",children:[l.map(([b,c])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-success-bg px-2 py-1.5 text-success",children:[e.jsx(oe,{variant:"outline",className:"border-success/30 text-xs",children:n("modelManagement.presets.diffAdded")}),e.jsx("span",{className:"truncate",children:b}),e.jsx(ge,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:c})]},`add-${b}`)),u.map(([b,c])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-error-bg px-2 py-1.5 text-error",children:[e.jsx(oe,{variant:"outline",className:"border-error/30 text-xs",children:n("modelManagement.presets.diffRemoved")}),e.jsx("span",{className:"truncate",children:b}),e.jsx(ge,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:c})]},`rm-${b}`)),d.map(([b,c,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(oe,{variant:"outline",className:"border-warning/30 text-xs",children:n("modelManagement.presets.diffChanged")}),e.jsx("span",{className:"truncate",children:b}),e.jsx(ge,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate line-through opacity-60",children:c}),e.jsx(ge,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:v})]},`chg-${b}`))]}):e.jsx("p",{className:"rounded-xl bg-secondary/50 py-8 text-center text-sm text-muted-foreground",children:n("modelManagement.presets.diffEmpty")})}),e.jsxs(at,{children:[e.jsx(q,{variant:"outline",onClick:s,children:n("common.cancel")}),e.jsx(q,{onClick:()=>i(p,h),disabled:!w,children:n("modelManagement.presets.diffConfirm")})]})]})})}function bs({open:a,mode:t,provider:i,existingProviderIds:s,onClose:n,onSubmit:p,testResult:h,testing:k,onTest:g,onDelete:y}){const{t:l}=W(),u=Xt({mode:t,provider:i,existingProviderIds:s}),{form:d,errors:w,advancedOpen:b,providerIdRef:c}=u,[v,N]=f.useState(!1),[C,R]=f.useState(null),[Z,K]=f.useState("basics"),T=f.useRef(null),j=f.useRef(null);f.useEffect(()=>{a&&(u.resetForm(),R(null),N(!1),K("basics"))},[a,i,t,u.resetForm]);const D=f.useRef(n);D.current=n,f.useEffect(()=>{if(!a)return;const L=Y=>{Y.key==="Escape"&&(document.querySelector('[role="dialog"][data-state="open"], [role="listbox"][data-state="open"], [data-radix-popper-content-wrapper]')||D.current())};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[a]),f.useEffect(()=>{if(a){if(t==="create"&&c.current){c.current.focus();return}j.current&&j.current.focus()}},[a,t]);const B=t==="create",z=f.useMemo(()=>d.models.filter(L=>L.id.trim().length>0),[d.models]),V=f.useMemo(()=>{var L;return((L=lt.find(Y=>Y.value===d.type))==null?void 0:L.label)??"Custom"},[d.type]),ae=d.label.trim()||d.id.trim()||l("providers.drawer.summary.untitled"),A=f.useMemo(()=>[{label:l("providers.drawer.summary.type"),value:V},{label:l("providers.drawer.summary.auth"),value:Yt(d.type,d.authMode,l)},{label:l("providers.drawer.summary.models"),value:z.length.toLocaleString()}],[z.length,d.authMode,d.type,V,l]),ie=async()=>{R(null);const L=u.validateErrors();if(Object.keys(L).length>0){L.baseUrl||L.id||L.extraHeaders?(K("basics"),L.extraHeaders&&u.setAdvancedOpen(!0)):L.models&&K("models");return}N(!0);try{const Y=u.serialize();await p(Y)}catch(Y){R(l("providers.drawer.toast.saveFailure",{message:xe(Y).message})),N(!1);return}N(!1),n()};if(!a)return null;const X=Oe.findIndex(L=>L.id===Z),M=X===Oe.length-1,I=d.id.trim(),H=I.length>0&&(t==="edit"||!s.includes(I)),Ce=d.baseUrl.trim();let re=Ce.length>0;if(re)try{new URL(Ce)}catch{re=!1}let Se=!d.defaultModel||d.models.some(L=>L.id===d.defaultModel);if(Se){const L=new Set;Se=!d.models.some(Y=>{const ce=Y.id.trim();return ce.length===0||L.has(ce)?!0:(L.add(ce),!1)})}const me={basics:H&&re,models:Se},pe=Oe.map((L,Y)=>{let ce;return Y===X?ce="current":Y<X?ce=me[L.id]?"complete":"error":ce="upcoming",{id:L.id,label:l(L.labelKey),status:ce}}),he=L=>{K(L)},be=()=>{X<Oe.length-1&&K(Oe[X+1].id)},we=()=>{X>0&&K(Oe[X-1].id)},ke={form:d,errors:w,isCreate:B,advancedOpen:b,onAdvancedOpenChange:u.setAdvancedOpen,idInputRef:c,onProviderIdChange:u.handleProviderIdChange,onFieldChange:u.handleFieldChange,onTypeChange:u.handleTypeChange,onAuthModeChange:u.handleAuthModeChange,onNonStreamViaStreamChange:u.handleProviderNonStreamViaStreamChange,onUseAbsoluteUrlChange:u.handleUseAbsoluteUrlChange,onAddHeader:u.handleAddHeader,onRemoveHeader:u.handleRemoveHeader,onHeaderChange:u.handleHeaderChange,onModelIdChange:u.handleModelIdChange,onModelChange:u.handleModelChange,onAddModel:u.handleAddModel,onRemoveModel:u.handleRemoveModel,onModelNonStreamViaStreamChange:u.handleModelNonStreamViaStreamChange,onSetDefaultModel:u.handleSetDefaultModel,testVerification:g?{available:t==="edit",testing:k??!1,result:h??null,onTest:g}:void 0};return e.jsxs("div",{className:"fixed inset-0 z-50 flex",children:[e.jsx("div",{className:"flex-1 bg-background/95","aria-hidden":"true"}),e.jsxs("aside",{ref:T,role:"dialog","aria-modal":"true","aria-labelledby":"provider-drawer-title","aria-describedby":"provider-drawer-desc",className:"flex h-full min-h-0 w-full max-w-5xl flex-col border-l border-border bg-background shadow-[var(--surface-shadow-lg)]",children:[e.jsxs("header",{className:"border-b border-border bg-secondary px-6 py-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"inline-flex rounded-full border border-primary/20 bg-primary/10 px-3 py-1 text-[11px] font-medium uppercase tracking-[0.18em] text-primary",children:l(B?"providers.drawer.quickStart":"providers.drawer.editTitle")}),e.jsxs("div",{children:[e.jsx("h2",{id:"provider-drawer-title",className:"text-lg font-semibold tracking-[-0.02em]",children:l(B?"providers.drawer.createTitle":"providers.drawer.editTitle")}),e.jsx("p",{id:"provider-drawer-desc",className:"text-sm text-muted-foreground",children:l("providers.drawer.description")})]})]}),e.jsx(q,{type:"button",ref:j,variant:"outline",onClick:n,className:"bg-card",children:l("common.actions.close")})]}),e.jsx("div",{className:"mt-4 grid gap-3 md:grid-cols-3",children:A.map(L=>e.jsxs("div",{className:"rounded-xl border border-transparent bg-card px-4 py-3 shadow-[var(--surface-shadow)]",children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground",children:L.label}),e.jsx("p",{className:"mt-2 text-sm font-semibold text-foreground",children:L.value})]},L.label))})]}),e.jsxs("div",{className:"grid min-h-0 flex-1 overflow-hidden xl:grid-cols-[minmax(0,1fr)_280px]",children:[e.jsxs("div",{className:"min-h-0 overflow-y-auto px-6 py-5 pb-10",children:[e.jsx(Zt,{steps:pe,current:Z,onSelect:he,className:"mb-6"}),Z==="basics"?e.jsx(es,{...ke}):null,Z==="models"?e.jsx(ts,{...ke}):null]}),e.jsx("aside",{className:"hidden min-h-0 overflow-y-auto border-l border-border/45 bg-secondary/40 px-5 py-5 xl:block",children:e.jsxs("div",{className:"sticky top-0 space-y-5",children:[e.jsxs("div",{className:"rounded-xl border border-transparent bg-card p-4 shadow-[var(--surface-shadow)]",children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground",children:l("providers.drawer.formSummary")}),e.jsx("p",{className:"mt-2 text-base font-semibold",children:ae}),e.jsx("div",{className:"mt-4 space-y-3 text-sm",children:A.map(L=>e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("span",{className:"text-muted-foreground",children:L.label}),e.jsx("span",{className:"text-right font-medium",children:L.value})]},L.label))})]}),e.jsxs("div",{className:"rounded-xl border border-transparent bg-card p-4 shadow-[var(--surface-shadow)]",children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground",children:l("providers.drawer.sections.checklist")}),e.jsxs("ul",{className:"mt-3 space-y-2 text-sm text-muted-foreground",children:[e.jsx("li",{children:l("providers.drawer.hints.checkUrl")}),e.jsx("li",{children:l("providers.drawer.hints.checkAuth")}),e.jsx("li",{children:l("providers.drawer.hints.checkModels")})]})]}),b&&e.jsxs("div",{className:"rounded-xl bg-accent p-4 text-sm text-foreground",children:[e.jsx("p",{className:"font-medium text-primary",children:l("providers.drawer.hints.advancedTitle")}),e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:l("providers.drawer.hints.advancedBody")})]})]})})]}),e.jsxs("footer",{className:"flex items-center justify-between gap-3 border-t border-border bg-secondary px-6 py-4 text-sm",children:[e.jsxs("div",{className:"flex flex-col gap-1 text-xs",children:[!B&&y?e.jsx("button",{type:"button",onClick:y,disabled:v,className:"text-muted-foreground underline-offset-2 hover:text-destructive hover:underline disabled:opacity-50",children:l("providers.actions.delete")}):null,C?e.jsx("span",{className:"text-destructive","aria-live":"polite",children:C}):null]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(q,{type:"button",variant:"outline",onClick:n,disabled:v,className:"bg-card",children:l("common.actions.cancel")}),e.jsx(q,{type:"button",variant:"outline",onClick:we,disabled:v||X===0,className:"bg-card",children:l("common.actions.previous")}),M?null:e.jsx(q,{type:"button",onClick:be,disabled:v,children:l("common.actions.next")}),e.jsx(q,{type:"button",onClick:ie,disabled:v,children:l(v?"common.actions.saving":"common.actions.save")})]})]})]})]})}function vs({provider:a,defaultModel:t,modelCount:i,requests24h:s,avgLatencyMs:n,routeCount:p,testResult:h,onTest:k,onEdit:g}){var b;const{t:y}=W(),l=a.label||a.id,u=l.slice(0,1).toUpperCase()||"?",d=((b=lt.find(c=>c.value===(a.type??"custom")))==null?void 0:b.label)??a.type??"custom",w=h?h.ok?"ok":"fail":"untested";return e.jsxs("div",{"data-testid":"provider-card",className:"flex flex-col rounded-lg border border-border bg-card p-4 transition-colors hover:border-primary/40",children:[e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-secondary text-sm font-semibold text-muted-foreground",children:u}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"truncate text-[13px] font-semibold text-foreground",title:l,children:l}),e.jsx(oe,{variant:"outline",className:"shrink-0 rounded-full px-2 py-0 text-[10px] font-normal text-muted-foreground",children:d})]}),e.jsx("code",{className:"mt-0.5 block truncate font-mono text-[10.5px] text-muted-foreground",title:a.baseUrl,children:a.baseUrl})]}),e.jsx(js,{state:w})]}),e.jsxs("div",{className:"mt-3 grid grid-cols-3 gap-2",children:[e.jsx(ot,{label:y("providers.card.statModels"),value:i>0?String(i):"—"}),e.jsx(ot,{label:y("providers.card.statRequests24h"),value:s!=null?s.toLocaleString():"—"}),e.jsx(ot,{label:y("providers.card.statAvgLatency"),value:is(n,y("common.units.ms"),{maximumFractionDigits:0})})]}),e.jsxs("div",{className:"mt-2.5 flex items-center gap-1.5 text-[11px] text-muted-foreground",children:[e.jsx("span",{className:"shrink-0",children:y("providers.card.defaultModelLabel")}),t?e.jsx("code",{className:"min-w-0 truncate rounded bg-secondary px-1.5 py-0.5 font-mono text-[10.5px] text-foreground",title:t,children:t}):e.jsx("span",{children:"—"})]}),e.jsxs("div",{className:"mt-3 flex items-center gap-1.5 border-t border-border pt-2.5 text-[10.5px] text-muted-foreground",children:[e.jsx("span",{className:"truncate",children:y("providers.card.routeCount",{count:p})}),e.jsxs("div",{className:"ml-auto flex shrink-0 gap-1.5",children:[e.jsx(q,{variant:"outline",size:"sm",className:"h-7 px-2.5 text-[11px]",onClick:k,children:y("providers.actions.test")}),e.jsx(q,{variant:"outline",size:"sm",className:"h-7 px-2.5 text-[11px]",onClick:g,children:y("providers.actions.edit")})]})]})]})}function ot({label:a,value:t}){return e.jsxs("div",{className:"rounded bg-secondary/60 px-2.5 py-2",children:[e.jsx("div",{className:"text-[10px] text-muted-foreground",children:a}),e.jsx("div",{className:"metric-number mt-0.5 truncate text-[13px] font-semibold text-foreground",children:t})]})}function js({state:a}){const{t}=W();return a==="ok"?e.jsx(oe,{variant:"success",className:"shrink-0 rounded-full px-1.5 py-0 text-[10px]",children:t("providers.card.health.ok")}):a==="fail"?e.jsx(oe,{variant:"destructive",className:"shrink-0 rounded-full px-1.5 py-0 text-[10px]",children:t("providers.card.health.fail")}):e.jsx(oe,{variant:"secondary",className:"shrink-0 rounded-full px-1.5 py-0 text-[10px]",children:t("providers.card.health.untested")})}function ys({providersLength:a,filteredProviders:t,testResults:i,providerSearch:s,providerTypeFilter:n,configPending:p,defaultLabels:h,config:k,customEndpoints:g,onTest:y,onEdit:l,onProviderSearchChange:u,onProviderTypeChange:d,onResetFilters:w}){const{t:b}=W(),[c,v]=f.useState("usage"),N=bt(Ee.stats.model(1,50),{url:"/api/stats/model",method:"GET",params:{days:1,limit:50}},{retry:!1}),{requestsByProvider:C,latencyByProvider:R}=f.useMemo(()=>{const T=new Map,j=new Map,D=new Map;for(const z of N.data??[]){const V=z.provider;T.set(V,(T.get(V)??0)+z.requests),z.avgLatencyMs>0&&(j.set(V,(j.get(V)??0)+z.avgLatencyMs*z.requests),D.set(V,(D.get(V)??0)+z.requests))}const B=new Map;for(const z of T.keys()){const V=D.get(z)??0;B.set(z,V>0?(j.get(z)??0)/V:null)}return{requestsByProvider:T,latencyByProvider:B}},[N.data]),Z=f.useMemo(()=>{const T=new Map;for(const j of t)T.set(j.id,ss(k,g,j.id).length);return T},[k,g,t]),K=f.useMemo(()=>{const T=[...t],j=(D,B)=>(D.label||D.id).localeCompare(B.label||B.id);return c==="usage"&&N.isSuccess?T.sort((D,B)=>(C.get(B.id)??0)-(C.get(D.id)??0)||j(D,B)):T.sort(j),T},[t,c,N.isSuccess,C]);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(He,{className:"overflow-hidden",children:e.jsx(qe,{className:"p-0",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2 bg-secondary/50 px-4 py-3",children:[e.jsx(fe,{value:s,onChange:T=>u(T.target.value),placeholder:b("providers.filters.searchPlaceholder"),className:"h-9 w-full sm:w-64"}),e.jsxs(Qe,{value:n,onValueChange:d,children:[e.jsx(Ge,{className:"h-9 w-[130px] text-xs",children:e.jsx(We,{})}),e.jsxs(Je,{children:[e.jsx(Fe,{value:"all",children:b("providers.filters.typeAll")}),lt.map(T=>e.jsx(Fe,{value:T.value??"custom",children:T.label},T.value??"custom"))]})]}),e.jsxs(Qe,{value:c,onValueChange:T=>v(T),children:[e.jsx(Ge,{className:"h-9 w-[104px] text-xs","aria-label":b("providers.list.sortLabel"),children:e.jsx(We,{})}),e.jsxs(Je,{children:[e.jsx(Fe,{value:"usage",children:b("providers.list.sortUsage")}),e.jsx(Fe,{value:"name",children:b("providers.list.sortName")})]})]}),e.jsx(oe,{variant:"secondary",className:"shrink-0 rounded-full px-2.5 py-1 text-[11px]",children:t.length}),e.jsx(q,{variant:"ghost",size:"sm",onClick:w,disabled:!s.trim()&&n==="all",className:"h-9 shrink-0 rounded-full px-2.5 text-xs",children:b("common.actions.reset")})]})})}),p?e.jsx("div",{className:"flex min-h-[160px] items-center justify-center text-sm text-muted-foreground",children:b("common.loading")}):a===0?e.jsx(it,{compact:!0,title:b("providers.emptyState"),description:e.jsxs(e.Fragment,{children:[e.jsx("p",{children:b("providers.emptyStateSub")}),e.jsx("p",{className:"mt-1",children:b("workbench.list.emptyHint")})]})}):t.length===0?e.jsx(it,{compact:!0,title:b("providers.emptyFiltered")}):e.jsx("div",{className:"grid gap-3.5 sm:grid-cols-2 xl:grid-cols-3",children:K.map(T=>{var j;return e.jsx(vs,{provider:T,defaultModel:h.get(T.id),modelCount:((j=T.models)==null?void 0:j.length)??0,requests24h:N.isSuccess?C.get(T.id)??0:null,avgLatencyMs:N.isSuccess?R.get(T.id)??null:null,routeCount:Z.get(T.id)??0,testResult:i[T.id]??null,onTest:()=>y(T),onEdit:()=>l(T)},T.id)})})]})}function Ns({routing:a,endpoint:t,tabInfo:i,config:s,customEndpoints:n}){var v,N;const{t:p}=W(),h=a.routesByEndpoint[t]||[],k=a.savingRouteFor===t,g=a.savingCompatibilityPolicy,y=a.writingEndpoint===t,l=((v=i==null?void 0:i.protocols)==null?void 0:v.some(C=>C.startsWith("openai")))??t==="openai",u=as(t,s,n),d=l?(u==null?void 0:u.enabled)??!1:!1,b=((N=i==null?void 0:i.protocols)==null?void 0:N.includes("anthropic"))??t==="anthropic"?vt:jt,c=new Set(h.map(C=>C.source.trim()).filter(Boolean));return e.jsx(He,{"data-testid":"endpoint-config-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(qe,{className:"space-y-3 p-4",children:[e.jsx("h3",{className:"text-[12.5px] font-semibold",children:p("workbench.endpointConfig.title")}),l?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(ye,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:p("modelManagement.openaiCompatibility.toggleLabel")}),e.jsx("p",{className:"text-[10.5px] text-muted-foreground",children:p(d?"modelManagement.openaiCompatibility.enabledHint":"modelManagement.openaiCompatibility.disabledHint")})]}),e.jsx(rt,{"data-testid":"compatibility-toggle",checked:d,onCheckedChange:C=>void a.handleCompatibilityEnabledChange(t,C),disabled:g||y,"aria-label":p("modelManagement.openaiCompatibility.toggleLabel")})]}):null,e.jsxs("div",{children:[e.jsx("p",{className:"mb-1.5 text-[11px] text-muted-foreground",children:p("settings.routing.suggested")}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:b.map(C=>{const R=c.has(C);return e.jsx("button",{"data-testid":"suggestion-chip",type:"button",onClick:()=>a.handleAddSuggestion(t,C),disabled:k||R,className:Ne("h-6 border px-2 text-[10.5px] transition-colors",R?"border-border bg-secondary/40 text-muted-foreground/50":"border-border bg-card hover:border-primary hover:text-primary"),children:C},`${t}-${C}`)})})]})]})})}const gt=6;function _e({value:a,onChange:t,options:i,disabled:s,placeholder:n,ariaLabel:p}){const{t:h}=W(),k=f.useId(),[g,y]=f.useState(!1),[l,u]=f.useState(""),d=f.useRef(null),w=f.useRef(!1),[b,c]=zt(Ut.modelManagement.recentRouteTargets,[]),v=f.useMemo(()=>{const j=new Map;for(const D of i)j.set(D.value,D);return j},[i]),N=(j,D)=>D?[j.label,j.value,j.providerId??"",j.providerLabel??"",j.modelId??"",j.modelLabel??""].join(" ").toLowerCase().includes(D):!0,C=f.useMemo(()=>{const j=l.trim().toLowerCase(),D=i.filter(A=>N(A,j)),B=b.map(A=>v.get(A)??(j?void 0:{value:A,label:A,kind:"custom"})).filter(A=>!!A).filter(A=>N(A,j)).slice(0,gt),z=[];B.length>0&&z.push({key:"recent",label:h("modelManagement.targetPicker.recent"),options:B});const V=new Map,ae=[];for(const A of D){if(A.kind==="custom"||!A.providerId){ae.push(A);continue}const ie=`provider:${A.providerId}`,X=V.get(ie);X?X.options.push(A):V.set(ie,{key:ie,label:A.providerLabel??A.providerId,options:[A]})}return z.push(...V.values()),ae.length>0&&z.push({key:"custom",label:h("modelManagement.targetPicker.custom"),options:ae,muted:!0}),z},[v,i,b,l,h]),R=C.reduce((j,D)=>j+D.options.length,0),Z=j=>{t(j),c(D=>[j,...D.filter(B=>B!==j)].slice(0,gt)),u(""),w.current=!0,typeof document<"u"&&document.activeElement instanceof HTMLElement&&document.activeElement.blur(),y(!1),typeof window<"u"?window.requestAnimationFrame(()=>{w.current=!1}):w.current=!1},K=j=>j.kind==="passthrough"?h("modelManagement.targetPicker.passthrough"):j.kind==="custom"?h("modelManagement.targetPicker.customValue"):h("modelManagement.targetPicker.model"),T=j=>j.kind==="passthrough"||j.kind==="custom"?j.label:j.modelLabel??j.label;return e.jsxs(ds,{open:g,onOpenChange:j=>{j&&w.current||(y(j),j&&u(""))},children:[e.jsx(cs,{asChild:!0,children:e.jsx(fe,{value:a,onChange:j=>{t(j.target.value),u(j.target.value),g||y(!0)},onFocus:()=>{u(""),y(!0)},onClick:()=>{g||y(!0)},placeholder:n,disabled:s,autoComplete:"off",role:"combobox","aria-label":p,"aria-expanded":g,"aria-controls":k,"aria-autocomplete":"list"})}),e.jsxs(us,{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:j=>{var D;j.preventDefault(),(D=d.current)==null||D.focus()},onCloseAutoFocus:j=>{j.preventDefault()},children:[e.jsxs("div",{className:"space-y-2 border-b border-border px-3 py-3",children:[e.jsx(fe,{ref:d,value:l,onChange:j=>u(j.target.value),placeholder:h("modelManagement.targetPicker.searchPlaceholder"),className:"h-9",autoComplete:"off"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:l.trim()?h("modelManagement.targetPicker.matchCount",{count:R}):h("modelManagement.targetPicker.helper")})]}),R===0?e.jsx("div",{className:"px-3 py-4 text-center text-xs text-muted-foreground",children:h("common.noMatches")}):e.jsx("div",{id:k,role:"listbox",className:"min-h-0 flex-1 overflow-y-auto p-1.5",children:C.map(j=>e.jsxs("div",{className:"py-1",children:[e.jsxs("div",{className:Ne("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",j.muted&&"opacity-80"),children:[e.jsx("span",{className:"truncate",children:j.label}),e.jsx("span",{children:j.options.length})]}),e.jsx("div",{className:"space-y-1",children:j.options.map(D=>e.jsxs("button",{type:"button",role:"option","aria-selected":D.value===a.trim(),className:Ne("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",D.value===a.trim()&&"bg-accent text-accent-foreground"),onMouseDown:B=>{B.preventDefault()},onClick:()=>Z(D.value),children:[e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate font-medium",children:T(D)}),e.jsx("span",{className:"block truncate text-xs text-muted-foreground",children:D.value})]}),e.jsxs("span",{className:"flex shrink-0 items-center gap-1",children:[D.isDefault?e.jsx(oe,{variant:"secondary",className:"text-[10px]",children:h("modelManagement.targetPicker.default")}):null,e.jsx(oe,{variant:D.kind==="passthrough"?"outline":"secondary",className:"text-[10px]",children:K(D)})]})]},`${j.key}-${D.value}`))})]},j.key))})]})]})}function ws({routing:a,endpoint:t}){const{t:i}=W(),s=a.defaultsByEndpoint[t]??null,n=a.isDefaultsDirtyByEndpoint[t]??!1,p=a.savingDefaultsFor===t,h=a.writingEndpoint===t,k=a.providerModelOptions;return e.jsx(He,{"data-testid":"routing-defaults-card",className:"border-primary/40 bg-primary/5 shadow-none",children:e.jsxs(qe,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-[13px] font-semibold text-primary",children:i("workbench.defaults.title")}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:i("workbench.defaults.cardSubtitle")})]}),e.jsxs(ls,{summary:e.jsx("span",{className:"text-[11px] font-medium text-muted-foreground",children:i("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(ye,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:i("workbench.defaults.reasoningLabel")}),e.jsx(_e,{value:(s==null?void 0:s.reasoning)??"",onChange:g=>a.handleDefaultsChange(t,"reasoning",g),options:k,disabled:p,ariaLabel:i("workbench.defaults.reasoningLabel"),placeholder:i("workbench.defaults.targetPlaceholder")})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ye,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:i("workbench.defaults.backgroundLabel")}),e.jsx(_e,{value:(s==null?void 0:s.background)??"",onChange:g=>a.handleDefaultsChange(t,"background",g),options:k,disabled:p,ariaLabel:i("workbench.defaults.backgroundLabel"),placeholder:i("workbench.defaults.targetPlaceholder")})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ye,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:i("workbench.defaults.thresholdLabel")}),e.jsx(fe,{type:"number",min:1,value:(s==null?void 0:s.longContextThreshold)||"",onChange:g=>{const y=Number.parseInt(g.target.value,10);a.handleDefaultsChange(t,"longContextThreshold",Number.isFinite(y)?y:0)},disabled:p,className:"md:w-56"})]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"border border-border bg-card px-2.5 py-2 font-mono text-xs",children:"*"}),e.jsx(ge,{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(_e,{value:(s==null?void 0:s.completion)??"",onChange:g=>a.handleDefaultsChange(t,"completion",g),options:k,disabled:p,ariaLabel:i("workbench.defaults.completionLabel"),placeholder:i("workbench.defaults.targetPlaceholder")})}),e.jsxs(q,{size:"sm","data-testid":"save-defaults",onClick:()=>void a.handleSaveDefaults(t),disabled:p||!n||h,className:"relative",children:[i(p?"common.actions.saving":"workbench.defaults.save"),n?e.jsx("span",{className:"absolute -right-1 -top-1 h-2 w-2 rounded-full bg-warning"}):null]})]})]})})}const ks={anthropic:"/anthropic",openai:"/openai"};function Cs(a){var t;return(t=a.paths)!=null&&t.length?a.paths[0].path:a.path?a.path:`/${a.id}`}function Ss({tabs:a,customEndpoints:t,routeCounts:i,selectedEndpointId:s,onSelect:n,onCreate:p,onEditEndpoint:h,onDeleteEndpoint:k}){const{t:g}=W(),y=a.map(l=>{const u=t.find(w=>w.id===l.key);if(!u)return{key:l.key,label:l.label,path:ks[l.key]??`/${l.key}`,protocols:l.protocols??[],enabled:!0};const d=u.paths??(u.path?[{path:u.path,protocol:u.protocol??"anthropic"}]:[]);return{key:l.key,label:u.label||u.id,path:Cs(u),protocols:[...new Set(d.map(w=>w.protocol))],enabled:u.enabled!==!1,custom:u}});return e.jsxs("section",{"data-testid":"endpoint-rail",className:"flex gap-2 overflow-x-auto border border-border bg-card shadow-[var(--surface-shadow)] lg:h-full lg:flex-col lg:overflow-visible",children:[e.jsxs("div",{className:"hidden shrink-0 border-b border-border/60 px-3 py-2.5 lg:block",children:[e.jsx("h2",{className:"text-[12.5px] font-semibold",children:g("workbench.endpointRail.title")}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:g("workbench.endpointRail.subtitle")})]}),e.jsxs("div",{className:"flex gap-1.5 p-2 lg:flex-col lg:gap-1",children:[y.map(l=>{const u=l.key===s,d=i[l.key]??0,w=!l.enabled;return e.jsxs("div",{"data-testid":"endpoint-row",className:Ne("flex shrink-0 items-stretch border transition-colors lg:shrink",u?"border-primary/40 bg-primary/5":"border-border bg-card hover:bg-accent",w?"opacity-60":""),children:[e.jsxs("button",{type:"button",onClick:()=>n(l.key),className:"flex min-w-0 flex-1 items-center gap-2 px-2.5 py-2 text-left",children:[e.jsx("span",{className:Ne("h-1.5 w-1.5 shrink-0 rounded-full",u?"bg-primary":"bg-muted-foreground/40"),"aria-hidden":!0}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-[11.5px] font-medium",title:l.label,children:l.label}),e.jsxs("span",{className:"mt-0.5 flex items-center gap-1.5 text-[10px] text-muted-foreground",children:[e.jsx("span",{className:"truncate font-mono",children:l.path}),e.jsx("span",{"aria-hidden":!0,children:"·"}),e.jsx("span",{className:"shrink-0 tabular-nums",children:g("workbench.endpointRail.ruleCount",{count:d})})]})]})]}),l.custom?e.jsxs("div",{className:"flex items-center gap-0.5 pr-1",children:[e.jsx("button",{type:"button",onClick:()=>h(l.custom),className:"flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-foreground",title:g("common.edit"),"aria-label":g("common.edit"),children:e.jsx(kt,{className:"h-3 w-3","aria-hidden":!0})}),l.custom.deletable!==!1?e.jsx("button",{type:"button",onClick:()=>k(l.custom),className:"flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-destructive",title:g("common.delete"),"aria-label":g("common.delete"),children:e.jsx(Ct,{className:"h-3 w-3","aria-hidden":!0})}):null]}):null]},l.key)}),e.jsxs("button",{type:"button","data-testid":"create-endpoint",onClick:p,className:"flex shrink-0 items-center justify-center border border-dashed border-border px-3 py-2 text-[11.5px] text-muted-foreground transition-colors hover:border-primary hover:text-primary lg:shrink",children:["+ ",g("workbench.endpointRail.add")]})]})]})}function Ms({endpointPath:a,defaultTarget:t}){const{t:i}=W();return e.jsxs("section",{"data-testid":"routing-flow-banner",className:"flex flex-wrap items-center gap-x-3 gap-y-2 border border-border bg-card px-4 py-3 shadow-[var(--surface-shadow)]",children:[e.jsx("span",{className:"text-[10.5px] font-semibold uppercase tracking-[0.06em] text-muted-foreground",children:i("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:i("workbench.flow.clientStep")}),e.jsx(ge,{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:[i("workbench.flow.endpointStep")," ",e.jsx("span",{className:"font-mono",children:a})]}),e.jsx(ge,{className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0}),e.jsx("span",{className:"border border-primary bg-primary/5 px-2.5 py-1 text-[11px] font-semibold text-primary",children:i("workbench.flow.matchStep")}),e.jsx(ge,{className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0}),e.jsx("span",{className:"border border-border bg-secondary px-2.5 py-1 font-mono text-[11px]",children:t||i("workbench.flow.fallbackNote")})]})]})}function Ps({routing:a,endpoint:t,onRequestDeletePreset:i}){var u,d;const{t:s}=W(),n=a.presetsByEndpoint[t]??[],p=a.presetNameByEndpoint[t]??"",h=a.presetErrorByEndpoint[t],k=a.savingPresetFor===t,g=((u=a.applyingPreset)==null?void 0:u.endpoint)===t?a.applyingPreset.name:null,y=((d=a.deletingPreset)==null?void 0:d.endpoint)===t?a.deletingPreset.name:null,l=a.writingEndpoint===t;return e.jsx(He,{"data-testid":"routing-presets-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(qe,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h3",{className:"text-[13px] font-semibold",children:s("modelManagement.presets.title")}),e.jsx(q,{variant:"outline",size:"sm","data-testid":"save-preset",onClick:()=>void a.handleSavePreset(t),disabled:k||l,children:s(k?"modelManagement.presets.saving":"modelManagement.presets.save")})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:s("modelManagement.presets.description")}),e.jsx(fe,{"data-testid":"preset-name-input",value:p,onChange:w=>a.handlePresetNameChange(t,w.target.value),placeholder:s("modelManagement.presets.namePlaceholder"),disabled:k,className:"h-8 text-xs"}),h?e.jsx("p",{className:"text-xs text-destructive",children:h}):null,n.length===0?e.jsx("p",{className:"py-2 text-center text-[11px] text-muted-foreground",children:s("modelManagement.presets.empty")}):e.jsx(Vt,{children:e.jsx("div",{className:"grid grid-cols-1 gap-1.5 sm:grid-cols-2",children:n.map(w=>{const b=g===w.name,c=y===w.name,v=Object.entries(w.modelRoutes??{}),N=v.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(_t,{children:[e.jsx(Kt,{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:w.name}),e.jsx(oe,{variant:"outline",className:"mt-0.5 text-[10px] font-normal",children:N>0?s("modelManagement.presets.rulesCount",{count:N}):s("modelManagement.presets.noRules")})]})}),N>0?e.jsx(Qt,{side:"bottom",className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1 text-xs",children:[v.slice(0,5).map(([C,R])=>e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"truncate",children:C}),e.jsx(ge,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:R})]},C)),N>5?e.jsxs("div",{className:"text-muted-foreground",children:["…+",N-5]}):null]})}):null]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"apply-preset",className:"text-[11px] font-semibold text-primary hover:underline disabled:opacity-50",onClick:()=>a.setPresetDiffDialog({endpoint:t,preset:w}),disabled:b||c||l,children:s(b?"modelManagement.presets.applying":"modelManagement.presets.apply")}),e.jsx("button",{type:"button","data-testid":"delete-preset",className:"text-[11px] text-muted-foreground hover:text-destructive disabled:opacity-50","aria-label":s("common.delete"),onClick:()=>i(t,w),disabled:c||b||l,children:s(c?"modelManagement.presets.deleting":"modelManagement.presets.delete")})]})]},w.name)})})})]})})}function Es({entry:a,index:t,savingRoute:i,options:s,sourceListId:n,onRouteChange:p,onRemoveRoute:h}){const{t:k}=W(),{attributes:g,listeners:y,setNodeRef:l,setActivatorNodeRef:u,transform:d,transition:w,isDragging:b}=St({id:a.id});return e.jsxs("div",{ref:l,"data-testid":"route-rule-row","data-id":a.id,style:{transform:Pt.Transform.toString(d),transition:w},className:Ne("flex items-center gap-2 border border-border bg-card p-2",b&&"z-10 opacity-60 shadow-[var(--surface-shadow-lg)]"),children:[e.jsx("button",{ref:u,type:"button","data-testid":"route-rule-grip","aria-label":k("workbench.routing.dragHandle"),className:"flex h-7 w-4 shrink-0 cursor-grab touch-none items-center justify-center text-muted-foreground hover:text-foreground active:cursor-grabbing",...g,...y,children:e.jsx(Mt,{className:"h-4 w-4","aria-hidden":!0})}),e.jsx("span",{className:"w-4 shrink-0 text-center text-[10.5px] tabular-nums text-muted-foreground",children:t+1}),e.jsx(fe,{"data-testid":"route-rule-source",value:a.source,onChange:c=>p(a.id,"source",c.target.value),placeholder:k("settings.routing.sourcePlaceholder"),list:n,disabled:i,className:"h-8 min-w-0 flex-1 text-xs"}),e.jsx(ge,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground","aria-hidden":!0}),e.jsx("div",{"data-testid":"route-rule-target",className:"min-w-0 flex-[1.15]",children:e.jsx(_e,{value:a.target,onChange:c=>p(a.id,"target",c),options:s,disabled:i,ariaLabel:k("workbench.routing.targetLabel"),placeholder:k("settings.routing.targetPlaceholder")})}),e.jsx(q,{variant:"ghost",size:"icon","data-testid":"route-rule-delete",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>h(a.id),disabled:i,"aria-label":k("common.delete"),children:e.jsx(ft,{className:"h-3.5 w-3.5","aria-hidden":!0})})]})}function Ds({routing:a,endpoint:t,tabInfo:i}){var c;const{t:s}=W(),n=a.routesByEndpoint[t]||[],p=a.routeError[t],h=a.savingRouteFor===t,k=a.isDirtyByEndpoint[t]??!1,g=a.writingEndpoint===t,y=a.providerModelOptions,l=`route-source-${t}`,u=Et(ct(It,{activationConstraint:{distance:6}}),ct(Ft,{coordinateGetter:Lt})),d=v=>{const{active:N,over:C}=v;!C||N.id===C.id||a.handleReorderRules(t,String(N.id),String(C.id))},b=((c=i==null?void 0:i.protocols)==null?void 0:c.includes("anthropic"))??t==="anthropic"?vt:jt;return e.jsx(He,{"data-testid":"routing-rules-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(qe,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h3",{className:"flex items-center gap-2 text-[13px] font-semibold",children:[s("workbench.routing.rulesTitle"),e.jsx(oe,{variant:"outline",className:"text-[10.5px] font-normal tabular-nums",children:n.length})]}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:s("workbench.routing.rulesSubtitle")})]}),e.jsx(q,{variant:"outline",size:"sm","data-testid":"add-route",onClick:()=>a.handleAddRoute(t),disabled:h,children:s("settings.routing.add")})]}),p?e.jsx("p",{className:"text-xs text-destructive",children:p}):null,n.length===0?e.jsx(it,{compact:!0,title:s("workbench.routing.emptyTitle"),description:s("workbench.routing.emptyDescription"),action:e.jsx(q,{size:"sm",onClick:()=>a.handleAddRoute(t),disabled:h,children:s("workbench.routing.addFirst")})}):e.jsx(Dt,{sensors:u,collisionDetection:Rt,onDragEnd:d,children:e.jsx(Tt,{items:n.map(v=>v.id),strategy:Ot,children:e.jsx("div",{className:"flex flex-col gap-1.5",children:n.map((v,N)=>e.jsx(Es,{entry:v,index:N,savingRoute:h,options:y,sourceListId:l,onRouteChange:(C,R,Z)=>a.handleRouteChange(t,C,R,Z),onRemoveRoute:C=>a.handleRemoveRoute(t,C)},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:s(k?"modelManagement.actions.footerDirtyHint":"modelManagement.actions.footerSavedHint")}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(q,{variant:"outline",size:"sm","data-testid":"reset-routes",onClick:()=>a.handleResetRoutes(t),disabled:h||!k,children:s("common.actions.reset")}),e.jsxs(q,{size:"sm","data-testid":"save-routes",onClick:()=>void a.handleSaveRoutes(t),disabled:h||g,className:"relative",children:[s(h?"common.actions.saving":"modelManagement.actions.saveRoutes"),k?e.jsx("span",{className:"absolute -right-1 -top-1 h-2 w-2 rounded-full bg-warning"}):null]})]})]}),e.jsx("datalist",{id:l,children:b.map(v=>e.jsx("option",{value:v},`${l}-${v}`))})]})})}const Rs={simulateRequest(a){return{url:"/api/routing/simulate",method:"POST",data:a}}},Ts=350;function Os(a,t){switch(a.kind){case"modelRoute":return{label:a.viaAlias?t("workbench.hitSim.reasonModelRouteAlias"):t("workbench.hitSim.reasonModelRoute"),tone:"hit"};case"directMatch":return{label:t("workbench.hitSim.reasonDirectMatch"),tone:"hit"};case"thinkingDefault":return{label:t("workbench.hitSim.reasonThinkingDefault"),tone:"hit"};case"completionDefault":return{label:t("workbench.hitSim.reasonCompletionDefault"),tone:"hit"};case"longContextDefault":return{label:t("workbench.hitSim.reasonLongContext"),tone:"hit",detail:t("workbench.hitSim.longContextDetail",{estimate:a.tokenEstimate.toLocaleString(),threshold:a.threshold.toLocaleString()})};case"fallback":return{label:t("workbench.hitSim.reasonFallback"),tone:"fallback"}}return{label:t("workbench.hitSim.reasonFallback"),tone:"fallback"}}function Ls({tabs:a,endpoint:t,onEndpointChange:i}){var C;const{t:s}=W(),n=a.filter(R=>R.key!=="providers"),[p,h]=f.useState(((C=n[0])==null?void 0:C.key)??"anthropic"),k=t??p,g=R=>{t&&i?i(R):h(R)},[y,l]=f.useState(""),[u,d]=f.useState(!1),[w,b]=f.useState("");f.useEffect(()=>{const R=setTimeout(()=>b(y.trim()),Ts);return()=>clearTimeout(R)},[y]);const{data:c,isFetching:v,error:N}=bt(["routing","simulate",k,w,u],Rs.simulateRequest({endpoint:k,model:w||void 0,thinking:u}),{retry:!1,refetchOnWindowFocus:!1,staleTime:1/0});return e.jsxs("section",{"data-testid":"routing-hit-simulator",className:"space-y-3 rounded-lg border border-border bg-card p-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm font-semibold text-foreground",children:s("workbench.hitSim.title")}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:s("workbench.hitSim.subtitle")})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-2",children:[t?null:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:s("workbench.hitSim.endpointLabel")}),e.jsxs(Qe,{value:k,onValueChange:g,children:[e.jsx(Ge,{className:"h-8 w-[168px]",children:e.jsx(We,{})}),e.jsx(Je,{children:n.map(R=>e.jsx(Fe,{value:R.key,children:R.label},R.key))})]})]}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(rt,{checked:u,onCheckedChange:d,"aria-label":s("workbench.hitSim.thinking")}),s("workbench.hitSim.thinking")]})]}),e.jsx(fe,{value:y,onChange:R=>l(R.target.value),placeholder:s("workbench.hitSim.modelPlaceholder"),className:"h-9 text-xs",spellCheck:!1,autoComplete:"off","aria-label":s("workbench.hitSim.modelPlaceholder")}),e.jsx(Fs,{result:c,loading:v,errorMessage:(N==null?void 0:N.message)??null,requestedModel:w})]})}function Fs({result:a,loading:t,errorMessage:i,requestedModel:s}){const{t:n}=W();if(i)return e.jsxs("p",{className:"text-xs text-muted-foreground",children:[n("workbench.hitSim.errorPrefix"),": ",i]});if(!a)return t?e.jsx("div",{className:"h-[72px] animate-pulse rounded-lg border border-border bg-secondary"}):e.jsx("p",{className:"text-xs text-muted-foreground",children:n("workbench.hitSim.empty")});const p=Os(a.reason,n),h=p.tone==="fallback",k=s||n("workbench.hitSim.anyModel");return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:h?"rounded-lg border border-border bg-secondary px-3 py-2.5":"rounded-lg border border-success bg-success-bg px-3 py-2.5",children:[e.jsx("div",{className:h?"text-[11px] font-semibold text-warning":"text-[11px] font-semibold text-success",children:p.label}),e.jsx("div",{className:"mt-1 text-xs text-foreground",children:k}),e.jsxs("div",{className:"mt-1 text-xs text-muted-foreground",children:["→ ",a.providerLabel,":",a.modelId]}),p.detail?e.jsx("div",{className:"mt-1 text-[11px] text-muted-foreground",children:p.detail}):null]}),h?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:n("workbench.hitSim.fallbackHint")}):null]})}function Is({routing:a,config:t,customEndpoints:i,selectedEndpointId:s,routeCounts:n,onSelectEndpoint:p,onCreateEndpoint:h,onEditEndpoint:k,onDeleteEndpoint:g,onRequestDeletePreset:y}){var b;W();const l=s??((b=a.endpointTabs[0])==null?void 0:b.key)??"anthropic",u=a.endpointTabs.find(c=>c.key===l),d=a.defaultsByEndpoint[l],w=(()=>{var v;if(l==="anthropic")return"/anthropic";if(l==="openai")return"/openai";const c=i.find(N=>N.id===l);return(v=c==null?void 0:c.paths)!=null&&v.length?c.paths[0].path:c!=null&&c.path?c.path:`/${l}`})();return e.jsxs("div",{"data-testid":"routing-workspace",className:"flex flex-col gap-3.5",children:[e.jsx(Ms,{endpointPath:w,defaultTarget:(d==null?void 0:d.completion)??null}),e.jsxs("div",{className:"grid items-start gap-3.5 lg:grid-cols-[200px_minmax(0,1fr)_288px]",children:[e.jsx(Ss,{tabs:a.endpointTabs,customEndpoints:i,routeCounts:n,selectedEndpointId:l,onSelect:p,onCreate:h,onEditEndpoint:k,onDeleteEndpoint:g}),e.jsxs("div",{className:"flex flex-col gap-3.5",children:[e.jsx(ws,{routing:a,endpoint:l}),e.jsx(Ds,{routing:a,endpoint:l,tabInfo:u}),e.jsx(Ps,{routing:a,endpoint:l,onRequestDeletePreset:y})]}),e.jsxs("div",{className:"flex flex-col gap-3.5",children:[e.jsx(Ls,{tabs:a.endpointTabs,endpoint:l,onEndpointChange:p}),e.jsx(Ns,{routing:a,endpoint:l,tabInfo:u,config:t,customEndpoints:i})]})]})]})}function As({open:a,provider:t,options:i,usePreset:s,preservedExtras:n,onPresetChange:p,onConfirm:h,onClose:k}){const{t:g}=W();return t?e.jsx(Xe,{open:a,onOpenChange:y=>!y&&k(),children:e.jsxs(Ye,{className:"max-w-2xl",onInteractOutside:y=>y.preventDefault(),children:[e.jsxs(Ze,{children:[e.jsx(et,{children:g("providers.testDialog.title")}),e.jsx(tt,{children:g("providers.testDialog.subtitle",{name:t.label||t.id})})]}),e.jsxs(st,{className:"space-y-4",children:[e.jsx("div",{className:"rounded-xl bg-accent p-4 text-sm text-primary",children:g("providers.testDialog.description")}),e.jsxs("div",{className:"space-y-4 rounded-xl bg-secondary/50 p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ye,{htmlFor:"provider-test-preset",children:g("providers.testDialog.presetLabel")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:g("providers.testDialog.presetDescription")})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(rt,{id:"provider-test-preset",checked:s,onCheckedChange:p})})]}),s?e.jsx("div",{className:"space-y-2",children:e.jsxs("details",{className:"rounded-xl border border-transparent bg-card p-2 text-xs shadow-[var(--surface-shadow)]",children:[e.jsx("summary",{className:"cursor-pointer text-primary hover:underline",children:g("providers.testDialog.presetPreviewSummary")}),e.jsx("div",{className:"mt-2 space-y-1",children:i.map(y=>e.jsxs("code",{className:"block rounded-lg bg-secondary px-2 py-1 text-xs",children:[y.key,": ",y.value]},y.key))})]})}):e.jsx("p",{className:"text-xs text-muted-foreground",children:g("providers.testDialog.presetDescription")})]}),Object.keys(n).length>0&&e.jsxs("div",{className:"space-y-2 rounded-xl bg-secondary/50 p-4 text-xs",children:[e.jsx("p",{className:"font-medium",children:g("providers.testDialog.preservedInfo")}),Object.entries(n).map(([y,l])=>e.jsxs("code",{className:"block rounded-lg border border-transparent bg-card px-2 py-1 shadow-[var(--surface-shadow)]",children:[y,": ",l]},y))]})]}),e.jsxs(at,{children:[e.jsx(q,{variant:"outline",onClick:k,children:g("providers.testDialog.cancel")}),e.jsx(q,{onClick:()=>void h(),children:g("providers.testDialog.primary")})]})]})}):null}function oa(){const{t:a}=W(),t=rs(),i=ms(t),s=ps(t,{sanitizeDraftsForProvider:i.sanitizeDraftsForProvider}),[n,p]=$t(),h=n.get("tab"),k=h==="routing"||h==="endpoints"?"routing":"providers";f.useEffect(()=>{h==="endpoints"&&p(M=>{const I=new URLSearchParams(M);return I.set("tab","routing"),I},{replace:!0})},[h,p]);const[g,y]=f.useState(!1),[l,u]=f.useState(void 0),[d,w]=f.useState(null),[b,c]=f.useState(!1),v=n.get("endpoint"),[N,C]=f.useState(v);f.useEffect(()=>{C(v)},[v]);const R=M=>{p(I=>{const H=new URLSearchParams(I);return H.set("tab","routing"),H.set("endpoint",M),H},{replace:!0})},Z=()=>{p(M=>{const I=new URLSearchParams(M);return I.delete("endpoint"),I},{replace:!0})};f.useEffect(()=>{N&&(t.customEndpointsQuery.isPending||i.endpointTabs.some(M=>M.key===N)||Z())},[N,i.endpointTabs,t.customEndpointsQuery.isPending]);const K=()=>{u(void 0),y(!0)},T=M=>{u(M),y(!0)},j=M=>{p(I=>{const H=new URLSearchParams(I);return M==="providers"?H.delete("tab"):H.set("tab",M),H},{replace:!0})},D=async()=>{if(d){c(!0);try{d.kind==="provider"?await s.handleDeleteProvider(d.provider):d.kind==="preset"?await i.handleDeletePreset(d.endpoint,d.preset):await i.handleDeleteEndpoint(d.endpoint.id),w(null)}finally{c(!1)}}},B=(d==null?void 0:d.kind)==="provider"?ns(t.config,t.customEndpoints,d.provider.id):0,z=(d==null?void 0:d.kind)==="provider"?a("providers.actions.delete"):(d==null?void 0:d.kind)==="preset"?a("modelManagement.presets.delete"):(d==null?void 0:d.kind)==="endpoint"?a("common.delete"):"",V=(d==null?void 0:d.kind)==="provider"?a("providers.confirm.delete",{name:d.provider.label||d.provider.id}):(d==null?void 0:d.kind)==="preset"?a("modelManagement.confirm.deletePreset",{name:d.preset.name}):(d==null?void 0:d.kind)==="endpoint"?a("modelManagement.deleteEndpointConfirm",{label:d.endpoint.label}):"",ae=(d==null?void 0:d.kind)==="provider"?d.provider.label||d.provider.id:(d==null?void 0:d.kind)==="preset"?d.preset.name:(d==null?void 0:d.kind)==="endpoint"?d.endpoint.label:"",A=Object.values(i.routesByEndpoint).reduce((M,I)=>M+((I==null?void 0:I.length)??0),0),ie=Object.fromEntries(Object.entries(i.routesByEndpoint).map(([M,I])=>[M,(I==null?void 0:I.length)??0])),X=[{value:"providers",icon:At,label:a("workbench.viewSwitch.providers"),description:a("workbench.viewSwitch.providersDesc"),count:s.providerCount},{value:"routing",icon:Bt,label:a("workbench.viewSwitch.routing"),description:a("workbench.viewSwitch.routingDesc"),count:A}];return e.jsxs("div",{className:"flex flex-col gap-6",children:[e.jsx(qt,{actions:k==="providers"?e.jsx(q,{size:"sm",onClick:s.handleOpenCreate,children:a("providers.actions.add")}):e.jsx(q,{size:"sm",onClick:K,children:a("workbench.endpoints.create")})}),e.jsx("div",{role:"tablist","aria-label":a("workbench.viewSwitch.label"),className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:X.map(M=>{const I=M.icon,H=k===M.value;return e.jsxs("button",{type:"button",role:"tab","aria-selected":H,onClick:()=>j(M.value),className:Ne("motion-surface flex items-center gap-3 rounded-xl border p-4 text-left",H?"border-primary/40 bg-primary/5":"border-border bg-card hover:bg-muted/40"),children:[e.jsx("span",{className:Ne("flex h-9 w-9 shrink-0 items-center justify-center rounded-lg",H?"bg-primary/10 text-primary":"bg-secondary text-muted-foreground"),children:e.jsx(I,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:Ne("text-sm font-semibold",H?"text-foreground":"text-muted-foreground"),children:M.label}),e.jsx(oe,{variant:H?"default":"secondary",className:"text-[10px]",children:M.count})]}),e.jsx("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",children:M.description})]})]},M.value)})}),k==="providers"?e.jsx(ys,{configPending:t.configQuery.isPending||!t.config&&t.configQuery.isFetching,testResults:s.testResults,filteredProviders:s.filteredProviders,providerSearch:s.providerSearch,providerTypeFilter:s.providerTypeFilter,providersLength:s.providers.length,defaultLabels:s.defaultLabels,config:t.config,customEndpoints:t.customEndpoints,onTest:M=>s.initiateTestConnection(M),onEdit:M=>s.handleOpenEdit(M),onProviderSearchChange:s.setProviderSearch,onProviderTypeChange:s.setProviderTypeFilter,onResetFilters:()=>{s.setProviderSearch(""),s.setProviderTypeFilter("all")}}):e.jsx(Is,{routing:i,config:t.config,customEndpoints:t.customEndpoints,routeCounts:ie,selectedEndpointId:N,onSelectEndpoint:R,onCreateEndpoint:K,onEditEndpoint:T,onDeleteEndpoint:M=>w({kind:"endpoint",endpoint:M}),onRequestDeletePreset:(M,I)=>w({kind:"preset",endpoint:M,preset:I})}),e.jsx(bs,{open:s.drawerOpen,mode:s.drawerMode,provider:s.drawerMode==="edit"?s.editingProvider:void 0,existingProviderIds:s.providers.map(M=>M.id).filter(M=>s.drawerMode==="edit"&&s.editingProvider?M!==s.editingProvider.id:!0),testResult:s.editingProvider?s.testResults[s.editingProvider.id]??null:null,testing:s.editingProvider?s.testingProviderId===s.editingProvider.id:!1,onTest:()=>{s.editingProvider&&s.handleTestConnection(s.editingProvider)},onDelete:()=>{s.drawerMode==="edit"&&s.editingProvider&&w({kind:"provider",provider:s.editingProvider})},onClose:()=>{s.setDrawerOpen(!1),s.setEditingProvider(void 0),s.setDrawerMode("create")},onSubmit:s.handleProviderSubmit}),e.jsx(As,{open:s.testDialogOpen,provider:s.testDialogProvider,options:s.anthropicTestHeaderOptions,preservedExtras:s.testDialogPreservedExtras,usePreset:s.testDialogUsePreset,onPresetChange:s.setTestDialogUsePreset,onConfirm:s.confirmTestDialog,onClose:s.closeTestDialog}),e.jsx(gs,{open:!!s.noModelDialogProvider,provider:s.noModelDialogProvider,onClose:()=>s.setNoModelDialogProvider(null),onEdit:M=>{s.setNoModelDialogProvider(null),s.handleOpenEdit(M)}}),e.jsx(xs,{open:g,endpoint:l,onClose:()=>{y(!1),u(void 0)},onSuccess:()=>{t.configQuery.refetch()}}),e.jsx(fs,{dialog:i.presetDiffDialog,currentRoutes:i.presetDiffDialog?i.routesByEndpoint[i.presetDiffDialog.endpoint]||[]:[],onConfirm:(M,I)=>{i.setPresetDiffDialog(null),i.handleApplyPreset(M,I)},onClose:()=>i.setPresetDiffDialog(null)}),e.jsx(Ht,{open:!!d,onOpenChange:M=>{!M&&!b&&w(null)},title:z,description:V,confirmLabel:a(b?"common.actions.loading":"common.delete"),cancelLabel:a("common.actions.cancel"),loading:b,onConfirm:D,children:ae?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:ae}),(d==null?void 0:d.kind)==="provider"&&B>0?e.jsx("p",{className:"text-xs text-muted-foreground",children:a("providers.confirm.deleteImpact",{count:B})}):null]}):null})]})}export{oa as default};
|
|
1
|
+
import{r as f,ax as Nt,j as e,ay as wt,as as ft,ab as ge,az as kt,aA as Ct,aB as St,aC as Mt,aD as Pt,aE as Et,aF as ct,aG as Dt,aH as Rt,aI as Tt,aJ as Ot,aK as Lt,aL as Ft,aM as It,aN as At,aO as Bt}from"./vendor-CITafuNQ.js";import{d as $t}from"./router-BoBrmro7.js";import{C as Ht}from"./ConfirmDialog-Bcxn6dph.js";import{P as qt}from"./PageToolbar-BdMtFJ0X.js";import{t as xe,q as Ee,e as $e,B as q,c as bt,b as zt,s as Ut,T as Vt,f as _t,g as Kt,h as Qt}from"./app-yrdXegKB.js";import{B as oe}from"./badge-BYKFKxPI.js";import{c as Ne}from"./global-CHsQhrWl.js";import{d as ut,g as mt,a as pt,b as Gt,c as ht,e as xt,r as Wt,f as Be,m as Ve,h as Jt,u as Xt,P as lt,i as Yt,j as Oe,S as Zt,B as es,M as ts,k as ss,l as as,C as vt,O as jt,n as rs,o as ns}from"./useProviderForm-BDM7-9ut.js";import{a as os}from"./query-DZF7K6hv.js";import{g as Le}from"./gateway-BGQ7-G-T.js";import{u as Ke}from"./useAppMutation-CaROpU2i.js";import{D as Xe,A as Ye,a as Ze,b as et,c as tt,d as st,e as at}from"./DialogShell-Dadn4IyM.js";import{L as ye,I as fe}from"./label-D10XnuKJ.js";import{S as Qe,a as Ge,b as We,c as Je,d as Fe}from"./select-Csn9x4DW.js";import{S as rt}from"./switch-CgcoKdbt.js";import{u as W}from"./i18n-PeX9kBVO.js";import{C as He,a as qe}from"./card-BzBD4ugM.js";import{a as it}from"./PageState-BfMFsTrq.js";import{b as is}from"./types-DYz12j32.js";import{D as ls}from"./disclosure-DtTSMZlG.js";import{P as ds,c as cs,b as us}from"./popover-CVazrITd.js";import"./radix-Bux_1C5J.js";function ms(a){const{t,pushToast:i,config:s,setConfig:n,configQuery:p,customEndpoints:h,tabs:k,ensureConfig:g}=a,y=os(),[l,u]=f.useState({}),[d,w]=f.useState({}),[b,c]=f.useState(null),[v,N]=f.useState({}),[C,R]=f.useState({}),[Z,K]=f.useState({}),[T,j]=f.useState(null),[D,B]=f.useState(null),[z,V]=f.useState(null),[ae,A]=f.useState(!1),[ie,X]=f.useState(null),[M,I]=f.useState({}),[H,Ce]=f.useState(null),re=f.useRef(null),[Se,me]=f.useState(null),pe=r=>{re.current=r,me(r)},he=()=>{re.current=null,me(null)},be=f.useMemo(()=>k.filter(r=>r.key!=="providers"),[k]);f.useEffect(()=>{if(!p.data)return;const r=p.data;u(m=>{const o=ut(r,h);if(!m||Object.keys(m).length===0)return o;const x={...o};for(const[S,O]of Object.entries(m)){if(!(S in o))continue;const F=mt(r,h,S);if(pt(O,F))x[S]=O;else{const J=new Map(O.map(_=>[_.source,_.id]));x[S]=o[S].map(_=>({..._,id:J.get(_.source)??_.id}))}}return x}),I(m=>{const o=Gt(r,h);if(!m||Object.keys(m).length===0)return o;const x={...o};for(const[S,O]of Object.entries(m)){if(!(S in o))continue;const F=ht(r,h,S);JSON.stringify(O)!==JSON.stringify(F)&&(x[S]=O)}return x}),w({}),N(xt(r,h))},[p.data,h]);const we=(s==null?void 0:s.providers)??[],ke=f.useMemo(()=>{const r=[],m=new Set;for(const o of we){const x=o.label&&o.label!==o.id?`${o.label} (${o.id})`:o.id,S=o.models??[];if(S.length>0)for(const F of S){const J=`${o.id}:${F.id}`;m.has(J)||(m.add(J),r.push({value:J,label:`${x} · ${F.label??F.id}`,providerId:o.id,providerLabel:x,modelId:F.id,modelLabel:F.label??F.id,kind:"model",isDefault:o.defaultModel===F.id}))}else if(o.defaultModel){const F=`${o.id}:${o.defaultModel}`;m.has(F)||(m.add(F),r.push({value:F,label:`${x} · ${o.defaultModel}`,providerId:o.id,providerLabel:x,modelId:o.defaultModel,modelLabel:o.defaultModel,kind:"model",isDefault:!0}))}const O=`${o.id}:*`;m.has(O)||(m.add(O),r.push({value:O,label:t("settings.routing.providerPassthroughOption",{provider:x}),providerId:o.id,providerLabel:x,modelId:"*",modelLabel:"*",kind:"passthrough"}))}for(const o of Object.values(l).flat()){const x=o.target.trim();x&&!m.has(x)&&(m.add(x),r.push({value:x,label:x,modelId:x,modelLabel:x,kind:"custom"}))}return r},[we,l,t]),L=r=>s?mt(s,h,r):{},Y=f.useMemo(()=>{const r={};for(const m of be){const o=l[m.key]||[];r[m.key]=pt(o,L(m.key))}return r},[s,h,l,be]),ce=f.useMemo(()=>{const r={};if(!s)return r;for(const m of be){const o=M[m.key];if(!o){r[m.key]=!1;continue}const x=ht(s,h,m.key);r[m.key]=JSON.stringify(o)!==JSON.stringify(x)}return r},[s,h,M,be]),dt=(r,m,o)=>{I(x=>({...x,[r]:{...x[r]??{completion:null,reasoning:null,background:null,longContextThreshold:6e4},[m]:o}}))},P=async r=>{var x,S,O,F,J,_,Q,ne;if(!g()||re.current)return;const m=M[r];if(!m)return;const o={completion:(x=m.completion)!=null&&x.trim()?m.completion.trim():null,reasoning:(S=m.reasoning)!=null&&S.trim()?m.reasoning.trim():null,background:(O=m.background)!=null&&O.trim()?m.background.trim():null,longContextThreshold:Number.isFinite(m.longContextThreshold)&&m.longContextThreshold>0?Math.floor(m.longContextThreshold):s.defaults.longContextThreshold};Ce(r),pe(r);try{const te=h.find(G=>G.id===r);if(te){const G={...te.routing??{},defaults:o,modelRoutes:((F=te.routing)==null?void 0:F.modelRoutes)??{}};await $e.update(r,{routing:G}),n(de=>{if(!de)return de;const Ue=[...de.customEndpoints??[]],nt=Ue.findIndex(yt=>yt.id===r);return nt===-1?de:(Ue[nt]={...Ue[nt],routing:G},{...de,customEndpoints:Ue})}),await y.invalidateQueries({queryKey:Ee.customEndpoints.all()})}else{const G=r,de={...s,endpointRouting:{...s.endpointRouting??{},[G]:{defaults:o,modelRoutes:((_=(J=s.endpointRouting)==null?void 0:J[G])==null?void 0:_.modelRoutes)??(G==="anthropic"?s.modelRoutes??{}:{}),compatibility:(ne=(Q=s.endpointRouting)==null?void 0:Q[G])==null?void 0:ne.compatibility}}};await Le.saveConfig(de),n(de)}I(G=>({...G,[r]:o})),i({title:t("workbench.defaults.saveSuccess"),variant:"success"}),p.refetch()}catch(te){i({title:t("workbench.defaults.saveFailure",{message:xe(te).message}),variant:"error"})}finally{Ce(null),he()}},$=(r,m)=>{N(o=>({...o,[r]:m})),n(o=>{if(!o)return o;if(r==="anthropic"||r==="openai")return{...o,routingPresets:{...o.routingPresets,[r]:m}};const x=[...o.customEndpoints??[]],S=x.findIndex(O=>O.id===r);return S===-1?o:(x[S]={...x[S],routingPresets:m},{...o,customEndpoints:x})})},U=(r,m)=>{R(o=>({...o,[r]:m})),m.trim()&&K(o=>({...o,[r]:null}))},E=async r=>{if(!g()||re.current)return;const m=(C[r]??"").trim();if(!m){K(o=>({...o,[r]:t("modelManagement.validation.presetName")}));return}if((v[r]??[]).some(o=>o.name.toLowerCase()===m.toLowerCase())){K(o=>({...o,[r]:t("modelManagement.validation.presetDuplicate",{name:m})}));return}j(r),pe(r);try{const x=(await Ve.savePreset(r,m)).presets??[];$(r,x),R(S=>({...S,[r]:""})),K(S=>({...S,[r]:null})),i({title:t("modelManagement.toast.presetSaved",{name:m}),variant:"success"})}catch(o){i({title:t("modelManagement.toast.presetSaveFailure",{message:xe(o).message}),variant:"error"})}finally{j(null),he(),p.refetch()}},ee=async(r,m)=>{if(g()&&!re.current){B({endpoint:r,name:m.name}),pe(r);try{const x=(await Ve.applyPreset(r,m.name)).config;n(x);const S=ut(x,h);u(O=>({...O,[r]:S[r]??[]})),N(xt(x,h)),r!=="anthropic"&&r!=="openai"&&await y.invalidateQueries({queryKey:Ee.customEndpoints.all()}),i({title:t("modelManagement.toast.presetApplySuccess",{name:m.name}),variant:"success"})}catch(o){i({title:t("modelManagement.toast.presetApplyFailure",{message:xe(o).message}),variant:"error"})}finally{B(null),he(),p.refetch()}}},ve=async(r,m)=>{if(g()&&!re.current){V({endpoint:r,name:m.name}),pe(r);try{const o=await Ve.deletePreset(r,m.name);$(r,o.presets??[]),i({title:t("modelManagement.toast.presetDeleteSuccess",{name:m.name}),variant:"success"})}catch(o){i({title:t("modelManagement.toast.presetDeleteFailure",{message:xe(o).message}),variant:"error"})}finally{V(null),he(),p.refetch()}}},De=async r=>{const m=h.find(o=>o.id===r);if(!(!m||m.deletable===!1))try{await $e.delete(r),await y.invalidateQueries({queryKey:Ee.customEndpoints.all()}),n(o=>o&&{...o,customEndpoints:(o.customEndpoints??[]).filter(x=>x.id!==r)}),p.refetch(),i({title:t("modelManagement.deleteEndpointSuccess"),variant:"success"})}catch(o){const x=xe(o);i({title:t("modelManagement.deleteEndpointError",{error:x.message}),variant:"error"})}},Me=r=>{u(m=>({...m,[r]:[...m[r]||[],{id:Be(),source:"",target:""}]})),w(m=>({...m,[r]:null}))},se=async(r,m)=>{if(g()&&!re.current){A(!0),pe(r);try{if(r==="anthropic"||r==="openai"){const o=r,x=s.endpointRouting?{...s.endpointRouting}:{},S=x[o]??{defaults:s.defaults,modelRoutes:(o==="anthropic"?s.modelRoutes:{})??{}},O={defaults:S.defaults??s.defaults,modelRoutes:S.modelRoutes??{}},F={...s,endpointRouting:{...x,[o]:m?{...O,compatibility:{enabled:!0}}:{...O}}};await Le.saveConfig(F),n(F)}else{const o=[...s.customEndpoints??[]],x=o.findIndex(J=>J.id===r);if(x===-1)throw new Error(t("modelManagement.toast.endpointNotFound"));const S=o[x],O=S.routing??{defaults:s.defaults,modelRoutes:{}};o[x]={...S,routing:m?{...O,compatibility:{enabled:!0}}:{defaults:O.defaults,modelRoutes:O.modelRoutes}};const F={...s,customEndpoints:o};await Le.saveConfig(F),n(F)}i({title:t("modelManagement.toast.compatibilitySaved",{state:t(m?"common.status.enabled":"common.status.disabled")}),variant:"success"}),p.refetch()}catch(o){const x=xe(o);i({title:t("modelManagement.toast.compatibilitySaveFailure",{message:x.message}),variant:"error"})}finally{A(!1),he()}}},je=(r,m)=>{u(o=>{const x=o[r]||[];return x.some(S=>S.source.trim()===m.trim())?o:{...o,[r]:[...x,{id:Be(),source:m,target:""}]}}),w(o=>({...o,[r]:null}))},Re=(r,m,o,x)=>{u(S=>({...S,[r]:(S[r]||[]).map(O=>O.id===m?{...O,[o]:x}:O)})),w(S=>({...S,[r]:null}))},Pe=(r,m)=>{u(o=>({...o,[r]:(o[r]||[]).filter(x=>x.id!==m)})),w(o=>({...o,[r]:null}))},Te=(r,m,o)=>{m!==o&&(u(x=>{const S=x[r]||[],O=S.findIndex(J=>J.id===m),F=S.findIndex(J=>J.id===o);return O===-1||F===-1?x:{...x,[r]:Nt(S,O,F)}}),w(x=>({...x,[r]:null})))},ze=r=>{var o;if(!s)return;const m=(s.customEndpoints??h).find(x=>x.id===r);if(m)u(x=>{var S;return{...x,[r]:Object.entries(((S=m.routing)==null?void 0:S.modelRoutes)??{}).map(([O,F])=>({id:Be(),source:O,target:F}))}});else{const x=s.endpointRouting??{},S=r,O=S==="anthropic"?s.modelRoutes??{}:{},F=((o=x[S])==null?void 0:o.modelRoutes)??O;u(J=>({...J,[r]:Object.entries(F).map(([_,Q])=>({id:Be(),source:_,target:Q}))}))}w(x=>({...x,[r]:null}))},le=Ke({mutationFn:async r=>(await Le.saveConfig(r.nextConfig),r)}),ue=Ke({mutationFn:async r=>(await $e.update(r.endpoint,{routing:r.routing}),r)});return{endpointTabs:be,routesByEndpoint:l,setRoutesByEndpoint:u,routeError:d,savingRouteFor:b,presetsByEndpoint:v,presetNameByEndpoint:C,presetErrorByEndpoint:Z,savingPresetFor:T,applyingPreset:D,deletingPreset:z,savingCompatibilityPolicy:ae,writingEndpoint:Se,presetDiffDialog:ie,setPresetDiffDialog:X,providerModelOptions:ke,isDirtyByEndpoint:Y,defaultsByEndpoint:M,isDefaultsDirtyByEndpoint:ce,savingDefaultsFor:H,handleDefaultsChange:dt,handleSaveDefaults:P,handlePresetNameChange:U,handleSavePreset:E,handleApplyPreset:ee,handleDeletePreset:ve,handleDeleteEndpoint:De,handleAddRoute:Me,handleAddSuggestion:je,handleRouteChange:Re,handleRemoveRoute:Pe,handleReorderRules:Te,handleResetRoutes:ze,handleSaveRoutes:async r=>{var x,S,O,F,J;if(!g()||re.current)return;const m=l[r]||[],o={};for(const _ of m){const Q=_.source.trim(),ne=_.target.trim();if(!(!Q&&!ne)){if(!Q||!ne){w(te=>({...te,[r]:t("settings.validation.routePair")}));return}if(o[Q]){w(te=>({...te,[r]:t("settings.validation.routeDuplicate",{model:Q})}));return}o[Q]=ne}}w(_=>({..._,[r]:null})),c(r),pe(r);try{const _=h.find(Q=>Q.id===r);if(_){const Q={..._.routing??{},modelRoutes:o,defaults:((x=_.routing)==null?void 0:x.defaults)||s.defaults};await ue.mutateAsync({endpoint:r,routing:Q}),n(ne=>{if(!ne)return ne;const te=[...ne.customEndpoints??[]],G=te.findIndex(de=>de.id===r);return G===-1?ne:(te[G]={...te[G],routing:Q},{...ne,customEndpoints:te})}),await y.invalidateQueries({queryKey:Ee.customEndpoints.all()})}else{const Q={...s,endpointRouting:{...s.endpointRouting??{},[r]:{defaults:((O=(S=s.endpointRouting)==null?void 0:S[r])==null?void 0:O.defaults)??s.defaults,modelRoutes:o,compatibility:(J=(F=s.endpointRouting)==null?void 0:F[r])==null?void 0:J.compatibility}},modelRoutes:r==="anthropic"?o:s.modelRoutes??{}};await le.mutateAsync({endpoint:r,nextConfig:Q}),n(Q)}u(Q=>{const ne=Q[r]??[],te=new Map(ne.map(G=>[G.source.trim(),G.id]));return{...Q,[r]:Object.entries(o).map(([G,de])=>({id:te.get(G.trim())??Be(),source:G,target:de}))}}),i({title:t("modelManagement.toast.routesSaved"),variant:"success"}),p.refetch()}catch(_){i({title:t("modelManagement.toast.routesSaveFailure",{message:xe(_).message}),variant:"error"})}finally{c(null),he()}},handleCompatibilityEnabledChange:se,sanitizeDraftsForProvider:r=>{u(m=>{const o={};for(const[x,S]of Object.entries(m))o[x]=S.filter(O=>!Wt(O.target.trim(),r));return o})}}}function ps(a,t){const{t:i,pushToast:s,config:n,setConfig:p,configQuery:h,customEndpoints:k,ensureConfig:g}=a,{sanitizeDraftsForProvider:y}=t??{},[l,u]=f.useState(""),[d,w]=f.useState("all"),[b,c]=f.useState(!1),[v,N]=f.useState("create"),[C,R]=f.useState(void 0),[Z,K]=f.useState(null),[T,j]=f.useState({}),[D,B]=f.useState(!1),[z,V]=f.useState(null),[ae,A]=f.useState(!0),[ie,X]=f.useState({}),[M,I]=f.useState(null),H=(n==null?void 0:n.providers)??[],Ce=H.length,re=f.useMemo(()=>H.filter(P=>{var ee;if(!(d==="all"||(P.type??"custom")===d))return!1;const U=l.trim().toLowerCase();return U?[P.id,P.label??"",P.baseUrl,P.defaultModel??"",...((ee=P.models)==null?void 0:ee.map(ve=>ve.id))??[]].join(" ").toLowerCase().includes(U):!0}),[l,d,H]),Se=f.useMemo(()=>{const P=new Map;for(const $ of H){if(!$.defaultModel||!$.models)continue;const U=$.models.find(E=>E.id===$.defaultModel);U&&P.set($.id,Jt(U))}return P},[H]),me=f.useMemo(()=>[{key:"anthropic-beta",value:"claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14",label:i("providers.testDialog.options.beta.label"),description:i("providers.testDialog.options.beta.description")}],[i]),pe=()=>{g()&&(N("create"),R(void 0),c(!0))},he=P=>{g()&&(N("edit"),R(P),c(!0))},be=async P=>{if(!n)throw new Error(i("settings.toast.missingConfig"));const $=v==="create"?[...H,P]:H.map(E=>C&&E.id===C.id?{...P,id:C.id}:E),U={...n,providers:$};await Le.saveConfig(U),p(U),h.refetch(),s({title:v==="create"?i("providers.toast.createSuccess",{name:P.label||P.id}):i("providers.toast.updateSuccess",{name:P.label||P.id}),variant:"success"})},we=(P,$)=>{j(U=>({...U,[P]:$}))},ke=async(P,$)=>{K(P.id);try{const U=$&&($.headers||$.query)?{headers:$.headers&&Object.keys($.headers).length>0?$.headers:void 0,query:$.query&&$.query.trim().length>0?$.query.trim():void 0}:void 0,E=await Ve.testProvider(P.id,U);if(E.ok){we(P.id,{ok:!0,status:E.status,statusText:E.statusText,durationMs:E.durationMs,testedAt:Date.now()}),s({title:i("providers.toast.testSuccess"),description:i("providers.toast.testSuccessDesc",{status:E.status,duration:E.durationMs?`${E.durationMs} ms`:"—"}),variant:"success"});return}we(P.id,{ok:!1,status:E.status,statusText:E.statusText,durationMs:E.durationMs,message:`${E.status} ${E.statusText}`,testedAt:Date.now()}),s({title:i("providers.toast.testFailure",{message:`${E.status} ${E.statusText}`}),variant:"error"})}catch(U){const E=xe(U),ee=E.status?`${E.status} ${E.message}`:E.message;we(P.id,{ok:!1,status:E.status,message:ee,testedAt:Date.now()}),s({title:i("providers.toast.testFailure",{message:ee}),variant:"error"})}finally{K(null)}},L=P=>{var De,Me;if(!(!!((De=P.defaultModel)!=null&&De.trim())||!!((Me=P.models)!=null&&Me.some(se=>se.id.trim().length>0)))){I(P);return}if(P.type!=="anthropic"){ke(P);return}const U=P.extraHeaders??{},E=new Map(me.map(se=>[se.key.toLowerCase(),se])),ee={};let ve=!0;for(const se of me){const je=Object.entries(U).find(([Te])=>Te.toLowerCase()===se.key.toLowerCase());if(!je)continue;const[Re,Pe]=je;String(Pe??"")!==se.value&&(ve=!1,ee[Re]=String(Pe??""))}for(const[se,je]of Object.entries(U))E.has(se.toLowerCase())||(ee[se]=String(je??""));X(ee),A(ve),V(P),B(!0)},Y=()=>{B(!1),V(null),A(!0),X({})};return{providers:H,providerCount:Ce,filteredProviders:re,providerSearch:l,setProviderSearch:u,providerTypeFilter:d,setProviderTypeFilter:w,defaultLabels:Se,drawerOpen:b,setDrawerOpen:c,drawerMode:v,setDrawerMode:N,editingProvider:C,setEditingProvider:R,testingProviderId:Z,testResults:T,testDialogOpen:D,testDialogProvider:z,testDialogUsePreset:ae,setTestDialogUsePreset:A,testDialogPreservedExtras:ie,noModelDialogProvider:M,setNoModelDialogProvider:I,anthropicTestHeaderOptions:me,handleOpenCreate:pe,handleOpenEdit:he,handleProviderSubmit:be,handleDeleteProvider:async P=>{var se,je,Re,Pe,Te,ze;if(!g())return;const $=H.filter(le=>le.id!==P.id),U=le=>{const ue={};if(!le)return ue;for(const[Ie,Ae]of Object.entries(le)){if(!Ae)continue;const[r]=Ae.split(":");r&&r===P.id||Ae===P.id||(ue[Ie]=Ae)}return ue},E=(n==null?void 0:n.endpointRouting)??{},ee=U(((se=E.anthropic)==null?void 0:se.modelRoutes)??(n==null?void 0:n.modelRoutes)??{}),ve=U(((je=E.openai)==null?void 0:je.modelRoutes)??{}),De=((n==null?void 0:n.customEndpoints)??k).map(le=>{const ue=le.routing,Ie=ue==null?void 0:ue.modelRoutes;return Ie?{...le,routing:{...ue,defaults:ue.defaults??n.defaults,modelRoutes:U(Ie)}}:le}),Me={...n,providers:$,modelRoutes:ee,customEndpoints:De,endpointRouting:{anthropic:{defaults:((Re=E.anthropic)==null?void 0:Re.defaults)??n.defaults,modelRoutes:ee,compatibility:(Pe=E.anthropic)==null?void 0:Pe.compatibility},openai:{defaults:((Te=E.openai)==null?void 0:Te.defaults)??n.defaults,modelRoutes:ve,compatibility:(ze=E.openai)==null?void 0:ze.compatibility}}};try{await Le.saveConfig(Me),p(Me),y==null||y(P.id),(C==null?void 0:C.id)===P.id&&(c(!1),R(void 0),N("create")),s({title:i("providers.toast.deleteSuccess",{name:P.label||P.id}),variant:"success"}),h.refetch()}catch(le){s({title:i("providers.toast.deleteFailure",{message:xe(le).message}),variant:"error"})}},handleTestConnection:ke,initiateTestConnection:L,closeTestDialog:Y,confirmTestDialog:async()=>{if(!z)return;const P={};if(ae)for(const E of me)P[E.key]=E.value;const $=new Map(me.map(E=>[E.key.toLowerCase(),E]));for(const[E,ee]of Object.entries(ie))$.get(E.toLowerCase())&&ae||(P[E]=ee);const U=z;Y(),await ke(U,{headers:Object.keys(P).length>0?P:void 0})}}}const hs=["anthropic","openai-auto","openai-chat","openai-responses"];function xs({open:a,endpoint:t,onClose:i,onSuccess:s}){const{t:n}=W(),[p,h]=f.useState({id:"",label:"",paths:[{path:"",protocol:"openai-auto"}],enabled:!0});f.useEffect(()=>{if(a){if(t){const c=t.paths&&t.paths.length>0?t.paths:t.path&&t.protocol?[{path:t.path,protocol:t.protocol}]:[{path:"",protocol:"openai-auto"}];h({id:t.id,label:t.label,paths:c,enabled:t.enabled!==!1});return}h({id:"",label:"",paths:[{path:"",protocol:"openai-auto"}],enabled:!0})}},[t,a]);const k=Ke({mutationFn:$e.create,invalidateKeys:[Ee.customEndpoints.all()],successToast:()=>({title:n("modelManagement.createEndpointSuccess")}),errorToast:c=>({title:n("modelManagement.createEndpointError",{error:c.message})}),onSuccess:async()=>{s(),i()}}),g=Ke({mutationFn:c=>$e.update(c.id,c.updates),invalidateKeys:[Ee.customEndpoints.all()],successToast:()=>({title:n("modelManagement.updateEndpointSuccess")}),errorToast:c=>({title:n("modelManagement.updateEndpointError",{error:c.message})}),onSuccess:async()=>{s(),i()}}),y=()=>{h(c=>({...c,paths:[...c.paths,{path:"",protocol:"anthropic"}]}))},l=c=>{p.paths.length!==1&&h(v=>({...v,paths:v.paths.filter((N,C)=>C!==c)}))},u=(c,v,N)=>{h(C=>{const R=[...C.paths];return R[c]={...R[c],[v]:N},{...C,paths:R}})},d=c=>{if(c==null||c.preventDefault(),!p.id.trim()||!p.label.trim())return;for(const N of p.paths)if(!N.path.trim())return;const v=p.paths.map(N=>({path:N.path.trim(),protocol:N.protocol}));if(t){g.mutate({id:t.id,updates:{label:p.label.trim(),paths:v,enabled:p.enabled}});return}k.mutate({id:p.id.trim(),label:p.label.trim(),paths:v,enabled:p.enabled})},w=k.isPending||g.isPending,b=p.paths.length===0?n("modelManagement.atLeastOnePath"):!p.id.trim()||!p.label.trim()?n("modelManagement.endpointValidationError"):p.paths.some(c=>!c.path.trim())?n("modelManagement.pathValidationError"):null;return e.jsx(Xe,{open:a,onOpenChange:c=>!c&&i(),children:e.jsxs(Ye,{className:"max-w-lg",onInteractOutside:c=>c.preventDefault(),children:[e.jsxs(Ze,{children:[e.jsx(et,{children:n(t?"modelManagement.editEndpoint":"modelManagement.createEndpoint")}),e.jsx(tt,{className:"truncate font-mono text-xs",children:t?t.id:n("modelManagement.endpointRoutingHint")})]}),e.jsx(st,{children:e.jsxs("form",{id:"endpoint-form",onSubmit:d,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ye,{children:[n("modelManagement.endpointId")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(fe,{value:p.id,onChange:c=>h(v=>({...v,id:c.target.value})),placeholder:n("modelManagement.endpointIdPlaceholder"),disabled:!!t,required:!0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:n("modelManagement.endpointIdHint")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ye,{children:[n("modelManagement.endpointLabel")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(fe,{value:p.label,onChange:c=>h(v=>({...v,label:c.target.value})),placeholder:n("modelManagement.endpointLabelPlaceholder"),required:!0})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ye,{children:[n("modelManagement.endpointPaths")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsxs(q,{type:"button",variant:"ghost",size:"sm",onClick:y,children:[e.jsx(wt,{className:"mr-1 h-3 w-3"}),n("modelManagement.addPath")]})]}),e.jsx("div",{className:"space-y-3",children:p.paths.map((c,v)=>e.jsxs("div",{className:"space-y-2 rounded-xl border border-transparent bg-card p-3 shadow-[var(--surface-shadow)]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(fe,{value:c.path,onChange:N=>u(v,"path",N.target.value),placeholder:n("modelManagement.endpointPathPlaceholder"),required:!0}),e.jsxs(Qe,{value:c.protocol,onValueChange:N=>u(v,"protocol",N),children:[e.jsx(Ge,{children:e.jsx(We,{})}),e.jsx(Je,{children:hs.map(N=>e.jsx(Fe,{value:N,children:n(N==="anthropic"?"modelManagement.protocolAnthropic":N==="openai-auto"?"modelManagement.protocolOpenAI":N==="openai-chat"?"modelManagement.protocolOpenAIChat":"modelManagement.protocolOpenAIResponses")},N))})]})]}),p.paths.length>1?e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>l(v),className:"text-destructive",children:e.jsx(ft,{className:"h-4 w-4"})}):null]}),e.jsxs("div",{className:"space-y-1 text-xs text-muted-foreground",children:[v===0?e.jsx("p",{children:n("modelManagement.endpointPathHint")}):null,e.jsx("p",{children:n(`modelManagement.protocolHints.${c.protocol}`)})]})]},`${c.protocol}-${v}`))}),b?e.jsx("p",{className:"text-xs text-destructive",children:b}):null]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(rt,{id:"endpoint-enabled",checked:p.enabled,onCheckedChange:c=>h(v=>({...v,enabled:c}))}),e.jsx(ye,{htmlFor:"endpoint-enabled",children:n("modelManagement.endpointEnabled")})]}),t?null:e.jsx("div",{className:"rounded-xl bg-accent p-4",children:e.jsx("p",{className:"text-sm text-primary",children:n("modelManagement.endpointRoutingHint")})})]})}),e.jsxs(at,{children:[e.jsx(q,{variant:"outline",onClick:i,disabled:w,children:n("common.cancel")}),e.jsx(q,{type:"submit",form:"endpoint-form",disabled:w,children:n(w?"common.saving":t?"common.save":"common.create")})]})]})})}function gs({open:a,provider:t,onClose:i,onEdit:s}){const{t:n}=W();return t?e.jsx(Xe,{open:a,onOpenChange:p=>!p&&i(),children:e.jsxs(Ye,{className:"max-w-md",children:[e.jsxs(Ze,{children:[e.jsx(et,{children:n("providers.noModelDialog.title")}),e.jsx(tt,{children:n("providers.noModelDialog.subtitle",{name:t.label||t.id})})]}),e.jsxs(st,{className:"space-y-4",children:[e.jsx("div",{className:"rounded-xl bg-accent p-4 text-sm text-primary",children:n("providers.noModelDialog.description")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:n("providers.noModelDialog.hint")})]}),e.jsxs(at,{children:[e.jsx(q,{variant:"outline",onClick:i,children:n("common.actions.close")}),e.jsx(q,{onClick:()=>s(t),children:n("providers.noModelDialog.primary")})]})]})}):null}function fs({dialog:a,currentRoutes:t,onConfirm:i,onClose:s}){const{t:n}=W();if(!a)return null;const{endpoint:p,preset:h}=a,k=h.modelRoutes??{},g={};for(const b of t){const c=b.source.trim(),v=b.target.trim();c&&v&&(g[c]=v)}const y=new Set([...Object.keys(g),...Object.keys(k)]),l=[],u=[],d=[];for(const b of y){const c=b in g,v=b in k;v&&!c?l.push([b,k[b]]):c&&!v?u.push([b,g[b]]):c&&v&&g[b]!==k[b]&&d.push([b,g[b],k[b]])}const w=l.length>0||u.length>0||d.length>0;return e.jsx(Xe,{open:!0,onOpenChange:b=>!b&&s(),children:e.jsxs(Ye,{className:"max-w-2xl",children:[e.jsxs(Ze,{children:[e.jsx(et,{children:n("modelManagement.presets.diffTitle")}),e.jsx(tt,{children:n("modelManagement.presets.diffDescription",{name:h.name})})]}),e.jsx(st,{children:w?e.jsxs("div",{className:"max-h-80 space-y-2 rounded-xl bg-secondary/50 p-3 text-sm",children:[l.map(([b,c])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-success-bg px-2 py-1.5 text-success",children:[e.jsx(oe,{variant:"outline",className:"border-success/30 text-xs",children:n("modelManagement.presets.diffAdded")}),e.jsx("span",{className:"truncate",children:b}),e.jsx(ge,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:c})]},`add-${b}`)),u.map(([b,c])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-error-bg px-2 py-1.5 text-error",children:[e.jsx(oe,{variant:"outline",className:"border-error/30 text-xs",children:n("modelManagement.presets.diffRemoved")}),e.jsx("span",{className:"truncate",children:b}),e.jsx(ge,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:c})]},`rm-${b}`)),d.map(([b,c,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(oe,{variant:"outline",className:"border-warning/30 text-xs",children:n("modelManagement.presets.diffChanged")}),e.jsx("span",{className:"truncate",children:b}),e.jsx(ge,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate line-through opacity-60",children:c}),e.jsx(ge,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:v})]},`chg-${b}`))]}):e.jsx("p",{className:"rounded-xl bg-secondary/50 py-8 text-center text-sm text-muted-foreground",children:n("modelManagement.presets.diffEmpty")})}),e.jsxs(at,{children:[e.jsx(q,{variant:"outline",onClick:s,children:n("common.cancel")}),e.jsx(q,{onClick:()=>i(p,h),disabled:!w,children:n("modelManagement.presets.diffConfirm")})]})]})})}function bs({open:a,mode:t,provider:i,existingProviderIds:s,onClose:n,onSubmit:p,testResult:h,testing:k,onTest:g,onDelete:y}){const{t:l}=W(),u=Xt({mode:t,provider:i,existingProviderIds:s}),{form:d,errors:w,advancedOpen:b,providerIdRef:c}=u,[v,N]=f.useState(!1),[C,R]=f.useState(null),[Z,K]=f.useState("basics"),T=f.useRef(null),j=f.useRef(null);f.useEffect(()=>{a&&(u.resetForm(),R(null),N(!1),K("basics"))},[a,i,t,u.resetForm]);const D=f.useRef(n);D.current=n,f.useEffect(()=>{if(!a)return;const L=Y=>{Y.key==="Escape"&&(document.querySelector('[role="dialog"][data-state="open"], [role="listbox"][data-state="open"], [data-radix-popper-content-wrapper]')||D.current())};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[a]),f.useEffect(()=>{if(a){if(t==="create"&&c.current){c.current.focus();return}j.current&&j.current.focus()}},[a,t]);const B=t==="create",z=f.useMemo(()=>d.models.filter(L=>L.id.trim().length>0),[d.models]),V=f.useMemo(()=>{var L;return((L=lt.find(Y=>Y.value===d.type))==null?void 0:L.label)??"Custom"},[d.type]),ae=d.label.trim()||d.id.trim()||l("providers.drawer.summary.untitled"),A=f.useMemo(()=>[{label:l("providers.drawer.summary.type"),value:V},{label:l("providers.drawer.summary.auth"),value:Yt(d.type,d.authMode,l)},{label:l("providers.drawer.summary.models"),value:z.length.toLocaleString()}],[z.length,d.authMode,d.type,V,l]),ie=async()=>{R(null);const L=u.validateErrors();if(Object.keys(L).length>0){L.baseUrl||L.id||L.extraHeaders?(K("basics"),L.extraHeaders&&u.setAdvancedOpen(!0)):L.models&&K("models");return}N(!0);try{const Y=u.serialize();await p(Y)}catch(Y){R(l("providers.drawer.toast.saveFailure",{message:xe(Y).message})),N(!1);return}N(!1),n()};if(!a)return null;const X=Oe.findIndex(L=>L.id===Z),M=X===Oe.length-1,I=d.id.trim(),H=I.length>0&&(t==="edit"||!s.includes(I)),Ce=d.baseUrl.trim();let re=Ce.length>0;if(re)try{new URL(Ce)}catch{re=!1}let Se=!d.defaultModel||d.models.some(L=>L.id===d.defaultModel);if(Se){const L=new Set;Se=!d.models.some(Y=>{const ce=Y.id.trim();return ce.length===0||L.has(ce)?!0:(L.add(ce),!1)})}const me={basics:H&&re,models:Se},pe=Oe.map((L,Y)=>{let ce;return Y===X?ce="current":Y<X?ce=me[L.id]?"complete":"error":ce="upcoming",{id:L.id,label:l(L.labelKey),status:ce}}),he=L=>{K(L)},be=()=>{X<Oe.length-1&&K(Oe[X+1].id)},we=()=>{X>0&&K(Oe[X-1].id)},ke={form:d,errors:w,isCreate:B,advancedOpen:b,onAdvancedOpenChange:u.setAdvancedOpen,idInputRef:c,onProviderIdChange:u.handleProviderIdChange,onFieldChange:u.handleFieldChange,onTypeChange:u.handleTypeChange,onAuthModeChange:u.handleAuthModeChange,onNonStreamViaStreamChange:u.handleProviderNonStreamViaStreamChange,onUseAbsoluteUrlChange:u.handleUseAbsoluteUrlChange,onAddHeader:u.handleAddHeader,onRemoveHeader:u.handleRemoveHeader,onHeaderChange:u.handleHeaderChange,onModelIdChange:u.handleModelIdChange,onModelChange:u.handleModelChange,onAddModel:u.handleAddModel,onRemoveModel:u.handleRemoveModel,onModelNonStreamViaStreamChange:u.handleModelNonStreamViaStreamChange,onSetDefaultModel:u.handleSetDefaultModel,testVerification:g?{available:t==="edit",testing:k??!1,result:h??null,onTest:g}:void 0};return e.jsxs("div",{className:"fixed inset-0 z-50 flex",children:[e.jsx("div",{className:"flex-1 bg-background/95","aria-hidden":"true"}),e.jsxs("aside",{ref:T,role:"dialog","aria-modal":"true","aria-labelledby":"provider-drawer-title","aria-describedby":"provider-drawer-desc",className:"flex h-full min-h-0 w-full max-w-5xl flex-col border-l border-border bg-background shadow-[var(--surface-shadow-lg)]",children:[e.jsxs("header",{className:"border-b border-border bg-secondary px-6 py-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"inline-flex rounded-full border border-primary/20 bg-primary/10 px-3 py-1 text-[11px] font-medium uppercase tracking-[0.18em] text-primary",children:l(B?"providers.drawer.quickStart":"providers.drawer.editTitle")}),e.jsxs("div",{children:[e.jsx("h2",{id:"provider-drawer-title",className:"text-lg font-semibold tracking-[-0.02em]",children:l(B?"providers.drawer.createTitle":"providers.drawer.editTitle")}),e.jsx("p",{id:"provider-drawer-desc",className:"text-sm text-muted-foreground",children:l("providers.drawer.description")})]})]}),e.jsx(q,{type:"button",ref:j,variant:"outline",onClick:n,className:"bg-card",children:l("common.actions.close")})]}),e.jsx("div",{className:"mt-4 grid gap-3 md:grid-cols-3",children:A.map(L=>e.jsxs("div",{className:"rounded-xl border border-transparent bg-card px-4 py-3 shadow-[var(--surface-shadow)]",children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground",children:L.label}),e.jsx("p",{className:"mt-2 text-sm font-semibold text-foreground",children:L.value})]},L.label))})]}),e.jsxs("div",{className:"grid min-h-0 flex-1 overflow-hidden xl:grid-cols-[minmax(0,1fr)_280px]",children:[e.jsxs("div",{className:"min-h-0 overflow-y-auto px-6 py-5 pb-10",children:[e.jsx(Zt,{steps:pe,current:Z,onSelect:he,className:"mb-6"}),Z==="basics"?e.jsx(es,{...ke}):null,Z==="models"?e.jsx(ts,{...ke}):null]}),e.jsx("aside",{className:"hidden min-h-0 overflow-y-auto border-l border-border/45 bg-secondary/40 px-5 py-5 xl:block",children:e.jsxs("div",{className:"sticky top-0 space-y-5",children:[e.jsxs("div",{className:"rounded-xl border border-transparent bg-card p-4 shadow-[var(--surface-shadow)]",children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground",children:l("providers.drawer.formSummary")}),e.jsx("p",{className:"mt-2 text-base font-semibold",children:ae}),e.jsx("div",{className:"mt-4 space-y-3 text-sm",children:A.map(L=>e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("span",{className:"text-muted-foreground",children:L.label}),e.jsx("span",{className:"text-right font-medium",children:L.value})]},L.label))})]}),e.jsxs("div",{className:"rounded-xl border border-transparent bg-card p-4 shadow-[var(--surface-shadow)]",children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground",children:l("providers.drawer.sections.checklist")}),e.jsxs("ul",{className:"mt-3 space-y-2 text-sm text-muted-foreground",children:[e.jsx("li",{children:l("providers.drawer.hints.checkUrl")}),e.jsx("li",{children:l("providers.drawer.hints.checkAuth")}),e.jsx("li",{children:l("providers.drawer.hints.checkModels")})]})]}),b&&e.jsxs("div",{className:"rounded-xl bg-accent p-4 text-sm text-foreground",children:[e.jsx("p",{className:"font-medium text-primary",children:l("providers.drawer.hints.advancedTitle")}),e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:l("providers.drawer.hints.advancedBody")})]})]})})]}),e.jsxs("footer",{className:"flex items-center justify-between gap-3 border-t border-border bg-secondary px-6 py-4 text-sm",children:[e.jsxs("div",{className:"flex flex-col gap-1 text-xs",children:[!B&&y?e.jsx("button",{type:"button",onClick:y,disabled:v,className:"text-muted-foreground underline-offset-2 hover:text-destructive hover:underline disabled:opacity-50",children:l("providers.actions.delete")}):null,C?e.jsx("span",{className:"text-destructive","aria-live":"polite",children:C}):null]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(q,{type:"button",variant:"outline",onClick:n,disabled:v,className:"bg-card",children:l("common.actions.cancel")}),e.jsx(q,{type:"button",variant:"outline",onClick:we,disabled:v||X===0,className:"bg-card",children:l("common.actions.previous")}),M?null:e.jsx(q,{type:"button",onClick:be,disabled:v,children:l("common.actions.next")}),e.jsx(q,{type:"button",onClick:ie,disabled:v,children:l(v?"common.actions.saving":"common.actions.save")})]})]})]})]})}function vs({provider:a,defaultModel:t,modelCount:i,requests24h:s,avgLatencyMs:n,routeCount:p,testResult:h,onTest:k,onEdit:g}){var b;const{t:y}=W(),l=a.label||a.id,u=l.slice(0,1).toUpperCase()||"?",d=((b=lt.find(c=>c.value===(a.type??"custom")))==null?void 0:b.label)??a.type??"custom",w=h?h.ok?"ok":"fail":"untested";return e.jsxs("div",{"data-testid":"provider-card",className:"flex flex-col rounded-lg border border-border bg-card p-4 transition-colors hover:border-primary/40",children:[e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-secondary text-sm font-semibold text-muted-foreground",children:u}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"truncate text-[13px] font-semibold text-foreground",title:l,children:l}),e.jsx(oe,{variant:"outline",className:"shrink-0 rounded-full px-2 py-0 text-[10px] font-normal text-muted-foreground",children:d})]}),e.jsx("code",{className:"mt-0.5 block truncate font-mono text-[10.5px] text-muted-foreground",title:a.baseUrl,children:a.baseUrl})]}),e.jsx(js,{state:w})]}),e.jsxs("div",{className:"mt-3 grid grid-cols-3 gap-2",children:[e.jsx(ot,{label:y("providers.card.statModels"),value:i>0?String(i):"—"}),e.jsx(ot,{label:y("providers.card.statRequests24h"),value:s!=null?s.toLocaleString():"—"}),e.jsx(ot,{label:y("providers.card.statAvgLatency"),value:is(n,y("common.units.ms"),{maximumFractionDigits:0})})]}),e.jsxs("div",{className:"mt-2.5 flex items-center gap-1.5 text-[11px] text-muted-foreground",children:[e.jsx("span",{className:"shrink-0",children:y("providers.card.defaultModelLabel")}),t?e.jsx("code",{className:"min-w-0 truncate rounded bg-secondary px-1.5 py-0.5 font-mono text-[10.5px] text-foreground",title:t,children:t}):e.jsx("span",{children:"—"})]}),e.jsxs("div",{className:"mt-3 flex items-center gap-1.5 border-t border-border pt-2.5 text-[10.5px] text-muted-foreground",children:[e.jsx("span",{className:"truncate",children:y("providers.card.routeCount",{count:p})}),e.jsxs("div",{className:"ml-auto flex shrink-0 gap-1.5",children:[e.jsx(q,{variant:"outline",size:"sm",className:"h-7 px-2.5 text-[11px]",onClick:k,children:y("providers.actions.test")}),e.jsx(q,{variant:"outline",size:"sm",className:"h-7 px-2.5 text-[11px]",onClick:g,children:y("providers.actions.edit")})]})]})]})}function ot({label:a,value:t}){return e.jsxs("div",{className:"rounded bg-secondary/60 px-2.5 py-2",children:[e.jsx("div",{className:"text-[10px] text-muted-foreground",children:a}),e.jsx("div",{className:"metric-number mt-0.5 truncate text-[13px] font-semibold text-foreground",children:t})]})}function js({state:a}){const{t}=W();return a==="ok"?e.jsx(oe,{variant:"success",className:"shrink-0 rounded-full px-1.5 py-0 text-[10px]",children:t("providers.card.health.ok")}):a==="fail"?e.jsx(oe,{variant:"destructive",className:"shrink-0 rounded-full px-1.5 py-0 text-[10px]",children:t("providers.card.health.fail")}):e.jsx(oe,{variant:"secondary",className:"shrink-0 rounded-full px-1.5 py-0 text-[10px]",children:t("providers.card.health.untested")})}function ys({providersLength:a,filteredProviders:t,testResults:i,providerSearch:s,providerTypeFilter:n,configPending:p,defaultLabels:h,config:k,customEndpoints:g,onTest:y,onEdit:l,onProviderSearchChange:u,onProviderTypeChange:d,onResetFilters:w}){const{t:b}=W(),[c,v]=f.useState("usage"),N=bt(Ee.stats.model(1,50),{url:"/api/stats/model",method:"GET",params:{days:1,limit:50}},{retry:!1}),{requestsByProvider:C,latencyByProvider:R}=f.useMemo(()=>{const T=new Map,j=new Map,D=new Map;for(const z of N.data??[]){const V=z.provider;T.set(V,(T.get(V)??0)+z.requests),z.avgLatencyMs>0&&(j.set(V,(j.get(V)??0)+z.avgLatencyMs*z.requests),D.set(V,(D.get(V)??0)+z.requests))}const B=new Map;for(const z of T.keys()){const V=D.get(z)??0;B.set(z,V>0?(j.get(z)??0)/V:null)}return{requestsByProvider:T,latencyByProvider:B}},[N.data]),Z=f.useMemo(()=>{const T=new Map;for(const j of t)T.set(j.id,ss(k,g,j.id).length);return T},[k,g,t]),K=f.useMemo(()=>{const T=[...t],j=(D,B)=>(D.label||D.id).localeCompare(B.label||B.id);return c==="usage"&&N.isSuccess?T.sort((D,B)=>(C.get(B.id)??0)-(C.get(D.id)??0)||j(D,B)):T.sort(j),T},[t,c,N.isSuccess,C]);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(He,{className:"overflow-hidden",children:e.jsx(qe,{className:"p-0",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2 bg-secondary/50 px-4 py-3",children:[e.jsx(fe,{value:s,onChange:T=>u(T.target.value),placeholder:b("providers.filters.searchPlaceholder"),className:"h-9 w-full sm:w-64"}),e.jsxs(Qe,{value:n,onValueChange:d,children:[e.jsx(Ge,{className:"h-9 w-[130px] text-xs",children:e.jsx(We,{})}),e.jsxs(Je,{children:[e.jsx(Fe,{value:"all",children:b("providers.filters.typeAll")}),lt.map(T=>e.jsx(Fe,{value:T.value??"custom",children:T.label},T.value??"custom"))]})]}),e.jsxs(Qe,{value:c,onValueChange:T=>v(T),children:[e.jsx(Ge,{className:"h-9 w-[104px] text-xs","aria-label":b("providers.list.sortLabel"),children:e.jsx(We,{})}),e.jsxs(Je,{children:[e.jsx(Fe,{value:"usage",children:b("providers.list.sortUsage")}),e.jsx(Fe,{value:"name",children:b("providers.list.sortName")})]})]}),e.jsx(oe,{variant:"secondary",className:"shrink-0 rounded-full px-2.5 py-1 text-[11px]",children:t.length}),e.jsx(q,{variant:"ghost",size:"sm",onClick:w,disabled:!s.trim()&&n==="all",className:"h-9 shrink-0 rounded-full px-2.5 text-xs",children:b("common.actions.reset")})]})})}),p?e.jsx("div",{className:"flex min-h-[160px] items-center justify-center text-sm text-muted-foreground",children:b("common.loading")}):a===0?e.jsx(it,{compact:!0,title:b("providers.emptyState"),description:e.jsxs(e.Fragment,{children:[e.jsx("p",{children:b("providers.emptyStateSub")}),e.jsx("p",{className:"mt-1",children:b("workbench.list.emptyHint")})]})}):t.length===0?e.jsx(it,{compact:!0,title:b("providers.emptyFiltered")}):e.jsx("div",{className:"grid gap-3.5 sm:grid-cols-2 xl:grid-cols-3",children:K.map(T=>{var j;return e.jsx(vs,{provider:T,defaultModel:h.get(T.id),modelCount:((j=T.models)==null?void 0:j.length)??0,requests24h:N.isSuccess?C.get(T.id)??0:null,avgLatencyMs:N.isSuccess?R.get(T.id)??null:null,routeCount:Z.get(T.id)??0,testResult:i[T.id]??null,onTest:()=>y(T),onEdit:()=>l(T)},T.id)})})]})}function Ns({routing:a,endpoint:t,tabInfo:i,config:s,customEndpoints:n}){var v,N;const{t:p}=W(),h=a.routesByEndpoint[t]||[],k=a.savingRouteFor===t,g=a.savingCompatibilityPolicy,y=a.writingEndpoint===t,l=((v=i==null?void 0:i.protocols)==null?void 0:v.some(C=>C.startsWith("openai")))??t==="openai",u=as(t,s,n),d=l?(u==null?void 0:u.enabled)??!1:!1,b=((N=i==null?void 0:i.protocols)==null?void 0:N.includes("anthropic"))??t==="anthropic"?vt:jt,c=new Set(h.map(C=>C.source.trim()).filter(Boolean));return e.jsx(He,{"data-testid":"endpoint-config-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(qe,{className:"space-y-3 p-4",children:[e.jsx("h3",{className:"text-[12.5px] font-semibold",children:p("workbench.endpointConfig.title")}),l?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(ye,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:p("modelManagement.openaiCompatibility.toggleLabel")}),e.jsx("p",{className:"text-[10.5px] text-muted-foreground",children:p(d?"modelManagement.openaiCompatibility.enabledHint":"modelManagement.openaiCompatibility.disabledHint")})]}),e.jsx(rt,{"data-testid":"compatibility-toggle",checked:d,onCheckedChange:C=>void a.handleCompatibilityEnabledChange(t,C),disabled:g||y,"aria-label":p("modelManagement.openaiCompatibility.toggleLabel")})]}):null,e.jsxs("div",{children:[e.jsx("p",{className:"mb-1.5 text-[11px] text-muted-foreground",children:p("settings.routing.suggested")}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:b.map(C=>{const R=c.has(C);return e.jsx("button",{"data-testid":"suggestion-chip",type:"button",onClick:()=>a.handleAddSuggestion(t,C),disabled:k||R,className:Ne("h-6 border px-2 text-[10.5px] transition-colors",R?"border-border bg-secondary/40 text-muted-foreground/50":"border-border bg-card hover:border-primary hover:text-primary"),children:C},`${t}-${C}`)})})]})]})})}const gt=6;function _e({value:a,onChange:t,options:i,disabled:s,placeholder:n,ariaLabel:p}){const{t:h}=W(),k=f.useId(),[g,y]=f.useState(!1),[l,u]=f.useState(""),d=f.useRef(null),w=f.useRef(!1),[b,c]=zt(Ut.modelManagement.recentRouteTargets,[]),v=f.useMemo(()=>{const j=new Map;for(const D of i)j.set(D.value,D);return j},[i]),N=(j,D)=>D?[j.label,j.value,j.providerId??"",j.providerLabel??"",j.modelId??"",j.modelLabel??""].join(" ").toLowerCase().includes(D):!0,C=f.useMemo(()=>{const j=l.trim().toLowerCase(),D=i.filter(A=>N(A,j)),B=b.map(A=>v.get(A)??(j?void 0:{value:A,label:A,kind:"custom"})).filter(A=>!!A).filter(A=>N(A,j)).slice(0,gt),z=[];B.length>0&&z.push({key:"recent",label:h("modelManagement.targetPicker.recent"),options:B});const V=new Map,ae=[];for(const A of D){if(A.kind==="custom"||!A.providerId){ae.push(A);continue}const ie=`provider:${A.providerId}`,X=V.get(ie);X?X.options.push(A):V.set(ie,{key:ie,label:A.providerLabel??A.providerId,options:[A]})}return z.push(...V.values()),ae.length>0&&z.push({key:"custom",label:h("modelManagement.targetPicker.custom"),options:ae,muted:!0}),z},[v,i,b,l,h]),R=C.reduce((j,D)=>j+D.options.length,0),Z=j=>{t(j),c(D=>[j,...D.filter(B=>B!==j)].slice(0,gt)),u(""),w.current=!0,typeof document<"u"&&document.activeElement instanceof HTMLElement&&document.activeElement.blur(),y(!1),typeof window<"u"?window.requestAnimationFrame(()=>{w.current=!1}):w.current=!1},K=j=>j.kind==="passthrough"?h("modelManagement.targetPicker.passthrough"):j.kind==="custom"?h("modelManagement.targetPicker.customValue"):h("modelManagement.targetPicker.model"),T=j=>j.kind==="passthrough"||j.kind==="custom"?j.label:j.modelLabel??j.label;return e.jsxs(ds,{open:g,onOpenChange:j=>{j&&w.current||(y(j),j&&u(""))},children:[e.jsx(cs,{asChild:!0,children:e.jsx(fe,{value:a,onChange:j=>{t(j.target.value),u(j.target.value),g||y(!0)},onFocus:()=>{u(""),y(!0)},onClick:()=>{g||y(!0)},placeholder:n,disabled:s,autoComplete:"off",role:"combobox","aria-label":p,"aria-expanded":g,"aria-controls":k,"aria-autocomplete":"list"})}),e.jsxs(us,{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:j=>{var D;j.preventDefault(),(D=d.current)==null||D.focus()},onCloseAutoFocus:j=>{j.preventDefault()},children:[e.jsxs("div",{className:"space-y-2 border-b border-border px-3 py-3",children:[e.jsx(fe,{ref:d,value:l,onChange:j=>u(j.target.value),placeholder:h("modelManagement.targetPicker.searchPlaceholder"),className:"h-9",autoComplete:"off"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:l.trim()?h("modelManagement.targetPicker.matchCount",{count:R}):h("modelManagement.targetPicker.helper")})]}),R===0?e.jsx("div",{className:"px-3 py-4 text-center text-xs text-muted-foreground",children:h("common.noMatches")}):e.jsx("div",{id:k,role:"listbox",className:"min-h-0 flex-1 overflow-y-auto p-1.5",children:C.map(j=>e.jsxs("div",{className:"py-1",children:[e.jsxs("div",{className:Ne("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",j.muted&&"opacity-80"),children:[e.jsx("span",{className:"truncate",children:j.label}),e.jsx("span",{children:j.options.length})]}),e.jsx("div",{className:"space-y-1",children:j.options.map(D=>e.jsxs("button",{type:"button",role:"option","aria-selected":D.value===a.trim(),className:Ne("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",D.value===a.trim()&&"bg-accent text-accent-foreground"),onMouseDown:B=>{B.preventDefault()},onClick:()=>Z(D.value),children:[e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate font-medium",children:T(D)}),e.jsx("span",{className:"block truncate text-xs text-muted-foreground",children:D.value})]}),e.jsxs("span",{className:"flex shrink-0 items-center gap-1",children:[D.isDefault?e.jsx(oe,{variant:"secondary",className:"text-[10px]",children:h("modelManagement.targetPicker.default")}):null,e.jsx(oe,{variant:D.kind==="passthrough"?"outline":"secondary",className:"text-[10px]",children:K(D)})]})]},`${j.key}-${D.value}`))})]},j.key))})]})]})}function ws({routing:a,endpoint:t}){const{t:i}=W(),s=a.defaultsByEndpoint[t]??null,n=a.isDefaultsDirtyByEndpoint[t]??!1,p=a.savingDefaultsFor===t,h=a.writingEndpoint===t,k=a.providerModelOptions;return e.jsx(He,{"data-testid":"routing-defaults-card",className:"border-primary/40 bg-primary/5 shadow-none",children:e.jsxs(qe,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-[13px] font-semibold text-primary",children:i("workbench.defaults.title")}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:i("workbench.defaults.cardSubtitle")})]}),e.jsxs(ls,{summary:e.jsx("span",{className:"text-[11px] font-medium text-muted-foreground",children:i("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(ye,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:i("workbench.defaults.reasoningLabel")}),e.jsx(_e,{value:(s==null?void 0:s.reasoning)??"",onChange:g=>a.handleDefaultsChange(t,"reasoning",g),options:k,disabled:p,ariaLabel:i("workbench.defaults.reasoningLabel"),placeholder:i("workbench.defaults.targetPlaceholder")})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ye,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:i("workbench.defaults.backgroundLabel")}),e.jsx(_e,{value:(s==null?void 0:s.background)??"",onChange:g=>a.handleDefaultsChange(t,"background",g),options:k,disabled:p,ariaLabel:i("workbench.defaults.backgroundLabel"),placeholder:i("workbench.defaults.targetPlaceholder")})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ye,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:i("workbench.defaults.thresholdLabel")}),e.jsx(fe,{type:"number",min:1,value:(s==null?void 0:s.longContextThreshold)||"",onChange:g=>{const y=Number.parseInt(g.target.value,10);a.handleDefaultsChange(t,"longContextThreshold",Number.isFinite(y)?y:0)},disabled:p,className:"md:w-56"})]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"border border-border bg-card px-2.5 py-2 font-mono text-xs",children:"*"}),e.jsx(ge,{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(_e,{value:(s==null?void 0:s.completion)??"",onChange:g=>a.handleDefaultsChange(t,"completion",g),options:k,disabled:p,ariaLabel:i("workbench.defaults.completionLabel"),placeholder:i("workbench.defaults.targetPlaceholder")})}),e.jsxs(q,{size:"sm","data-testid":"save-defaults",onClick:()=>void a.handleSaveDefaults(t),disabled:p||!n||h,className:"relative",children:[i(p?"common.actions.saving":"workbench.defaults.save"),n?e.jsx("span",{className:"absolute -right-1 -top-1 h-2 w-2 rounded-full bg-warning"}):null]})]})]})})}const ks={anthropic:"/anthropic",openai:"/openai"};function Cs(a){var t;return(t=a.paths)!=null&&t.length?a.paths[0].path:a.path?a.path:`/${a.id}`}function Ss({tabs:a,customEndpoints:t,routeCounts:i,selectedEndpointId:s,onSelect:n,onCreate:p,onEditEndpoint:h,onDeleteEndpoint:k}){const{t:g}=W(),y=a.map(l=>{const u=t.find(w=>w.id===l.key);if(!u)return{key:l.key,label:l.label,path:ks[l.key]??`/${l.key}`,protocols:l.protocols??[],enabled:!0};const d=u.paths??(u.path?[{path:u.path,protocol:u.protocol??"anthropic"}]:[]);return{key:l.key,label:u.label||u.id,path:Cs(u),protocols:[...new Set(d.map(w=>w.protocol))],enabled:u.enabled!==!1,custom:u}});return e.jsxs("section",{"data-testid":"endpoint-rail",className:"flex gap-2 overflow-x-auto border border-border bg-card shadow-[var(--surface-shadow)] lg:h-full lg:flex-col lg:overflow-visible",children:[e.jsxs("div",{className:"hidden shrink-0 border-b border-border/60 px-3 py-2.5 lg:block",children:[e.jsx("h2",{className:"text-[12.5px] font-semibold",children:g("workbench.endpointRail.title")}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:g("workbench.endpointRail.subtitle")})]}),e.jsxs("div",{className:"flex gap-1.5 p-2 lg:flex-col lg:gap-1",children:[y.map(l=>{const u=l.key===s,d=i[l.key]??0,w=!l.enabled;return e.jsxs("div",{"data-testid":"endpoint-row",className:Ne("flex shrink-0 items-stretch border transition-colors lg:shrink",u?"border-primary/40 bg-primary/5":"border-border bg-card hover:bg-accent",w?"opacity-60":""),children:[e.jsxs("button",{type:"button",onClick:()=>n(l.key),className:"flex min-w-0 flex-1 items-center gap-2 px-2.5 py-2 text-left",children:[e.jsx("span",{className:Ne("h-1.5 w-1.5 shrink-0 rounded-full",u?"bg-primary":"bg-muted-foreground/40"),"aria-hidden":!0}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-[11.5px] font-medium",title:l.label,children:l.label}),e.jsxs("span",{className:"mt-0.5 flex items-center gap-1.5 text-[10px] text-muted-foreground",children:[e.jsx("span",{className:"truncate font-mono",children:l.path}),e.jsx("span",{"aria-hidden":!0,children:"·"}),e.jsx("span",{className:"shrink-0 tabular-nums",children:g("workbench.endpointRail.ruleCount",{count:d})})]})]})]}),l.custom?e.jsxs("div",{className:"flex items-center gap-0.5 pr-1",children:[e.jsx("button",{type:"button",onClick:()=>h(l.custom),className:"flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-foreground",title:g("common.edit"),"aria-label":g("common.edit"),children:e.jsx(kt,{className:"h-3 w-3","aria-hidden":!0})}),l.custom.deletable!==!1?e.jsx("button",{type:"button",onClick:()=>k(l.custom),className:"flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-destructive",title:g("common.delete"),"aria-label":g("common.delete"),children:e.jsx(Ct,{className:"h-3 w-3","aria-hidden":!0})}):null]}):null]},l.key)}),e.jsxs("button",{type:"button","data-testid":"create-endpoint",onClick:p,className:"flex shrink-0 items-center justify-center border border-dashed border-border px-3 py-2 text-[11.5px] text-muted-foreground transition-colors hover:border-primary hover:text-primary lg:shrink",children:["+ ",g("workbench.endpointRail.add")]})]})]})}function Ms({endpointPath:a,defaultTarget:t}){const{t:i}=W();return e.jsxs("section",{"data-testid":"routing-flow-banner",className:"flex flex-wrap items-center gap-x-3 gap-y-2 border border-border bg-card px-4 py-3 shadow-[var(--surface-shadow)]",children:[e.jsx("span",{className:"text-[10.5px] font-semibold uppercase tracking-[0.06em] text-muted-foreground",children:i("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:i("workbench.flow.clientStep")}),e.jsx(ge,{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:[i("workbench.flow.endpointStep")," ",e.jsx("span",{className:"font-mono",children:a})]}),e.jsx(ge,{className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0}),e.jsx("span",{className:"border border-primary bg-primary/5 px-2.5 py-1 text-[11px] font-semibold text-primary",children:i("workbench.flow.matchStep")}),e.jsx(ge,{className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0}),e.jsx("span",{className:"border border-border bg-secondary px-2.5 py-1 font-mono text-[11px]",children:t||i("workbench.flow.fallbackNote")})]})]})}function Ps({routing:a,endpoint:t,onRequestDeletePreset:i}){var u,d;const{t:s}=W(),n=a.presetsByEndpoint[t]??[],p=a.presetNameByEndpoint[t]??"",h=a.presetErrorByEndpoint[t],k=a.savingPresetFor===t,g=((u=a.applyingPreset)==null?void 0:u.endpoint)===t?a.applyingPreset.name:null,y=((d=a.deletingPreset)==null?void 0:d.endpoint)===t?a.deletingPreset.name:null,l=a.writingEndpoint===t;return e.jsx(He,{"data-testid":"routing-presets-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(qe,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h3",{className:"text-[13px] font-semibold",children:s("modelManagement.presets.title")}),e.jsx(q,{variant:"outline",size:"sm","data-testid":"save-preset",onClick:()=>void a.handleSavePreset(t),disabled:k||l,children:s(k?"modelManagement.presets.saving":"modelManagement.presets.save")})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:s("modelManagement.presets.description")}),e.jsx(fe,{"data-testid":"preset-name-input",value:p,onChange:w=>a.handlePresetNameChange(t,w.target.value),placeholder:s("modelManagement.presets.namePlaceholder"),disabled:k,className:"h-8 text-xs"}),h?e.jsx("p",{className:"text-xs text-destructive",children:h}):null,n.length===0?e.jsx("p",{className:"py-2 text-center text-[11px] text-muted-foreground",children:s("modelManagement.presets.empty")}):e.jsx(Vt,{children:e.jsx("div",{className:"grid grid-cols-1 gap-1.5 sm:grid-cols-2",children:n.map(w=>{const b=g===w.name,c=y===w.name,v=Object.entries(w.modelRoutes??{}),N=v.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(_t,{children:[e.jsx(Kt,{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:w.name}),e.jsx(oe,{variant:"outline",className:"mt-0.5 text-[10px] font-normal",children:N>0?s("modelManagement.presets.rulesCount",{count:N}):s("modelManagement.presets.noRules")})]})}),N>0?e.jsx(Qt,{side:"bottom",className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1 text-xs",children:[v.slice(0,5).map(([C,R])=>e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"truncate",children:C}),e.jsx(ge,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:R})]},C)),N>5?e.jsxs("div",{className:"text-muted-foreground",children:["…+",N-5]}):null]})}):null]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"apply-preset",className:"text-[11px] font-semibold text-primary hover:underline disabled:opacity-50",onClick:()=>a.setPresetDiffDialog({endpoint:t,preset:w}),disabled:b||c||l,children:s(b?"modelManagement.presets.applying":"modelManagement.presets.apply")}),e.jsx("button",{type:"button","data-testid":"delete-preset",className:"text-[11px] text-muted-foreground hover:text-destructive disabled:opacity-50","aria-label":s("common.delete"),onClick:()=>i(t,w),disabled:c||b||l,children:s(c?"modelManagement.presets.deleting":"modelManagement.presets.delete")})]})]},w.name)})})})]})})}function Es({entry:a,index:t,savingRoute:i,options:s,sourceListId:n,onRouteChange:p,onRemoveRoute:h}){const{t:k}=W(),{attributes:g,listeners:y,setNodeRef:l,setActivatorNodeRef:u,transform:d,transition:w,isDragging:b}=St({id:a.id});return e.jsxs("div",{ref:l,"data-testid":"route-rule-row","data-id":a.id,style:{transform:Pt.Transform.toString(d),transition:w},className:Ne("flex items-center gap-2 border border-border bg-card p-2",b&&"z-10 opacity-60 shadow-[var(--surface-shadow-lg)]"),children:[e.jsx("button",{ref:u,type:"button","data-testid":"route-rule-grip","aria-label":k("workbench.routing.dragHandle"),className:"flex h-7 w-4 shrink-0 cursor-grab touch-none items-center justify-center text-muted-foreground hover:text-foreground active:cursor-grabbing",...g,...y,children:e.jsx(Mt,{className:"h-4 w-4","aria-hidden":!0})}),e.jsx("span",{className:"w-4 shrink-0 text-center text-[10.5px] tabular-nums text-muted-foreground",children:t+1}),e.jsx(fe,{"data-testid":"route-rule-source",value:a.source,onChange:c=>p(a.id,"source",c.target.value),placeholder:k("settings.routing.sourcePlaceholder"),list:n,disabled:i,className:"h-8 min-w-0 flex-1 text-xs"}),e.jsx(ge,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground","aria-hidden":!0}),e.jsx("div",{"data-testid":"route-rule-target",className:"min-w-0 flex-[1.15]",children:e.jsx(_e,{value:a.target,onChange:c=>p(a.id,"target",c),options:s,disabled:i,ariaLabel:k("workbench.routing.targetLabel"),placeholder:k("settings.routing.targetPlaceholder")})}),e.jsx(q,{variant:"ghost",size:"icon","data-testid":"route-rule-delete",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>h(a.id),disabled:i,"aria-label":k("common.delete"),children:e.jsx(ft,{className:"h-3.5 w-3.5","aria-hidden":!0})})]})}function Ds({routing:a,endpoint:t,tabInfo:i}){var c;const{t:s}=W(),n=a.routesByEndpoint[t]||[],p=a.routeError[t],h=a.savingRouteFor===t,k=a.isDirtyByEndpoint[t]??!1,g=a.writingEndpoint===t,y=a.providerModelOptions,l=`route-source-${t}`,u=Et(ct(It,{activationConstraint:{distance:6}}),ct(Ft,{coordinateGetter:Lt})),d=v=>{const{active:N,over:C}=v;!C||N.id===C.id||a.handleReorderRules(t,String(N.id),String(C.id))},b=((c=i==null?void 0:i.protocols)==null?void 0:c.includes("anthropic"))??t==="anthropic"?vt:jt;return e.jsx(He,{"data-testid":"routing-rules-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(qe,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h3",{className:"flex items-center gap-2 text-[13px] font-semibold",children:[s("workbench.routing.rulesTitle"),e.jsx(oe,{variant:"outline",className:"text-[10.5px] font-normal tabular-nums",children:n.length})]}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:s("workbench.routing.rulesSubtitle")})]}),e.jsx(q,{variant:"outline",size:"sm","data-testid":"add-route",onClick:()=>a.handleAddRoute(t),disabled:h,children:s("settings.routing.add")})]}),p?e.jsx("p",{className:"text-xs text-destructive",children:p}):null,n.length===0?e.jsx(it,{compact:!0,title:s("workbench.routing.emptyTitle"),description:s("workbench.routing.emptyDescription"),action:e.jsx(q,{size:"sm",onClick:()=>a.handleAddRoute(t),disabled:h,children:s("workbench.routing.addFirst")})}):e.jsx(Dt,{sensors:u,collisionDetection:Rt,onDragEnd:d,children:e.jsx(Tt,{items:n.map(v=>v.id),strategy:Ot,children:e.jsx("div",{className:"flex flex-col gap-1.5",children:n.map((v,N)=>e.jsx(Es,{entry:v,index:N,savingRoute:h,options:y,sourceListId:l,onRouteChange:(C,R,Z)=>a.handleRouteChange(t,C,R,Z),onRemoveRoute:C=>a.handleRemoveRoute(t,C)},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:s(k?"modelManagement.actions.footerDirtyHint":"modelManagement.actions.footerSavedHint")}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(q,{variant:"outline",size:"sm","data-testid":"reset-routes",onClick:()=>a.handleResetRoutes(t),disabled:h||!k,children:s("common.actions.reset")}),e.jsxs(q,{size:"sm","data-testid":"save-routes",onClick:()=>void a.handleSaveRoutes(t),disabled:h||g,className:"relative",children:[s(h?"common.actions.saving":"modelManagement.actions.saveRoutes"),k?e.jsx("span",{className:"absolute -right-1 -top-1 h-2 w-2 rounded-full bg-warning"}):null]})]})]}),e.jsx("datalist",{id:l,children:b.map(v=>e.jsx("option",{value:v},`${l}-${v}`))})]})})}const Rs={simulateRequest(a){return{url:"/api/routing/simulate",method:"POST",data:a}}},Ts=350;function Os(a,t){switch(a.kind){case"modelRoute":return{label:a.viaAlias?t("workbench.hitSim.reasonModelRouteAlias"):t("workbench.hitSim.reasonModelRoute"),tone:"hit"};case"directMatch":return{label:t("workbench.hitSim.reasonDirectMatch"),tone:"hit"};case"thinkingDefault":return{label:t("workbench.hitSim.reasonThinkingDefault"),tone:"hit"};case"completionDefault":return{label:t("workbench.hitSim.reasonCompletionDefault"),tone:"hit"};case"longContextDefault":return{label:t("workbench.hitSim.reasonLongContext"),tone:"hit",detail:t("workbench.hitSim.longContextDetail",{estimate:a.tokenEstimate.toLocaleString(),threshold:a.threshold.toLocaleString()})};case"fallback":return{label:t("workbench.hitSim.reasonFallback"),tone:"fallback"}}return{label:t("workbench.hitSim.reasonFallback"),tone:"fallback"}}function Ls({tabs:a,endpoint:t,onEndpointChange:i}){var C;const{t:s}=W(),n=a.filter(R=>R.key!=="providers"),[p,h]=f.useState(((C=n[0])==null?void 0:C.key)??"anthropic"),k=t??p,g=R=>{t&&i?i(R):h(R)},[y,l]=f.useState(""),[u,d]=f.useState(!1),[w,b]=f.useState("");f.useEffect(()=>{const R=setTimeout(()=>b(y.trim()),Ts);return()=>clearTimeout(R)},[y]);const{data:c,isFetching:v,error:N}=bt(["routing","simulate",k,w,u],Rs.simulateRequest({endpoint:k,model:w||void 0,thinking:u}),{retry:!1,refetchOnWindowFocus:!1,staleTime:1/0});return e.jsxs("section",{"data-testid":"routing-hit-simulator",className:"space-y-3 rounded-lg border border-border bg-card p-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm font-semibold text-foreground",children:s("workbench.hitSim.title")}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:s("workbench.hitSim.subtitle")})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-2",children:[t?null:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:s("workbench.hitSim.endpointLabel")}),e.jsxs(Qe,{value:k,onValueChange:g,children:[e.jsx(Ge,{className:"h-8 w-[168px]",children:e.jsx(We,{})}),e.jsx(Je,{children:n.map(R=>e.jsx(Fe,{value:R.key,children:R.label},R.key))})]})]}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(rt,{checked:u,onCheckedChange:d,"aria-label":s("workbench.hitSim.thinking")}),s("workbench.hitSim.thinking")]})]}),e.jsx(fe,{value:y,onChange:R=>l(R.target.value),placeholder:s("workbench.hitSim.modelPlaceholder"),className:"h-9 text-xs",spellCheck:!1,autoComplete:"off","aria-label":s("workbench.hitSim.modelPlaceholder")}),e.jsx(Fs,{result:c,loading:v,errorMessage:(N==null?void 0:N.message)??null,requestedModel:w})]})}function Fs({result:a,loading:t,errorMessage:i,requestedModel:s}){const{t:n}=W();if(i)return e.jsxs("p",{className:"text-xs text-muted-foreground",children:[n("workbench.hitSim.errorPrefix"),": ",i]});if(!a)return t?e.jsx("div",{className:"h-[72px] animate-pulse rounded-lg border border-border bg-secondary"}):e.jsx("p",{className:"text-xs text-muted-foreground",children:n("workbench.hitSim.empty")});const p=Os(a.reason,n),h=p.tone==="fallback",k=s||n("workbench.hitSim.anyModel");return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:h?"rounded-lg border border-border bg-secondary px-3 py-2.5":"rounded-lg border border-success bg-success-bg px-3 py-2.5",children:[e.jsx("div",{className:h?"text-[11px] font-semibold text-warning":"text-[11px] font-semibold text-success",children:p.label}),e.jsx("div",{className:"mt-1 text-xs text-foreground",children:k}),e.jsxs("div",{className:"mt-1 text-xs text-muted-foreground",children:["→ ",a.providerLabel,":",a.modelId]}),p.detail?e.jsx("div",{className:"mt-1 text-[11px] text-muted-foreground",children:p.detail}):null]}),h?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:n("workbench.hitSim.fallbackHint")}):null]})}function Is({routing:a,config:t,customEndpoints:i,selectedEndpointId:s,routeCounts:n,onSelectEndpoint:p,onCreateEndpoint:h,onEditEndpoint:k,onDeleteEndpoint:g,onRequestDeletePreset:y}){var b;W();const l=s??((b=a.endpointTabs[0])==null?void 0:b.key)??"anthropic",u=a.endpointTabs.find(c=>c.key===l),d=a.defaultsByEndpoint[l],w=(()=>{var v;if(l==="anthropic")return"/anthropic";if(l==="openai")return"/openai";const c=i.find(N=>N.id===l);return(v=c==null?void 0:c.paths)!=null&&v.length?c.paths[0].path:c!=null&&c.path?c.path:`/${l}`})();return e.jsxs("div",{"data-testid":"routing-workspace",className:"flex flex-col gap-3.5",children:[e.jsx(Ms,{endpointPath:w,defaultTarget:(d==null?void 0:d.completion)??null}),e.jsxs("div",{className:"grid items-start gap-3.5 lg:grid-cols-[200px_minmax(0,1fr)_288px]",children:[e.jsx(Ss,{tabs:a.endpointTabs,customEndpoints:i,routeCounts:n,selectedEndpointId:l,onSelect:p,onCreate:h,onEditEndpoint:k,onDeleteEndpoint:g}),e.jsxs("div",{className:"flex flex-col gap-3.5",children:[e.jsx(ws,{routing:a,endpoint:l}),e.jsx(Ds,{routing:a,endpoint:l,tabInfo:u}),e.jsx(Ps,{routing:a,endpoint:l,onRequestDeletePreset:y})]}),e.jsxs("div",{className:"flex flex-col gap-3.5",children:[e.jsx(Ls,{tabs:a.endpointTabs,endpoint:l,onEndpointChange:p}),e.jsx(Ns,{routing:a,endpoint:l,tabInfo:u,config:t,customEndpoints:i})]})]})]})}function As({open:a,provider:t,options:i,usePreset:s,preservedExtras:n,onPresetChange:p,onConfirm:h,onClose:k}){const{t:g}=W();return t?e.jsx(Xe,{open:a,onOpenChange:y=>!y&&k(),children:e.jsxs(Ye,{className:"max-w-2xl",onInteractOutside:y=>y.preventDefault(),children:[e.jsxs(Ze,{children:[e.jsx(et,{children:g("providers.testDialog.title")}),e.jsx(tt,{children:g("providers.testDialog.subtitle",{name:t.label||t.id})})]}),e.jsxs(st,{className:"space-y-4",children:[e.jsx("div",{className:"rounded-xl bg-accent p-4 text-sm text-primary",children:g("providers.testDialog.description")}),e.jsxs("div",{className:"space-y-4 rounded-xl bg-secondary/50 p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ye,{htmlFor:"provider-test-preset",children:g("providers.testDialog.presetLabel")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:g("providers.testDialog.presetDescription")})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(rt,{id:"provider-test-preset",checked:s,onCheckedChange:p})})]}),s?e.jsx("div",{className:"space-y-2",children:e.jsxs("details",{className:"rounded-xl border border-transparent bg-card p-2 text-xs shadow-[var(--surface-shadow)]",children:[e.jsx("summary",{className:"cursor-pointer text-primary hover:underline",children:g("providers.testDialog.presetPreviewSummary")}),e.jsx("div",{className:"mt-2 space-y-1",children:i.map(y=>e.jsxs("code",{className:"block rounded-lg bg-secondary px-2 py-1 text-xs",children:[y.key,": ",y.value]},y.key))})]})}):e.jsx("p",{className:"text-xs text-muted-foreground",children:g("providers.testDialog.presetDescription")})]}),Object.keys(n).length>0&&e.jsxs("div",{className:"space-y-2 rounded-xl bg-secondary/50 p-4 text-xs",children:[e.jsx("p",{className:"font-medium",children:g("providers.testDialog.preservedInfo")}),Object.entries(n).map(([y,l])=>e.jsxs("code",{className:"block rounded-lg border border-transparent bg-card px-2 py-1 shadow-[var(--surface-shadow)]",children:[y,": ",l]},y))]})]}),e.jsxs(at,{children:[e.jsx(q,{variant:"outline",onClick:k,children:g("providers.testDialog.cancel")}),e.jsx(q,{onClick:()=>void h(),children:g("providers.testDialog.primary")})]})]})}):null}function oa(){const{t:a}=W(),t=rs(),i=ms(t),s=ps(t,{sanitizeDraftsForProvider:i.sanitizeDraftsForProvider}),[n,p]=$t(),h=n.get("tab"),k=h==="routing"||h==="endpoints"?"routing":"providers";f.useEffect(()=>{h==="endpoints"&&p(M=>{const I=new URLSearchParams(M);return I.set("tab","routing"),I},{replace:!0})},[h,p]);const[g,y]=f.useState(!1),[l,u]=f.useState(void 0),[d,w]=f.useState(null),[b,c]=f.useState(!1),v=n.get("endpoint"),[N,C]=f.useState(v);f.useEffect(()=>{C(v)},[v]);const R=M=>{p(I=>{const H=new URLSearchParams(I);return H.set("tab","routing"),H.set("endpoint",M),H},{replace:!0})},Z=()=>{p(M=>{const I=new URLSearchParams(M);return I.delete("endpoint"),I},{replace:!0})};f.useEffect(()=>{N&&(t.customEndpointsQuery.isPending||i.endpointTabs.some(M=>M.key===N)||Z())},[N,i.endpointTabs,t.customEndpointsQuery.isPending]);const K=()=>{u(void 0),y(!0)},T=M=>{u(M),y(!0)},j=M=>{p(I=>{const H=new URLSearchParams(I);return M==="providers"?H.delete("tab"):H.set("tab",M),H},{replace:!0})},D=async()=>{if(d){c(!0);try{d.kind==="provider"?await s.handleDeleteProvider(d.provider):d.kind==="preset"?await i.handleDeletePreset(d.endpoint,d.preset):await i.handleDeleteEndpoint(d.endpoint.id),w(null)}finally{c(!1)}}},B=(d==null?void 0:d.kind)==="provider"?ns(t.config,t.customEndpoints,d.provider.id):0,z=(d==null?void 0:d.kind)==="provider"?a("providers.actions.delete"):(d==null?void 0:d.kind)==="preset"?a("modelManagement.presets.delete"):(d==null?void 0:d.kind)==="endpoint"?a("common.delete"):"",V=(d==null?void 0:d.kind)==="provider"?a("providers.confirm.delete",{name:d.provider.label||d.provider.id}):(d==null?void 0:d.kind)==="preset"?a("modelManagement.confirm.deletePreset",{name:d.preset.name}):(d==null?void 0:d.kind)==="endpoint"?a("modelManagement.deleteEndpointConfirm",{label:d.endpoint.label}):"",ae=(d==null?void 0:d.kind)==="provider"?d.provider.label||d.provider.id:(d==null?void 0:d.kind)==="preset"?d.preset.name:(d==null?void 0:d.kind)==="endpoint"?d.endpoint.label:"",A=Object.values(i.routesByEndpoint).reduce((M,I)=>M+((I==null?void 0:I.length)??0),0),ie=Object.fromEntries(Object.entries(i.routesByEndpoint).map(([M,I])=>[M,(I==null?void 0:I.length)??0])),X=[{value:"providers",icon:At,label:a("workbench.viewSwitch.providers"),description:a("workbench.viewSwitch.providersDesc"),count:s.providerCount},{value:"routing",icon:Bt,label:a("workbench.viewSwitch.routing"),description:a("workbench.viewSwitch.routingDesc"),count:A}];return e.jsxs("div",{className:"flex flex-col gap-6",children:[e.jsx(qt,{actions:k==="providers"?e.jsx(q,{size:"sm",onClick:s.handleOpenCreate,children:a("providers.actions.add")}):e.jsx(q,{size:"sm",onClick:K,children:a("workbench.endpoints.create")})}),e.jsx("div",{role:"tablist","aria-label":a("workbench.viewSwitch.label"),className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:X.map(M=>{const I=M.icon,H=k===M.value;return e.jsxs("button",{type:"button",role:"tab","aria-selected":H,onClick:()=>j(M.value),className:Ne("motion-surface flex items-center gap-3 rounded-xl border p-4 text-left",H?"border-primary/40 bg-primary/5":"border-border bg-card hover:bg-muted/40"),children:[e.jsx("span",{className:Ne("flex h-9 w-9 shrink-0 items-center justify-center rounded-lg",H?"bg-primary/10 text-primary":"bg-secondary text-muted-foreground"),children:e.jsx(I,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:Ne("text-sm font-semibold",H?"text-foreground":"text-muted-foreground"),children:M.label}),e.jsx(oe,{variant:H?"default":"secondary",className:"text-[10px]",children:M.count})]}),e.jsx("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",children:M.description})]})]},M.value)})}),k==="providers"?e.jsx(ys,{configPending:t.configQuery.isPending||!t.config&&t.configQuery.isFetching,testResults:s.testResults,filteredProviders:s.filteredProviders,providerSearch:s.providerSearch,providerTypeFilter:s.providerTypeFilter,providersLength:s.providers.length,defaultLabels:s.defaultLabels,config:t.config,customEndpoints:t.customEndpoints,onTest:M=>s.initiateTestConnection(M),onEdit:M=>s.handleOpenEdit(M),onProviderSearchChange:s.setProviderSearch,onProviderTypeChange:s.setProviderTypeFilter,onResetFilters:()=>{s.setProviderSearch(""),s.setProviderTypeFilter("all")}}):e.jsx(Is,{routing:i,config:t.config,customEndpoints:t.customEndpoints,routeCounts:ie,selectedEndpointId:N,onSelectEndpoint:R,onCreateEndpoint:K,onEditEndpoint:T,onDeleteEndpoint:M=>w({kind:"endpoint",endpoint:M}),onRequestDeletePreset:(M,I)=>w({kind:"preset",endpoint:M,preset:I})}),e.jsx(bs,{open:s.drawerOpen,mode:s.drawerMode,provider:s.drawerMode==="edit"?s.editingProvider:void 0,existingProviderIds:s.providers.map(M=>M.id).filter(M=>s.drawerMode==="edit"&&s.editingProvider?M!==s.editingProvider.id:!0),testResult:s.editingProvider?s.testResults[s.editingProvider.id]??null:null,testing:s.editingProvider?s.testingProviderId===s.editingProvider.id:!1,onTest:()=>{s.editingProvider&&s.handleTestConnection(s.editingProvider)},onDelete:()=>{s.drawerMode==="edit"&&s.editingProvider&&w({kind:"provider",provider:s.editingProvider})},onClose:()=>{s.setDrawerOpen(!1),s.setEditingProvider(void 0),s.setDrawerMode("create")},onSubmit:s.handleProviderSubmit}),e.jsx(As,{open:s.testDialogOpen,provider:s.testDialogProvider,options:s.anthropicTestHeaderOptions,preservedExtras:s.testDialogPreservedExtras,usePreset:s.testDialogUsePreset,onPresetChange:s.setTestDialogUsePreset,onConfirm:s.confirmTestDialog,onClose:s.closeTestDialog}),e.jsx(gs,{open:!!s.noModelDialogProvider,provider:s.noModelDialogProvider,onClose:()=>s.setNoModelDialogProvider(null),onEdit:M=>{s.setNoModelDialogProvider(null),s.handleOpenEdit(M)}}),e.jsx(xs,{open:g,endpoint:l,onClose:()=>{y(!1),u(void 0)},onSuccess:()=>{t.configQuery.refetch()}}),e.jsx(fs,{dialog:i.presetDiffDialog,currentRoutes:i.presetDiffDialog?i.routesByEndpoint[i.presetDiffDialog.endpoint]||[]:[],onConfirm:(M,I)=>{i.setPresetDiffDialog(null),i.handleApplyPreset(M,I)},onClose:()=>i.setPresetDiffDialog(null)}),e.jsx(Ht,{open:!!d,onOpenChange:M=>{!M&&!b&&w(null)},title:z,description:V,confirmLabel:a(b?"common.actions.loading":"common.delete"),cancelLabel:a("common.actions.cancel"),loading:b,onConfirm:D,children:ae?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:ae}),(d==null?void 0:d.kind)==="provider"&&B>0?e.jsx("p",{className:"text-xs text-muted-foreground",children:a("providers.confirm.deleteImpact",{count:B})}):null]}):null})]})}export{oa as default};
|