@chenpu17/cc-gw 0.10.1 → 0.10.2

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