@chenpu17/cc-gw 0.8.29 → 0.9.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/package.json +8 -8
  2. package/src/cli/dist/index.js +15 -1
  3. package/src/web/dist/assets/About-DY21fypB.js +1 -0
  4. package/src/web/dist/assets/ApiKeys-FWkRLPTy.js +1 -0
  5. package/src/web/dist/assets/{ConfirmDialog-BYuZwgWC.js → ConfirmDialog-CyTpXZeT.js} +1 -1
  6. package/src/web/dist/assets/Dashboard-FKM-9UNt.js +1 -0
  7. package/src/web/dist/assets/DialogShell-CM92wXHo.js +1 -0
  8. package/src/web/dist/assets/Events-x_fSf1mz.js +1 -0
  9. package/src/web/dist/assets/Help-BMgllYJq.js +4 -0
  10. package/src/web/dist/assets/Login-DrtDFqbk.js +1 -0
  11. package/src/web/dist/assets/Logs-18flgbiW.js +1 -0
  12. package/src/web/dist/assets/PageSection-N34Nu8NO.js +1 -0
  13. package/src/web/dist/assets/PageState-CFLrRswm.js +1 -0
  14. package/src/web/dist/assets/{PageToolbar-DATSQ0uI.js → PageToolbar-CWw40AFL.js} +1 -1
  15. package/src/web/dist/assets/ProvidersWorkbench-aHO5-ApY.js +1 -0
  16. package/src/web/dist/assets/Settings-iEjCAGgm.js +1 -0
  17. package/src/web/dist/assets/Setup-B1j2zExa.js +2 -0
  18. package/src/web/dist/assets/apiKeys-k1jIJuDa.js +1 -0
  19. package/src/web/dist/assets/app-Citq5KW4.js +61 -0
  20. package/src/web/dist/assets/badge-DpUlf_NW.js +1 -0
  21. package/src/web/dist/assets/card-D4YOc5eB.js +1 -0
  22. package/src/web/dist/assets/{charts-core-CK8TVJro.js → charts-core-BTTtAoo-.js} +1 -1
  23. package/src/web/dist/assets/{charts-engine-CWjgwbj5.js → charts-engine-CFhx8nba.js} +1 -1
  24. package/src/web/dist/assets/{charts-react-CmmN-08P.js → charts-react-BQP6-BFp.js} +1 -1
  25. package/src/web/dist/assets/disclosure-l5qsWhr7.js +1 -0
  26. package/src/web/dist/assets/{gateway-DhxavTUf.js → gateway-i49olSPp.js} +1 -1
  27. package/src/web/dist/assets/{global-DA-0y145.js → global-BCehxTGJ.js} +1 -1
  28. package/src/web/dist/assets/global-CIVH6GQV.css +1 -0
  29. package/src/web/dist/assets/{i18n-C8tBby0x.js → i18n-PeX9kBVO.js} +1 -1
  30. package/src/web/dist/assets/label-DSVzZIex.js +1 -0
  31. package/src/web/dist/assets/landing-W4f2Nx8j.js +17 -0
  32. package/src/web/dist/assets/metric-card-G1bbpbiR.js +1 -0
  33. package/src/web/dist/assets/package-B2CgmdJ7.js +1 -0
  34. package/src/web/dist/assets/popover-QZXvcPr8.js +1 -0
  35. package/src/web/dist/assets/{query-QCek5MsK.js → query-DZF7K6hv.js} +1 -1
  36. package/src/web/dist/assets/radix-Bux_1C5J.js +5 -0
  37. package/src/web/dist/assets/router-BoBrmro7.js +19 -0
  38. package/src/web/dist/assets/segmented-control-13KTib6k.js +1 -0
  39. package/src/web/dist/assets/select-sOwKYsgI.js +1 -0
  40. package/src/web/dist/assets/shared-Cuakym23.js +1 -0
  41. package/src/web/dist/assets/switch-7PH_rDz6.js +1 -0
  42. package/src/web/dist/assets/{table-BGY9lGZo.js → table-CVuTTP1s.js} +1 -1
  43. package/src/web/dist/assets/tabs-UWyz9J_W.js +1 -0
  44. package/src/web/dist/assets/types-DYz12j32.js +1 -0
  45. package/src/web/dist/assets/useAppMutation-CEN5Oa4S.js +1 -0
  46. package/src/web/dist/assets/useEventStream-BYg6oKvQ.js +1 -0
  47. package/src/web/dist/assets/useProviderForm-DZEYuRhD.js +1 -0
  48. package/src/web/dist/assets/utils-B_Q3Hhgb.js +3 -0
  49. package/src/web/dist/assets/vendor-CITafuNQ.js +409 -0
  50. package/src/web/dist/index.html +15 -9
  51. package/src/web/dist/landing.html +5 -5
  52. package/src/web/dist/assets/About-Cm8SdgXs.js +0 -1
  53. package/src/web/dist/assets/ApiKeys-Buc2uXF3.js +0 -1
  54. package/src/web/dist/assets/Dashboard-DShNHNh0.js +0 -1
  55. package/src/web/dist/assets/DialogShell-C0YGDw-Y.js +0 -1
  56. package/src/web/dist/assets/Events-TZCjFq06.js +0 -1
  57. package/src/web/dist/assets/Help-Bwzt4gRi.js +0 -4
  58. package/src/web/dist/assets/Login-DTIGK-8_.js +0 -1
  59. package/src/web/dist/assets/Logs-CTGZCZ3d.js +0 -1
  60. package/src/web/dist/assets/ModelManagement-Bu4yl0en.js +0 -1
  61. package/src/web/dist/assets/PageSection-D4eaagP4.js +0 -1
  62. package/src/web/dist/assets/PageState-B8pYAtQ5.js +0 -1
  63. package/src/web/dist/assets/Profiler-B-Lg2yQp.js +0 -1
  64. package/src/web/dist/assets/RoutingManagement-RFMTV2o6.js +0 -1
  65. package/src/web/dist/assets/Settings-iT-oQVjg.js +0 -1
  66. package/src/web/dist/assets/Skeleton-9Z0ltPLO.js +0 -1
  67. package/src/web/dist/assets/app-CUHICvDo.js +0 -61
  68. package/src/web/dist/assets/card-DPI7HeM2.js +0 -1
  69. package/src/web/dist/assets/global-DvELjyJN.css +0 -1
  70. package/src/web/dist/assets/input-CRm3Lt3O.js +0 -1
  71. package/src/web/dist/assets/label-D0KXM_V7.js +0 -1
  72. package/src/web/dist/assets/landing-aXQw-el0.js +0 -17
  73. package/src/web/dist/assets/live-en-events-DJwaP-WW.png +0 -0
  74. package/src/web/dist/assets/live-events-D_njD291.png +0 -0
  75. package/src/web/dist/assets/package-BcqrltRw.js +0 -1
  76. package/src/web/dist/assets/popover-DVsRdElU.js +0 -1
  77. package/src/web/dist/assets/queryKeys-DLyolp-A.js +0 -1
  78. package/src/web/dist/assets/radix-C0Bt6n-I.js +0 -5
  79. package/src/web/dist/assets/router-D2Fb4U0L.js +0 -19
  80. package/src/web/dist/assets/select-C4IDwhTu.js +0 -1
  81. package/src/web/dist/assets/switch-W7ZoAE3i.js +0 -1
  82. package/src/web/dist/assets/useApiQuery-DhdisbOK.js +0 -1
  83. package/src/web/dist/assets/useAppMutation-CJrALOdE.js +0 -1
  84. package/src/web/dist/assets/useModelManagementState-DFFjS9uq.js +0 -1
  85. package/src/web/dist/assets/utils-DNPbJsD2.js +0 -3
  86. package/src/web/dist/assets/vendor-DdPBfMMb.js +0 -437
@@ -0,0 +1 @@
1
+ import{r as f,ax as Nt,j as e,ay as wt,as as ft,ab as ge,az as kt,aA as Ct,aB as St,aC as Mt,aD as Pt,aE as Et,aF as ct,aG as Dt,aH as Rt,aI as Tt,aJ as Ot,aK as Lt,aL as Ft,aM as It,aN as At,aO as Bt}from"./vendor-CITafuNQ.js";import{d as $t}from"./router-BoBrmro7.js";import{C as Ht}from"./ConfirmDialog-CyTpXZeT.js";import{P as qt}from"./PageToolbar-CWw40AFL.js";import{t as xe,q as Ee,e as $e,B as q,c as bt,b as zt,s as Ut,T as Vt,f as _t,g as Kt,h as Qt}from"./app-Citq5KW4.js";import{B as oe}from"./badge-DpUlf_NW.js";import{c as Ne}from"./global-BCehxTGJ.js";import{d as ut,g as mt,a as pt,b as Gt,c as ht,e as xt,r as Wt,f as Be,m as Ve,h as Jt,u as Xt,P as lt,i as Yt,j as Oe,S as Zt,B as es,M as ts,k as ss,l as as,C as vt,O as jt,n as rs,o as ns}from"./useProviderForm-DZEYuRhD.js";import{a as os}from"./query-DZF7K6hv.js";import{g as Le}from"./gateway-i49olSPp.js";import{u as Ke}from"./useAppMutation-CEN5Oa4S.js";import{D as Xe,A as Ye,a as Ze,b as et,c as tt,d as st,e as at}from"./DialogShell-CM92wXHo.js";import{L as ye,I as fe}from"./label-DSVzZIex.js";import{S as Qe,a as Ge,b as We,c as Je,d as Fe}from"./select-sOwKYsgI.js";import{S as rt}from"./switch-7PH_rDz6.js";import{u as W}from"./i18n-PeX9kBVO.js";import{C as He,a as qe}from"./card-D4YOc5eB.js";import{a as it}from"./PageState-CFLrRswm.js";import{b as is}from"./types-DYz12j32.js";import{D as ls}from"./disclosure-l5qsWhr7.js";import{P as ds,c as cs,b as us}from"./popover-QZXvcPr8.js";import"./radix-Bux_1C5J.js";function ms(a){const{t,pushToast:i,config:s,setConfig:n,configQuery:p,customEndpoints:h,tabs:k,ensureConfig:g}=a,y=os(),[l,u]=f.useState({}),[d,w]=f.useState({}),[b,c]=f.useState(null),[v,N]=f.useState({}),[C,R]=f.useState({}),[Z,K]=f.useState({}),[T,j]=f.useState(null),[D,B]=f.useState(null),[z,V]=f.useState(null),[ae,A]=f.useState(!1),[ie,X]=f.useState(null),[M,I]=f.useState({}),[H,Ce]=f.useState(null),re=f.useRef(null),[Se,me]=f.useState(null),pe=r=>{re.current=r,me(r)},he=()=>{re.current=null,me(null)},be=f.useMemo(()=>k.filter(r=>r.key!=="providers"),[k]);f.useEffect(()=>{if(!p.data)return;const r=p.data;u(m=>{const o=ut(r,h);if(!m||Object.keys(m).length===0)return o;const x={...o};for(const[S,O]of Object.entries(m)){if(!(S in o))continue;const F=mt(r,h,S);if(pt(O,F))x[S]=O;else{const J=new Map(O.map(_=>[_.source,_.id]));x[S]=o[S].map(_=>({..._,id:J.get(_.source)??_.id}))}}return x}),I(m=>{const o=Gt(r,h);if(!m||Object.keys(m).length===0)return o;const x={...o};for(const[S,O]of Object.entries(m)){if(!(S in o))continue;const F=ht(r,h,S);JSON.stringify(O)!==JSON.stringify(F)&&(x[S]=O)}return x}),w({}),N(xt(r,h))},[p.data,h]);const we=(s==null?void 0:s.providers)??[],ke=f.useMemo(()=>{const r=[],m=new Set;for(const o of we){const x=o.label&&o.label!==o.id?`${o.label} (${o.id})`:o.id,S=o.models??[];if(S.length>0)for(const F of S){const J=`${o.id}:${F.id}`;m.has(J)||(m.add(J),r.push({value:J,label:`${x} · ${F.label??F.id}`,providerId:o.id,providerLabel:x,modelId:F.id,modelLabel:F.label??F.id,kind:"model",isDefault:o.defaultModel===F.id}))}else if(o.defaultModel){const F=`${o.id}:${o.defaultModel}`;m.has(F)||(m.add(F),r.push({value:F,label:`${x} · ${o.defaultModel}`,providerId:o.id,providerLabel:x,modelId:o.defaultModel,modelLabel:o.defaultModel,kind:"model",isDefault:!0}))}const O=`${o.id}:*`;m.has(O)||(m.add(O),r.push({value:O,label:t("settings.routing.providerPassthroughOption",{provider:x}),providerId:o.id,providerLabel:x,modelId:"*",modelLabel:"*",kind:"passthrough"}))}for(const o of Object.values(l).flat()){const x=o.target.trim();x&&!m.has(x)&&(m.add(x),r.push({value:x,label:x,modelId:x,modelLabel:x,kind:"custom"}))}return r},[we,l,t]),L=r=>s?mt(s,h,r):{},Y=f.useMemo(()=>{const r={};for(const m of be){const o=l[m.key]||[];r[m.key]=pt(o,L(m.key))}return r},[s,h,l,be]),ce=f.useMemo(()=>{const r={};if(!s)return r;for(const m of be){const o=M[m.key];if(!o){r[m.key]=!1;continue}const x=ht(s,h,m.key);r[m.key]=JSON.stringify(o)!==JSON.stringify(x)}return r},[s,h,M,be]),dt=(r,m,o)=>{I(x=>({...x,[r]:{...x[r]??{completion:null,reasoning:null,background:null,longContextThreshold:6e4},[m]:o}}))},P=async r=>{var x,S,O,F,J,_,Q,ne;if(!g()||re.current)return;const m=M[r];if(!m)return;const o={completion:(x=m.completion)!=null&&x.trim()?m.completion.trim():null,reasoning:(S=m.reasoning)!=null&&S.trim()?m.reasoning.trim():null,background:(O=m.background)!=null&&O.trim()?m.background.trim():null,longContextThreshold:Number.isFinite(m.longContextThreshold)&&m.longContextThreshold>0?Math.floor(m.longContextThreshold):s.defaults.longContextThreshold};Ce(r),pe(r);try{const te=h.find(G=>G.id===r);if(te){const G={...te.routing??{},defaults:o,modelRoutes:((F=te.routing)==null?void 0:F.modelRoutes)??{}};await $e.update(r,{routing:G}),n(de=>{if(!de)return de;const Ue=[...de.customEndpoints??[]],nt=Ue.findIndex(yt=>yt.id===r);return nt===-1?de:(Ue[nt]={...Ue[nt],routing:G},{...de,customEndpoints:Ue})}),await y.invalidateQueries({queryKey:Ee.customEndpoints.all()})}else{const G=r,de={...s,endpointRouting:{...s.endpointRouting??{},[G]:{defaults:o,modelRoutes:((_=(J=s.endpointRouting)==null?void 0:J[G])==null?void 0:_.modelRoutes)??(G==="anthropic"?s.modelRoutes??{}:{}),compatibility:(ne=(Q=s.endpointRouting)==null?void 0:Q[G])==null?void 0:ne.compatibility}}};await Le.saveConfig(de),n(de)}I(G=>({...G,[r]:o})),i({title:t("workbench.defaults.saveSuccess"),variant:"success"}),p.refetch()}catch(te){i({title:t("workbench.defaults.saveFailure",{message:xe(te).message}),variant:"error"})}finally{Ce(null),he()}},$=(r,m)=>{N(o=>({...o,[r]:m})),n(o=>{if(!o)return o;if(r==="anthropic"||r==="openai")return{...o,routingPresets:{...o.routingPresets,[r]:m}};const x=[...o.customEndpoints??[]],S=x.findIndex(O=>O.id===r);return S===-1?o:(x[S]={...x[S],routingPresets:m},{...o,customEndpoints:x})})},U=(r,m)=>{R(o=>({...o,[r]:m})),m.trim()&&K(o=>({...o,[r]:null}))},E=async r=>{if(!g()||re.current)return;const m=(C[r]??"").trim();if(!m){K(o=>({...o,[r]:t("modelManagement.validation.presetName")}));return}if((v[r]??[]).some(o=>o.name.toLowerCase()===m.toLowerCase())){K(o=>({...o,[r]:t("modelManagement.validation.presetDuplicate",{name:m})}));return}j(r),pe(r);try{const x=(await Ve.savePreset(r,m)).presets??[];$(r,x),R(S=>({...S,[r]:""})),K(S=>({...S,[r]:null})),i({title:t("modelManagement.toast.presetSaved",{name:m}),variant:"success"})}catch(o){i({title:t("modelManagement.toast.presetSaveFailure",{message:xe(o).message}),variant:"error"})}finally{j(null),he(),p.refetch()}},ee=async(r,m)=>{if(g()&&!re.current){B({endpoint:r,name:m.name}),pe(r);try{const x=(await Ve.applyPreset(r,m.name)).config;n(x);const S=ut(x,h);u(O=>({...O,[r]:S[r]??[]})),N(xt(x,h)),r!=="anthropic"&&r!=="openai"&&await y.invalidateQueries({queryKey:Ee.customEndpoints.all()}),i({title:t("modelManagement.toast.presetApplySuccess",{name:m.name}),variant:"success"})}catch(o){i({title:t("modelManagement.toast.presetApplyFailure",{message:xe(o).message}),variant:"error"})}finally{B(null),he(),p.refetch()}}},ve=async(r,m)=>{if(g()&&!re.current){V({endpoint:r,name:m.name}),pe(r);try{const o=await Ve.deletePreset(r,m.name);$(r,o.presets??[]),i({title:t("modelManagement.toast.presetDeleteSuccess",{name:m.name}),variant:"success"})}catch(o){i({title:t("modelManagement.toast.presetDeleteFailure",{message:xe(o).message}),variant:"error"})}finally{V(null),he(),p.refetch()}}},De=async r=>{const m=h.find(o=>o.id===r);if(!(!m||m.deletable===!1))try{await $e.delete(r),await y.invalidateQueries({queryKey:Ee.customEndpoints.all()}),n(o=>o&&{...o,customEndpoints:(o.customEndpoints??[]).filter(x=>x.id!==r)}),p.refetch(),i({title:t("modelManagement.deleteEndpointSuccess"),variant:"success"})}catch(o){const x=xe(o);i({title:t("modelManagement.deleteEndpointError",{error:x.message}),variant:"error"})}},Me=r=>{u(m=>({...m,[r]:[...m[r]||[],{id:Be(),source:"",target:""}]})),w(m=>({...m,[r]:null}))},se=async(r,m)=>{if(g()&&!re.current){A(!0),pe(r);try{if(r==="anthropic"||r==="openai"){const o=r,x=s.endpointRouting?{...s.endpointRouting}:{},S=x[o]??{defaults:s.defaults,modelRoutes:(o==="anthropic"?s.modelRoutes:{})??{}},O={defaults:S.defaults??s.defaults,modelRoutes:S.modelRoutes??{}},F={...s,endpointRouting:{...x,[o]:m?{...O,compatibility:{enabled:!0}}:{...O}}};await Le.saveConfig(F),n(F)}else{const o=[...s.customEndpoints??[]],x=o.findIndex(J=>J.id===r);if(x===-1)throw new Error(t("modelManagement.toast.endpointNotFound"));const S=o[x],O=S.routing??{defaults:s.defaults,modelRoutes:{}};o[x]={...S,routing:m?{...O,compatibility:{enabled:!0}}:{defaults:O.defaults,modelRoutes:O.modelRoutes}};const F={...s,customEndpoints:o};await Le.saveConfig(F),n(F)}i({title:t("modelManagement.toast.compatibilitySaved",{state:t(m?"common.status.enabled":"common.status.disabled")}),variant:"success"}),p.refetch()}catch(o){const x=xe(o);i({title:t("modelManagement.toast.compatibilitySaveFailure",{message:x.message}),variant:"error"})}finally{A(!1),he()}}},je=(r,m)=>{u(o=>{const x=o[r]||[];return x.some(S=>S.source.trim()===m.trim())?o:{...o,[r]:[...x,{id:Be(),source:m,target:""}]}}),w(o=>({...o,[r]:null}))},Re=(r,m,o,x)=>{u(S=>({...S,[r]:(S[r]||[]).map(O=>O.id===m?{...O,[o]:x}:O)})),w(S=>({...S,[r]:null}))},Pe=(r,m)=>{u(o=>({...o,[r]:(o[r]||[]).filter(x=>x.id!==m)})),w(o=>({...o,[r]:null}))},Te=(r,m,o)=>{m!==o&&(u(x=>{const S=x[r]||[],O=S.findIndex(J=>J.id===m),F=S.findIndex(J=>J.id===o);return O===-1||F===-1?x:{...x,[r]:Nt(S,O,F)}}),w(x=>({...x,[r]:null})))},ze=r=>{var o;if(!s)return;const m=(s.customEndpoints??h).find(x=>x.id===r);if(m)u(x=>{var S;return{...x,[r]:Object.entries(((S=m.routing)==null?void 0:S.modelRoutes)??{}).map(([O,F])=>({id:Be(),source:O,target:F}))}});else{const x=s.endpointRouting??{},S=r,O=S==="anthropic"?s.modelRoutes??{}:{},F=((o=x[S])==null?void 0:o.modelRoutes)??O;u(J=>({...J,[r]:Object.entries(F).map(([_,Q])=>({id:Be(),source:_,target:Q}))}))}w(x=>({...x,[r]:null}))},le=Ke({mutationFn:async r=>(await Le.saveConfig(r.nextConfig),r)}),ue=Ke({mutationFn:async r=>(await $e.update(r.endpoint,{routing:r.routing}),r)});return{endpointTabs:be,routesByEndpoint:l,setRoutesByEndpoint:u,routeError:d,savingRouteFor:b,presetsByEndpoint:v,presetNameByEndpoint:C,presetErrorByEndpoint:Z,savingPresetFor:T,applyingPreset:D,deletingPreset:z,savingCompatibilityPolicy:ae,writingEndpoint:Se,presetDiffDialog:ie,setPresetDiffDialog:X,providerModelOptions:ke,isDirtyByEndpoint:Y,defaultsByEndpoint:M,isDefaultsDirtyByEndpoint:ce,savingDefaultsFor:H,handleDefaultsChange:dt,handleSaveDefaults:P,handlePresetNameChange:U,handleSavePreset:E,handleApplyPreset:ee,handleDeletePreset:ve,handleDeleteEndpoint:De,handleAddRoute:Me,handleAddSuggestion:je,handleRouteChange:Re,handleRemoveRoute:Pe,handleReorderRules:Te,handleResetRoutes:ze,handleSaveRoutes:async r=>{var x,S,O,F,J;if(!g()||re.current)return;const m=l[r]||[],o={};for(const _ of m){const Q=_.source.trim(),ne=_.target.trim();if(!(!Q&&!ne)){if(!Q||!ne){w(te=>({...te,[r]:t("settings.validation.routePair")}));return}if(o[Q]){w(te=>({...te,[r]:t("settings.validation.routeDuplicate",{model:Q})}));return}o[Q]=ne}}w(_=>({..._,[r]:null})),c(r),pe(r);try{const _=h.find(Q=>Q.id===r);if(_){const Q={..._.routing??{},modelRoutes:o,defaults:((x=_.routing)==null?void 0:x.defaults)||s.defaults};await ue.mutateAsync({endpoint:r,routing:Q}),n(ne=>{if(!ne)return ne;const te=[...ne.customEndpoints??[]],G=te.findIndex(de=>de.id===r);return G===-1?ne:(te[G]={...te[G],routing:Q},{...ne,customEndpoints:te})}),await y.invalidateQueries({queryKey:Ee.customEndpoints.all()})}else{const Q={...s,endpointRouting:{...s.endpointRouting??{},[r]:{defaults:((O=(S=s.endpointRouting)==null?void 0:S[r])==null?void 0:O.defaults)??s.defaults,modelRoutes:o,compatibility:(J=(F=s.endpointRouting)==null?void 0:F[r])==null?void 0:J.compatibility}},modelRoutes:r==="anthropic"?o:s.modelRoutes??{}};await le.mutateAsync({endpoint:r,nextConfig:Q}),n(Q)}u(Q=>{const ne=Q[r]??[],te=new Map(ne.map(G=>[G.source.trim(),G.id]));return{...Q,[r]:Object.entries(o).map(([G,de])=>({id:te.get(G.trim())??Be(),source:G,target:de}))}}),i({title:t("modelManagement.toast.routesSaved"),variant:"success"}),p.refetch()}catch(_){i({title:t("modelManagement.toast.routesSaveFailure",{message:xe(_).message}),variant:"error"})}finally{c(null),he()}},handleCompatibilityEnabledChange:se,sanitizeDraftsForProvider:r=>{u(m=>{const o={};for(const[x,S]of Object.entries(m))o[x]=S.filter(O=>!Wt(O.target.trim(),r));return o})}}}function ps(a,t){const{t:i,pushToast:s,config:n,setConfig:p,configQuery:h,customEndpoints:k,ensureConfig:g}=a,{sanitizeDraftsForProvider:y}=t??{},[l,u]=f.useState(""),[d,w]=f.useState("all"),[b,c]=f.useState(!1),[v,N]=f.useState("create"),[C,R]=f.useState(void 0),[Z,K]=f.useState(null),[T,j]=f.useState({}),[D,B]=f.useState(!1),[z,V]=f.useState(null),[ae,A]=f.useState(!0),[ie,X]=f.useState({}),[M,I]=f.useState(null),H=(n==null?void 0:n.providers)??[],Ce=H.length,re=f.useMemo(()=>H.filter(P=>{var ee;if(!(d==="all"||(P.type??"custom")===d))return!1;const U=l.trim().toLowerCase();return U?[P.id,P.label??"",P.baseUrl,P.defaultModel??"",...((ee=P.models)==null?void 0:ee.map(ve=>ve.id))??[]].join(" ").toLowerCase().includes(U):!0}),[l,d,H]),Se=f.useMemo(()=>{const P=new Map;for(const $ of H){if(!$.defaultModel||!$.models)continue;const U=$.models.find(E=>E.id===$.defaultModel);U&&P.set($.id,Jt(U))}return P},[H]),me=f.useMemo(()=>[{key:"anthropic-beta",value:"claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14",label:i("providers.testDialog.options.beta.label"),description:i("providers.testDialog.options.beta.description")}],[i]),pe=()=>{g()&&(N("create"),R(void 0),c(!0))},he=P=>{g()&&(N("edit"),R(P),c(!0))},be=async P=>{if(!n)throw new Error(i("settings.toast.missingConfig"));const $=v==="create"?[...H,P]:H.map(E=>C&&E.id===C.id?{...P,id:C.id}:E),U={...n,providers:$};await Le.saveConfig(U),p(U),h.refetch(),s({title:v==="create"?i("providers.toast.createSuccess",{name:P.label||P.id}):i("providers.toast.updateSuccess",{name:P.label||P.id}),variant:"success"})},we=(P,$)=>{j(U=>({...U,[P]:$}))},ke=async(P,$)=>{K(P.id);try{const U=$&&($.headers||$.query)?{headers:$.headers&&Object.keys($.headers).length>0?$.headers:void 0,query:$.query&&$.query.trim().length>0?$.query.trim():void 0}:void 0,E=await Ve.testProvider(P.id,U);if(E.ok){we(P.id,{ok:!0,status:E.status,statusText:E.statusText,durationMs:E.durationMs,testedAt:Date.now()}),s({title:i("providers.toast.testSuccess"),description:i("providers.toast.testSuccessDesc",{status:E.status,duration:E.durationMs?`${E.durationMs} ms`:"—"}),variant:"success"});return}we(P.id,{ok:!1,status:E.status,statusText:E.statusText,durationMs:E.durationMs,message:`${E.status} ${E.statusText}`,testedAt:Date.now()}),s({title:i("providers.toast.testFailure",{message:`${E.status} ${E.statusText}`}),variant:"error"})}catch(U){const E=xe(U),ee=E.status?`${E.status} ${E.message}`:E.message;we(P.id,{ok:!1,status:E.status,message:ee,testedAt:Date.now()}),s({title:i("providers.toast.testFailure",{message:ee}),variant:"error"})}finally{K(null)}},L=P=>{var De,Me;if(!(!!((De=P.defaultModel)!=null&&De.trim())||!!((Me=P.models)!=null&&Me.some(se=>se.id.trim().length>0)))){I(P);return}if(P.type!=="anthropic"){ke(P);return}const U=P.extraHeaders??{},E=new Map(me.map(se=>[se.key.toLowerCase(),se])),ee={};let ve=!0;for(const se of me){const je=Object.entries(U).find(([Te])=>Te.toLowerCase()===se.key.toLowerCase());if(!je)continue;const[Re,Pe]=je;String(Pe??"")!==se.value&&(ve=!1,ee[Re]=String(Pe??""))}for(const[se,je]of Object.entries(U))E.has(se.toLowerCase())||(ee[se]=String(je??""));X(ee),A(ve),V(P),B(!0)},Y=()=>{B(!1),V(null),A(!0),X({})};return{providers:H,providerCount:Ce,filteredProviders:re,providerSearch:l,setProviderSearch:u,providerTypeFilter:d,setProviderTypeFilter:w,defaultLabels:Se,drawerOpen:b,setDrawerOpen:c,drawerMode:v,setDrawerMode:N,editingProvider:C,setEditingProvider:R,testingProviderId:Z,testResults:T,testDialogOpen:D,testDialogProvider:z,testDialogUsePreset:ae,setTestDialogUsePreset:A,testDialogPreservedExtras:ie,noModelDialogProvider:M,setNoModelDialogProvider:I,anthropicTestHeaderOptions:me,handleOpenCreate:pe,handleOpenEdit:he,handleProviderSubmit:be,handleDeleteProvider:async P=>{var se,je,Re,Pe,Te,ze;if(!g())return;const $=H.filter(le=>le.id!==P.id),U=le=>{const ue={};if(!le)return ue;for(const[Ie,Ae]of Object.entries(le)){if(!Ae)continue;const[r]=Ae.split(":");r&&r===P.id||Ae===P.id||(ue[Ie]=Ae)}return ue},E=(n==null?void 0:n.endpointRouting)??{},ee=U(((se=E.anthropic)==null?void 0:se.modelRoutes)??(n==null?void 0:n.modelRoutes)??{}),ve=U(((je=E.openai)==null?void 0:je.modelRoutes)??{}),De=((n==null?void 0:n.customEndpoints)??k).map(le=>{const ue=le.routing,Ie=ue==null?void 0:ue.modelRoutes;return Ie?{...le,routing:{...ue,defaults:ue.defaults??n.defaults,modelRoutes:U(Ie)}}:le}),Me={...n,providers:$,modelRoutes:ee,customEndpoints:De,endpointRouting:{anthropic:{defaults:((Re=E.anthropic)==null?void 0:Re.defaults)??n.defaults,modelRoutes:ee,compatibility:(Pe=E.anthropic)==null?void 0:Pe.compatibility},openai:{defaults:((Te=E.openai)==null?void 0:Te.defaults)??n.defaults,modelRoutes:ve,compatibility:(ze=E.openai)==null?void 0:ze.compatibility}}};try{await Le.saveConfig(Me),p(Me),y==null||y(P.id),(C==null?void 0:C.id)===P.id&&(c(!1),R(void 0),N("create")),s({title:i("providers.toast.deleteSuccess",{name:P.label||P.id}),variant:"success"}),h.refetch()}catch(le){s({title:i("providers.toast.deleteFailure",{message:xe(le).message}),variant:"error"})}},handleTestConnection:ke,initiateTestConnection:L,closeTestDialog:Y,confirmTestDialog:async()=>{if(!z)return;const P={};if(ae)for(const E of me)P[E.key]=E.value;const $=new Map(me.map(E=>[E.key.toLowerCase(),E]));for(const[E,ee]of Object.entries(ie))$.get(E.toLowerCase())&&ae||(P[E]=ee);const U=z;Y(),await ke(U,{headers:Object.keys(P).length>0?P:void 0})}}}const hs=["anthropic","openai-auto","openai-chat","openai-responses"];function xs({open:a,endpoint:t,onClose:i,onSuccess:s}){const{t:n}=W(),[p,h]=f.useState({id:"",label:"",paths:[{path:"",protocol:"openai-auto"}],enabled:!0});f.useEffect(()=>{if(a){if(t){const c=t.paths&&t.paths.length>0?t.paths:t.path&&t.protocol?[{path:t.path,protocol:t.protocol}]:[{path:"",protocol:"openai-auto"}];h({id:t.id,label:t.label,paths:c,enabled:t.enabled!==!1});return}h({id:"",label:"",paths:[{path:"",protocol:"openai-auto"}],enabled:!0})}},[t,a]);const k=Ke({mutationFn:$e.create,invalidateKeys:[Ee.customEndpoints.all()],successToast:()=>({title:n("modelManagement.createEndpointSuccess")}),errorToast:c=>({title:n("modelManagement.createEndpointError",{error:c.message})}),onSuccess:async()=>{s(),i()}}),g=Ke({mutationFn:c=>$e.update(c.id,c.updates),invalidateKeys:[Ee.customEndpoints.all()],successToast:()=>({title:n("modelManagement.updateEndpointSuccess")}),errorToast:c=>({title:n("modelManagement.updateEndpointError",{error:c.message})}),onSuccess:async()=>{s(),i()}}),y=()=>{h(c=>({...c,paths:[...c.paths,{path:"",protocol:"anthropic"}]}))},l=c=>{p.paths.length!==1&&h(v=>({...v,paths:v.paths.filter((N,C)=>C!==c)}))},u=(c,v,N)=>{h(C=>{const R=[...C.paths];return R[c]={...R[c],[v]:N},{...C,paths:R}})},d=c=>{if(c==null||c.preventDefault(),!p.id.trim()||!p.label.trim())return;for(const N of p.paths)if(!N.path.trim())return;const v=p.paths.map(N=>({path:N.path.trim(),protocol:N.protocol}));if(t){g.mutate({id:t.id,updates:{label:p.label.trim(),paths:v,enabled:p.enabled}});return}k.mutate({id:p.id.trim(),label:p.label.trim(),paths:v,enabled:p.enabled})},w=k.isPending||g.isPending,b=p.paths.length===0?n("modelManagement.atLeastOnePath"):!p.id.trim()||!p.label.trim()?n("modelManagement.endpointValidationError"):p.paths.some(c=>!c.path.trim())?n("modelManagement.pathValidationError"):null;return e.jsx(Xe,{open:a,onOpenChange:c=>!c&&i(),children:e.jsxs(Ye,{className:"max-w-lg",onInteractOutside:c=>c.preventDefault(),children:[e.jsxs(Ze,{children:[e.jsx(et,{children:n(t?"modelManagement.editEndpoint":"modelManagement.createEndpoint")}),e.jsx(tt,{className:"truncate font-mono text-xs",children:t?t.id:n("modelManagement.endpointRoutingHint")})]}),e.jsx(st,{children:e.jsxs("form",{id:"endpoint-form",onSubmit:d,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ye,{children:[n("modelManagement.endpointId")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(fe,{value:p.id,onChange:c=>h(v=>({...v,id:c.target.value})),placeholder:n("modelManagement.endpointIdPlaceholder"),disabled:!!t,required:!0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:n("modelManagement.endpointIdHint")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ye,{children:[n("modelManagement.endpointLabel")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(fe,{value:p.label,onChange:c=>h(v=>({...v,label:c.target.value})),placeholder:n("modelManagement.endpointLabelPlaceholder"),required:!0})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ye,{children:[n("modelManagement.endpointPaths")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsxs(q,{type:"button",variant:"ghost",size:"sm",onClick:y,children:[e.jsx(wt,{className:"mr-1 h-3 w-3"}),n("modelManagement.addPath")]})]}),e.jsx("div",{className:"space-y-3",children:p.paths.map((c,v)=>e.jsxs("div",{className:"space-y-2 rounded-xl border border-transparent bg-card p-3 shadow-[var(--surface-shadow)]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(fe,{value:c.path,onChange:N=>u(v,"path",N.target.value),placeholder:n("modelManagement.endpointPathPlaceholder"),required:!0}),e.jsxs(Qe,{value:c.protocol,onValueChange:N=>u(v,"protocol",N),children:[e.jsx(Ge,{children:e.jsx(We,{})}),e.jsx(Je,{children:hs.map(N=>e.jsx(Fe,{value:N,children:n(N==="anthropic"?"modelManagement.protocolAnthropic":N==="openai-auto"?"modelManagement.protocolOpenAI":N==="openai-chat"?"modelManagement.protocolOpenAIChat":"modelManagement.protocolOpenAIResponses")},N))})]})]}),p.paths.length>1?e.jsx(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>l(v),className:"text-destructive",children:e.jsx(ft,{className:"h-4 w-4"})}):null]}),e.jsxs("div",{className:"space-y-1 text-xs text-muted-foreground",children:[v===0?e.jsx("p",{children:n("modelManagement.endpointPathHint")}):null,e.jsx("p",{children:n(`modelManagement.protocolHints.${c.protocol}`)})]})]},`${c.protocol}-${v}`))}),b?e.jsx("p",{className:"text-xs text-destructive",children:b}):null]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(rt,{id:"endpoint-enabled",checked:p.enabled,onCheckedChange:c=>h(v=>({...v,enabled:c}))}),e.jsx(ye,{htmlFor:"endpoint-enabled",children:n("modelManagement.endpointEnabled")})]}),t?null:e.jsx("div",{className:"rounded-xl bg-accent p-4",children:e.jsx("p",{className:"text-sm text-primary",children:n("modelManagement.endpointRoutingHint")})})]})}),e.jsxs(at,{children:[e.jsx(q,{variant:"outline",onClick:i,disabled:w,children:n("common.cancel")}),e.jsx(q,{type:"submit",form:"endpoint-form",disabled:w,children:n(w?"common.saving":t?"common.save":"common.create")})]})]})})}function gs({open:a,provider:t,onClose:i,onEdit:s}){const{t:n}=W();return t?e.jsx(Xe,{open:a,onOpenChange:p=>!p&&i(),children:e.jsxs(Ye,{className:"max-w-md",children:[e.jsxs(Ze,{children:[e.jsx(et,{children:n("providers.noModelDialog.title")}),e.jsx(tt,{children:n("providers.noModelDialog.subtitle",{name:t.label||t.id})})]}),e.jsxs(st,{className:"space-y-4",children:[e.jsx("div",{className:"rounded-xl bg-accent p-4 text-sm text-primary",children:n("providers.noModelDialog.description")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:n("providers.noModelDialog.hint")})]}),e.jsxs(at,{children:[e.jsx(q,{variant:"outline",onClick:i,children:n("common.actions.close")}),e.jsx(q,{onClick:()=>s(t),children:n("providers.noModelDialog.primary")})]})]})}):null}function fs({dialog:a,currentRoutes:t,onConfirm:i,onClose:s}){const{t:n}=W();if(!a)return null;const{endpoint:p,preset:h}=a,k=h.modelRoutes??{},g={};for(const b of t){const c=b.source.trim(),v=b.target.trim();c&&v&&(g[c]=v)}const y=new Set([...Object.keys(g),...Object.keys(k)]),l=[],u=[],d=[];for(const b of y){const c=b in g,v=b in k;v&&!c?l.push([b,k[b]]):c&&!v?u.push([b,g[b]]):c&&v&&g[b]!==k[b]&&d.push([b,g[b],k[b]])}const w=l.length>0||u.length>0||d.length>0;return e.jsx(Xe,{open:!0,onOpenChange:b=>!b&&s(),children:e.jsxs(Ye,{className:"max-w-2xl",children:[e.jsxs(Ze,{children:[e.jsx(et,{children:n("modelManagement.presets.diffTitle")}),e.jsx(tt,{children:n("modelManagement.presets.diffDescription",{name:h.name})})]}),e.jsx(st,{children:w?e.jsxs("div",{className:"max-h-80 space-y-2 rounded-xl bg-secondary/50 p-3 text-sm",children:[l.map(([b,c])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-success-bg px-2 py-1.5 text-success",children:[e.jsx(oe,{variant:"outline",className:"border-success/30 text-xs",children:n("modelManagement.presets.diffAdded")}),e.jsx("span",{className:"truncate",children:b}),e.jsx(ge,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:c})]},`add-${b}`)),u.map(([b,c])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-error-bg px-2 py-1.5 text-error",children:[e.jsx(oe,{variant:"outline",className:"border-error/30 text-xs",children:n("modelManagement.presets.diffRemoved")}),e.jsx("span",{className:"truncate",children:b}),e.jsx(ge,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:c})]},`rm-${b}`)),d.map(([b,c,v])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-warning-bg px-2 py-1.5 text-warning",children:[e.jsx(oe,{variant:"outline",className:"border-warning/30 text-xs",children:n("modelManagement.presets.diffChanged")}),e.jsx("span",{className:"truncate",children:b}),e.jsx(ge,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate line-through opacity-60",children:c}),e.jsx(ge,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:v})]},`chg-${b}`))]}):e.jsx("p",{className:"rounded-xl bg-secondary/50 py-8 text-center text-sm text-muted-foreground",children:n("modelManagement.presets.diffEmpty")})}),e.jsxs(at,{children:[e.jsx(q,{variant:"outline",onClick:s,children:n("common.cancel")}),e.jsx(q,{onClick:()=>i(p,h),disabled:!w,children:n("modelManagement.presets.diffConfirm")})]})]})})}function bs({open:a,mode:t,provider:i,existingProviderIds:s,onClose:n,onSubmit:p,testResult:h,testing:k,onTest:g,onDelete:y}){const{t:l}=W(),u=Xt({mode:t,provider:i,existingProviderIds:s}),{form:d,errors:w,advancedOpen:b,providerIdRef:c}=u,[v,N]=f.useState(!1),[C,R]=f.useState(null),[Z,K]=f.useState("basics"),T=f.useRef(null),j=f.useRef(null);f.useEffect(()=>{a&&(u.resetForm(),R(null),N(!1),K("basics"))},[a,i,t,u.resetForm]);const D=f.useRef(n);D.current=n,f.useEffect(()=>{if(!a)return;const L=Y=>{Y.key==="Escape"&&(document.querySelector('[role="dialog"][data-state="open"], [role="listbox"][data-state="open"], [data-radix-popper-content-wrapper]')||D.current())};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[a]),f.useEffect(()=>{if(a){if(t==="create"&&c.current){c.current.focus();return}j.current&&j.current.focus()}},[a,t]);const B=t==="create",z=f.useMemo(()=>d.models.filter(L=>L.id.trim().length>0),[d.models]),V=f.useMemo(()=>{var L;return((L=lt.find(Y=>Y.value===d.type))==null?void 0:L.label)??"Custom"},[d.type]),ae=d.label.trim()||d.id.trim()||l("providers.drawer.summary.untitled"),A=f.useMemo(()=>[{label:l("providers.drawer.summary.type"),value:V},{label:l("providers.drawer.summary.auth"),value:Yt(d.type,d.authMode,l)},{label:l("providers.drawer.summary.models"),value:z.length.toLocaleString()}],[z.length,d.authMode,d.type,V,l]),ie=async()=>{R(null);const L=u.validateErrors();if(Object.keys(L).length>0){L.baseUrl||L.id||L.extraHeaders?(K("basics"),L.extraHeaders&&u.setAdvancedOpen(!0)):L.models&&K("models");return}N(!0);try{const Y=u.serialize();await p(Y)}catch(Y){R(l("providers.drawer.toast.saveFailure",{message:xe(Y).message})),N(!1);return}N(!1),n()};if(!a)return null;const X=Oe.findIndex(L=>L.id===Z),M=X===Oe.length-1,I=d.id.trim(),H=I.length>0&&(t==="edit"||!s.includes(I)),Ce=d.baseUrl.trim();let re=Ce.length>0;if(re)try{new URL(Ce)}catch{re=!1}let Se=!d.defaultModel||d.models.some(L=>L.id===d.defaultModel);if(Se){const L=new Set;Se=!d.models.some(Y=>{const ce=Y.id.trim();return ce.length===0||L.has(ce)?!0:(L.add(ce),!1)})}const me={basics:H&&re,models:Se},pe=Oe.map((L,Y)=>{let ce;return Y===X?ce="current":Y<X?ce=me[L.id]?"complete":"error":ce="upcoming",{id:L.id,label:l(L.labelKey),status:ce}}),he=L=>{K(L)},be=()=>{X<Oe.length-1&&K(Oe[X+1].id)},we=()=>{X>0&&K(Oe[X-1].id)},ke={form:d,errors:w,isCreate:B,advancedOpen:b,onAdvancedOpenChange:u.setAdvancedOpen,idInputRef:c,onProviderIdChange:u.handleProviderIdChange,onFieldChange:u.handleFieldChange,onTypeChange:u.handleTypeChange,onAuthModeChange:u.handleAuthModeChange,onNonStreamViaStreamChange:u.handleProviderNonStreamViaStreamChange,onUseAbsoluteUrlChange:u.handleUseAbsoluteUrlChange,onAddHeader:u.handleAddHeader,onRemoveHeader:u.handleRemoveHeader,onHeaderChange:u.handleHeaderChange,onModelIdChange:u.handleModelIdChange,onModelChange:u.handleModelChange,onAddModel:u.handleAddModel,onRemoveModel:u.handleRemoveModel,onModelNonStreamViaStreamChange:u.handleModelNonStreamViaStreamChange,onSetDefaultModel:u.handleSetDefaultModel,testVerification:g?{available:t==="edit",testing:k??!1,result:h??null,onTest:g}:void 0};return e.jsxs("div",{className:"fixed inset-0 z-50 flex",children:[e.jsx("div",{className:"flex-1 bg-background/95","aria-hidden":"true"}),e.jsxs("aside",{ref:T,role:"dialog","aria-modal":"true","aria-labelledby":"provider-drawer-title","aria-describedby":"provider-drawer-desc",className:"flex h-full min-h-0 w-full max-w-5xl flex-col border-l border-border bg-background shadow-[var(--surface-shadow-lg)]",children:[e.jsxs("header",{className:"border-b border-border bg-secondary px-6 py-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"inline-flex rounded-full border border-primary/20 bg-primary/10 px-3 py-1 text-[11px] font-medium uppercase tracking-[0.18em] text-primary",children:l(B?"providers.drawer.quickStart":"providers.drawer.editTitle")}),e.jsxs("div",{children:[e.jsx("h2",{id:"provider-drawer-title",className:"text-lg font-semibold tracking-[-0.02em]",children:l(B?"providers.drawer.createTitle":"providers.drawer.editTitle")}),e.jsx("p",{id:"provider-drawer-desc",className:"text-sm text-muted-foreground",children:l("providers.drawer.description")})]})]}),e.jsx(q,{type:"button",ref:j,variant:"outline",onClick:n,className:"bg-card",children:l("common.actions.close")})]}),e.jsx("div",{className:"mt-4 grid gap-3 md:grid-cols-3",children:A.map(L=>e.jsxs("div",{className:"rounded-xl border border-transparent bg-card px-4 py-3 shadow-[var(--surface-shadow)]",children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground",children:L.label}),e.jsx("p",{className:"mt-2 text-sm font-semibold text-foreground",children:L.value})]},L.label))})]}),e.jsxs("div",{className:"grid min-h-0 flex-1 overflow-hidden xl:grid-cols-[minmax(0,1fr)_280px]",children:[e.jsxs("div",{className:"min-h-0 overflow-y-auto px-6 py-5 pb-10",children:[e.jsx(Zt,{steps:pe,current:Z,onSelect:he,className:"mb-6"}),Z==="basics"?e.jsx(es,{...ke}):null,Z==="models"?e.jsx(ts,{...ke}):null]}),e.jsx("aside",{className:"hidden min-h-0 overflow-y-auto border-l border-border/45 bg-secondary/40 px-5 py-5 xl:block",children:e.jsxs("div",{className:"sticky top-0 space-y-5",children:[e.jsxs("div",{className:"rounded-xl border border-transparent bg-card p-4 shadow-[var(--surface-shadow)]",children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground",children:l("providers.drawer.formSummary")}),e.jsx("p",{className:"mt-2 text-base font-semibold",children:ae}),e.jsx("div",{className:"mt-4 space-y-3 text-sm",children:A.map(L=>e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("span",{className:"text-muted-foreground",children:L.label}),e.jsx("span",{className:"text-right font-medium",children:L.value})]},L.label))})]}),e.jsxs("div",{className:"rounded-xl border border-transparent bg-card p-4 shadow-[var(--surface-shadow)]",children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-[0.16em] text-muted-foreground",children:l("providers.drawer.sections.checklist")}),e.jsxs("ul",{className:"mt-3 space-y-2 text-sm text-muted-foreground",children:[e.jsx("li",{children:l("providers.drawer.hints.checkUrl")}),e.jsx("li",{children:l("providers.drawer.hints.checkAuth")}),e.jsx("li",{children:l("providers.drawer.hints.checkModels")})]})]}),b&&e.jsxs("div",{className:"rounded-xl bg-accent p-4 text-sm text-foreground",children:[e.jsx("p",{className:"font-medium text-primary",children:l("providers.drawer.hints.advancedTitle")}),e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:l("providers.drawer.hints.advancedBody")})]})]})})]}),e.jsxs("footer",{className:"flex items-center justify-between gap-3 border-t border-border bg-secondary px-6 py-4 text-sm",children:[e.jsxs("div",{className:"flex flex-col gap-1 text-xs",children:[!B&&y?e.jsx("button",{type:"button",onClick:y,disabled:v,className:"text-muted-foreground underline-offset-2 hover:text-destructive hover:underline disabled:opacity-50",children:l("providers.actions.delete")}):null,C?e.jsx("span",{className:"text-destructive","aria-live":"polite",children:C}):null]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(q,{type:"button",variant:"outline",onClick:n,disabled:v,className:"bg-card",children:l("common.actions.cancel")}),e.jsx(q,{type:"button",variant:"outline",onClick:we,disabled:v||X===0,className:"bg-card",children:l("common.actions.previous")}),M?null:e.jsx(q,{type:"button",onClick:be,disabled:v,children:l("common.actions.next")}),e.jsx(q,{type:"button",onClick:ie,disabled:v,children:l(v?"common.actions.saving":"common.actions.save")})]})]})]})]})}function vs({provider:a,defaultModel:t,modelCount:i,requests24h:s,avgLatencyMs:n,routeCount:p,testResult:h,onTest:k,onEdit:g}){var b;const{t:y}=W(),l=a.label||a.id,u=l.slice(0,1).toUpperCase()||"?",d=((b=lt.find(c=>c.value===(a.type??"custom")))==null?void 0:b.label)??a.type??"custom",w=h?h.ok?"ok":"fail":"untested";return e.jsxs("div",{"data-testid":"provider-card",className:"flex flex-col rounded-lg border border-border bg-card p-4 transition-colors hover:border-primary/40",children:[e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-secondary text-sm font-semibold text-muted-foreground",children:u}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"truncate text-[13px] font-semibold text-foreground",title:l,children:l}),e.jsx(oe,{variant:"outline",className:"shrink-0 rounded-full px-2 py-0 text-[10px] font-normal text-muted-foreground",children:d})]}),e.jsx("code",{className:"mt-0.5 block truncate font-mono text-[10.5px] text-muted-foreground",title:a.baseUrl,children:a.baseUrl})]}),e.jsx(js,{state:w})]}),e.jsxs("div",{className:"mt-3 grid grid-cols-3 gap-2",children:[e.jsx(ot,{label:y("providers.card.statModels"),value:i>0?String(i):"—"}),e.jsx(ot,{label:y("providers.card.statRequests24h"),value:s!=null?s.toLocaleString():"—"}),e.jsx(ot,{label:y("providers.card.statAvgLatency"),value:is(n,y("common.units.ms"),{maximumFractionDigits:0})})]}),e.jsxs("div",{className:"mt-2.5 flex items-center gap-1.5 text-[11px] text-muted-foreground",children:[e.jsx("span",{className:"shrink-0",children:y("providers.card.defaultModelLabel")}),t?e.jsx("code",{className:"min-w-0 truncate rounded bg-secondary px-1.5 py-0.5 font-mono text-[10.5px] text-foreground",title:t,children:t}):e.jsx("span",{children:"—"})]}),e.jsxs("div",{className:"mt-3 flex items-center gap-1.5 border-t border-border pt-2.5 text-[10.5px] text-muted-foreground",children:[e.jsx("span",{className:"truncate",children:y("providers.card.routeCount",{count:p})}),e.jsxs("div",{className:"ml-auto flex shrink-0 gap-1.5",children:[e.jsx(q,{variant:"outline",size:"sm",className:"h-7 px-2.5 text-[11px]",onClick:k,children:y("providers.actions.test")}),e.jsx(q,{variant:"outline",size:"sm",className:"h-7 px-2.5 text-[11px]",onClick:g,children:y("providers.actions.edit")})]})]})]})}function ot({label:a,value:t}){return e.jsxs("div",{className:"rounded bg-secondary/60 px-2.5 py-2",children:[e.jsx("div",{className:"text-[10px] text-muted-foreground",children:a}),e.jsx("div",{className:"metric-number mt-0.5 truncate text-[13px] font-semibold text-foreground",children:t})]})}function js({state:a}){const{t}=W();return a==="ok"?e.jsx(oe,{variant:"success",className:"shrink-0 rounded-full px-1.5 py-0 text-[10px]",children:t("providers.card.health.ok")}):a==="fail"?e.jsx(oe,{variant:"destructive",className:"shrink-0 rounded-full px-1.5 py-0 text-[10px]",children:t("providers.card.health.fail")}):e.jsx(oe,{variant:"secondary",className:"shrink-0 rounded-full px-1.5 py-0 text-[10px]",children:t("providers.card.health.untested")})}function ys({providersLength:a,filteredProviders:t,testResults:i,providerSearch:s,providerTypeFilter:n,configPending:p,defaultLabels:h,config:k,customEndpoints:g,onTest:y,onEdit:l,onProviderSearchChange:u,onProviderTypeChange:d,onResetFilters:w}){const{t:b}=W(),[c,v]=f.useState("usage"),N=bt(Ee.stats.model(1,50),{url:"/api/stats/model",method:"GET",params:{days:1,limit:50}},{retry:!1}),{requestsByProvider:C,latencyByProvider:R}=f.useMemo(()=>{const T=new Map,j=new Map,D=new Map;for(const z of N.data??[]){const V=z.provider;T.set(V,(T.get(V)??0)+z.requests),z.avgLatencyMs>0&&(j.set(V,(j.get(V)??0)+z.avgLatencyMs*z.requests),D.set(V,(D.get(V)??0)+z.requests))}const B=new Map;for(const z of T.keys()){const V=D.get(z)??0;B.set(z,V>0?(j.get(z)??0)/V:null)}return{requestsByProvider:T,latencyByProvider:B}},[N.data]),Z=f.useMemo(()=>{const T=new Map;for(const j of t)T.set(j.id,ss(k,g,j.id).length);return T},[k,g,t]),K=f.useMemo(()=>{const T=[...t],j=(D,B)=>(D.label||D.id).localeCompare(B.label||B.id);return c==="usage"&&N.isSuccess?T.sort((D,B)=>(C.get(B.id)??0)-(C.get(D.id)??0)||j(D,B)):T.sort(j),T},[t,c,N.isSuccess,C]);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(He,{className:"overflow-hidden",children:e.jsx(qe,{className:"p-0",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2 bg-secondary/50 px-4 py-3",children:[e.jsx(fe,{value:s,onChange:T=>u(T.target.value),placeholder:b("providers.filters.searchPlaceholder"),className:"h-9 w-full sm:w-64"}),e.jsxs(Qe,{value:n,onValueChange:d,children:[e.jsx(Ge,{className:"h-9 w-[130px] text-xs",children:e.jsx(We,{})}),e.jsxs(Je,{children:[e.jsx(Fe,{value:"all",children:b("providers.filters.typeAll")}),lt.map(T=>e.jsx(Fe,{value:T.value??"custom",children:T.label},T.value??"custom"))]})]}),e.jsxs(Qe,{value:c,onValueChange:T=>v(T),children:[e.jsx(Ge,{className:"h-9 w-[104px] text-xs","aria-label":b("providers.list.sortLabel"),children:e.jsx(We,{})}),e.jsxs(Je,{children:[e.jsx(Fe,{value:"usage",children:b("providers.list.sortUsage")}),e.jsx(Fe,{value:"name",children:b("providers.list.sortName")})]})]}),e.jsx(oe,{variant:"secondary",className:"shrink-0 rounded-full px-2.5 py-1 text-[11px]",children:t.length}),e.jsx(q,{variant:"ghost",size:"sm",onClick:w,disabled:!s.trim()&&n==="all",className:"h-9 shrink-0 rounded-full px-2.5 text-xs",children:b("common.actions.reset")})]})})}),p?e.jsx("div",{className:"flex min-h-[160px] items-center justify-center text-sm text-muted-foreground",children:b("common.loading")}):a===0?e.jsx(it,{compact:!0,title:b("providers.emptyState"),description:e.jsxs(e.Fragment,{children:[e.jsx("p",{children:b("providers.emptyStateSub")}),e.jsx("p",{className:"mt-1",children:b("workbench.list.emptyHint")})]})}):t.length===0?e.jsx(it,{compact:!0,title:b("providers.emptyFiltered")}):e.jsx("div",{className:"grid gap-3.5 sm:grid-cols-2 xl:grid-cols-3",children:K.map(T=>{var j;return e.jsx(vs,{provider:T,defaultModel:h.get(T.id),modelCount:((j=T.models)==null?void 0:j.length)??0,requests24h:N.isSuccess?C.get(T.id)??0:null,avgLatencyMs:N.isSuccess?R.get(T.id)??null:null,routeCount:Z.get(T.id)??0,testResult:i[T.id]??null,onTest:()=>y(T),onEdit:()=>l(T)},T.id)})})]})}function Ns({routing:a,endpoint:t,tabInfo:i,config:s,customEndpoints:n}){var v,N;const{t:p}=W(),h=a.routesByEndpoint[t]||[],k=a.savingRouteFor===t,g=a.savingCompatibilityPolicy,y=a.writingEndpoint===t,l=((v=i==null?void 0:i.protocols)==null?void 0:v.some(C=>C.startsWith("openai")))??t==="openai",u=as(t,s,n),d=l?(u==null?void 0:u.enabled)??!1:!1,b=((N=i==null?void 0:i.protocols)==null?void 0:N.includes("anthropic"))??t==="anthropic"?vt:jt,c=new Set(h.map(C=>C.source.trim()).filter(Boolean));return e.jsx(He,{"data-testid":"endpoint-config-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(qe,{className:"space-y-3 p-4",children:[e.jsx("h3",{className:"text-[12.5px] font-semibold",children:p("workbench.endpointConfig.title")}),l?e.jsxs("div",{className:"flex items-center justify-between gap-2 border border-border/60 bg-secondary/30 px-2.5 py-2",children:[e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsx(ye,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:p("modelManagement.openaiCompatibility.toggleLabel")}),e.jsx("p",{className:"text-[10.5px] text-muted-foreground",children:p(d?"modelManagement.openaiCompatibility.enabledHint":"modelManagement.openaiCompatibility.disabledHint")})]}),e.jsx(rt,{"data-testid":"compatibility-toggle",checked:d,onCheckedChange:C=>void a.handleCompatibilityEnabledChange(t,C),disabled:g||y,"aria-label":p("modelManagement.openaiCompatibility.toggleLabel")})]}):null,e.jsxs("div",{children:[e.jsx("p",{className:"mb-1.5 text-[11px] text-muted-foreground",children:p("settings.routing.suggested")}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:b.map(C=>{const R=c.has(C);return e.jsx("button",{"data-testid":"suggestion-chip",type:"button",onClick:()=>a.handleAddSuggestion(t,C),disabled:k||R,className:Ne("h-6 border px-2 text-[10.5px] transition-colors",R?"border-border bg-secondary/40 text-muted-foreground/50":"border-border bg-card hover:border-primary hover:text-primary"),children:C},`${t}-${C}`)})})]})]})})}const gt=6;function _e({value:a,onChange:t,options:i,disabled:s,placeholder:n,ariaLabel:p}){const{t:h}=W(),k=f.useId(),[g,y]=f.useState(!1),[l,u]=f.useState(""),d=f.useRef(null),w=f.useRef(!1),[b,c]=zt(Ut.modelManagement.recentRouteTargets,[]),v=f.useMemo(()=>{const j=new Map;for(const D of i)j.set(D.value,D);return j},[i]),N=(j,D)=>D?[j.label,j.value,j.providerId??"",j.providerLabel??"",j.modelId??"",j.modelLabel??""].join(" ").toLowerCase().includes(D):!0,C=f.useMemo(()=>{const j=l.trim().toLowerCase(),D=i.filter(A=>N(A,j)),B=b.map(A=>v.get(A)??(j?void 0:{value:A,label:A,kind:"custom"})).filter(A=>!!A).filter(A=>N(A,j)).slice(0,gt),z=[];B.length>0&&z.push({key:"recent",label:h("modelManagement.targetPicker.recent"),options:B});const V=new Map,ae=[];for(const A of D){if(A.kind==="custom"||!A.providerId){ae.push(A);continue}const ie=`provider:${A.providerId}`,X=V.get(ie);X?X.options.push(A):V.set(ie,{key:ie,label:A.providerLabel??A.providerId,options:[A]})}return z.push(...V.values()),ae.length>0&&z.push({key:"custom",label:h("modelManagement.targetPicker.custom"),options:ae,muted:!0}),z},[v,i,b,l,h]),R=C.reduce((j,D)=>j+D.options.length,0),Z=j=>{t(j),c(D=>[j,...D.filter(B=>B!==j)].slice(0,gt)),u(""),w.current=!0,typeof document<"u"&&document.activeElement instanceof HTMLElement&&document.activeElement.blur(),y(!1),typeof window<"u"?window.requestAnimationFrame(()=>{w.current=!1}):w.current=!1},K=j=>j.kind==="passthrough"?h("modelManagement.targetPicker.passthrough"):j.kind==="custom"?h("modelManagement.targetPicker.customValue"):h("modelManagement.targetPicker.model"),T=j=>j.kind==="passthrough"||j.kind==="custom"?j.label:j.modelLabel??j.label;return e.jsxs(ds,{open:g,onOpenChange:j=>{j&&w.current||(y(j),j&&u(""))},children:[e.jsx(cs,{asChild:!0,children:e.jsx(fe,{value:a,onChange:j=>{t(j.target.value),u(j.target.value),g||y(!0)},onFocus:()=>{u(""),y(!0)},onClick:()=>{g||y(!0)},placeholder:n,disabled:s,autoComplete:"off",role:"combobox","aria-label":p,"aria-expanded":g,"aria-controls":k,"aria-autocomplete":"list"})}),e.jsxs(us,{className:"flex max-h-[min(28rem,var(--radix-popover-content-available-height))] flex-col overflow-hidden rounded-xl border border-[color:var(--surface-border)] bg-popover/96 p-0 shadow-[var(--surface-shadow-lg)]",style:{width:"max(var(--radix-popover-trigger-width), 360px)"},align:"start",onOpenAutoFocus:j=>{var D;j.preventDefault(),(D=d.current)==null||D.focus()},onCloseAutoFocus:j=>{j.preventDefault()},children:[e.jsxs("div",{className:"space-y-2 border-b border-border/70 px-3 py-3",children:[e.jsx(fe,{ref:d,value:l,onChange:j=>u(j.target.value),placeholder:h("modelManagement.targetPicker.searchPlaceholder"),className:"h-9",autoComplete:"off"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:l.trim()?h("modelManagement.targetPicker.matchCount",{count:R}):h("modelManagement.targetPicker.helper")})]}),R===0?e.jsx("div",{className:"px-3 py-4 text-center text-xs text-muted-foreground",children:h("common.noMatches")}):e.jsx("div",{id:k,role:"listbox",className:"min-h-0 flex-1 overflow-y-auto p-1.5",children:C.map(j=>e.jsxs("div",{className:"py-1",children:[e.jsxs("div",{className:Ne("sticky top-0 z-10 flex items-center justify-between bg-popover/95 px-2 py-1 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",j.muted&&"opacity-80"),children:[e.jsx("span",{className:"truncate",children:j.label}),e.jsx("span",{children:j.options.length})]}),e.jsx("div",{className:"space-y-1",children:j.options.map(D=>e.jsxs("button",{type:"button",role:"option","aria-selected":D.value===a.trim(),className:Ne("flex w-full min-w-0 items-center gap-2 rounded-lg px-3 py-2 text-left text-sm transition-colors hover:bg-accent/80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",D.value===a.trim()&&"bg-accent/90 text-accent-foreground"),onMouseDown:B=>{B.preventDefault()},onClick:()=>Z(D.value),children:[e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate font-medium",children:T(D)}),e.jsx("span",{className:"block truncate text-xs text-muted-foreground",children:D.value})]}),e.jsxs("span",{className:"flex shrink-0 items-center gap-1",children:[D.isDefault?e.jsx(oe,{variant:"secondary",className:"text-[10px]",children:h("modelManagement.targetPicker.default")}):null,e.jsx(oe,{variant:D.kind==="passthrough"?"outline":"secondary",className:"text-[10px]",children:K(D)})]})]},`${j.key}-${D.value}`))})]},j.key))})]})]})}function ws({routing:a,endpoint:t}){const{t:i}=W(),s=a.defaultsByEndpoint[t]??null,n=a.isDefaultsDirtyByEndpoint[t]??!1,p=a.savingDefaultsFor===t,h=a.writingEndpoint===t,k=a.providerModelOptions;return e.jsx(He,{"data-testid":"routing-defaults-card",className:"border-primary/40 bg-primary/5 shadow-none",children:e.jsxs(qe,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-[13px] font-semibold text-primary",children:i("workbench.defaults.title")}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:i("workbench.defaults.cardSubtitle")})]}),e.jsxs(ls,{summary:e.jsx("span",{className:"text-[11px] font-medium text-muted-foreground",children:i("workbench.defaults.moreLabel")}),summaryClassName:"px-2 py-1",contentClassName:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ye,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:i("workbench.defaults.reasoningLabel")}),e.jsx(_e,{value:(s==null?void 0:s.reasoning)??"",onChange:g=>a.handleDefaultsChange(t,"reasoning",g),options:k,disabled:p,ariaLabel:i("workbench.defaults.reasoningLabel"),placeholder:i("workbench.defaults.targetPlaceholder")})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ye,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:i("workbench.defaults.backgroundLabel")}),e.jsx(_e,{value:(s==null?void 0:s.background)??"",onChange:g=>a.handleDefaultsChange(t,"background",g),options:k,disabled:p,ariaLabel:i("workbench.defaults.backgroundLabel"),placeholder:i("workbench.defaults.targetPlaceholder")})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ye,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:i("workbench.defaults.thresholdLabel")}),e.jsx(fe,{type:"number",min:1,value:(s==null?void 0:s.longContextThreshold)||"",onChange:g=>{const y=Number.parseInt(g.target.value,10);a.handleDefaultsChange(t,"longContextThreshold",Number.isFinite(y)?y:0)},disabled:p,className:"md:w-56"})]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"border border-border bg-card px-2.5 py-2 font-mono text-xs",children:"*"}),e.jsx(ge,{className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground","aria-hidden":!0}),e.jsx("div",{"data-testid":"default-target",className:"min-w-[180px] flex-1",children:e.jsx(_e,{value:(s==null?void 0:s.completion)??"",onChange:g=>a.handleDefaultsChange(t,"completion",g),options:k,disabled:p,ariaLabel:i("workbench.defaults.completionLabel"),placeholder:i("workbench.defaults.targetPlaceholder")})}),e.jsxs(q,{size:"sm","data-testid":"save-defaults",onClick:()=>void a.handleSaveDefaults(t),disabled:p||!n||h,className:"relative",children:[i(p?"common.actions.saving":"workbench.defaults.save"),n?e.jsx("span",{className:"absolute -right-1 -top-1 h-2 w-2 rounded-full bg-warning"}):null]})]})]})})}const ks={anthropic:"/anthropic",openai:"/openai"};function Cs(a){var t;return(t=a.paths)!=null&&t.length?a.paths[0].path:a.path?a.path:`/${a.id}`}function Ss({tabs:a,customEndpoints:t,routeCounts:i,selectedEndpointId:s,onSelect:n,onCreate:p,onEditEndpoint:h,onDeleteEndpoint:k}){const{t:g}=W(),y=a.map(l=>{const u=t.find(w=>w.id===l.key);if(!u)return{key:l.key,label:l.label,path:ks[l.key]??`/${l.key}`,protocols:l.protocols??[],enabled:!0};const d=u.paths??(u.path?[{path:u.path,protocol:u.protocol??"anthropic"}]:[]);return{key:l.key,label:u.label||u.id,path:Cs(u),protocols:[...new Set(d.map(w=>w.protocol))],enabled:u.enabled!==!1,custom:u}});return e.jsxs("section",{"data-testid":"endpoint-rail",className:"flex gap-2 overflow-x-auto border border-border bg-card shadow-[var(--surface-shadow)] lg:h-full lg:flex-col lg:overflow-visible",children:[e.jsxs("div",{className:"hidden shrink-0 border-b border-border/60 px-3 py-2.5 lg:block",children:[e.jsx("h2",{className:"text-[12.5px] font-semibold",children:g("workbench.endpointRail.title")}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:g("workbench.endpointRail.subtitle")})]}),e.jsxs("div",{className:"flex gap-1.5 p-2 lg:flex-col lg:gap-1",children:[y.map(l=>{const u=l.key===s,d=i[l.key]??0,w=!l.enabled;return e.jsxs("div",{"data-testid":"endpoint-row",className:Ne("flex shrink-0 items-stretch border transition-colors lg:shrink",u?"border-primary/40 bg-primary/5":"border-border bg-card hover:bg-accent",w?"opacity-60":""),children:[e.jsxs("button",{type:"button",onClick:()=>n(l.key),className:"flex min-w-0 flex-1 items-center gap-2 px-2.5 py-2 text-left",children:[e.jsx("span",{className:Ne("h-1.5 w-1.5 shrink-0 rounded-full",u?"bg-primary":"bg-muted-foreground/40"),"aria-hidden":!0}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-[11.5px] font-medium",title:l.label,children:l.label}),e.jsxs("span",{className:"mt-0.5 flex items-center gap-1.5 text-[10px] text-muted-foreground",children:[e.jsx("span",{className:"truncate font-mono",children:l.path}),e.jsx("span",{"aria-hidden":!0,children:"·"}),e.jsx("span",{className:"shrink-0 tabular-nums",children:g("workbench.endpointRail.ruleCount",{count:d})})]})]})]}),l.custom?e.jsxs("div",{className:"flex items-center gap-0.5 pr-1",children:[e.jsx("button",{type:"button",onClick:()=>h(l.custom),className:"flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-foreground",title:g("common.edit"),"aria-label":g("common.edit"),children:e.jsx(kt,{className:"h-3 w-3","aria-hidden":!0})}),l.custom.deletable!==!1?e.jsx("button",{type:"button",onClick:()=>k(l.custom),className:"flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-destructive",title:g("common.delete"),"aria-label":g("common.delete"),children:e.jsx(Ct,{className:"h-3 w-3","aria-hidden":!0})}):null]}):null]},l.key)}),e.jsxs("button",{type:"button","data-testid":"create-endpoint",onClick:p,className:"flex shrink-0 items-center justify-center border border-dashed border-border px-3 py-2 text-[11.5px] text-muted-foreground transition-colors hover:border-primary hover:text-primary lg:shrink",children:["+ ",g("workbench.endpointRail.add")]})]})]})}function Ms({endpointPath:a,defaultTarget:t}){const{t:i}=W();return e.jsxs("section",{"data-testid":"routing-flow-banner",className:"flex flex-wrap items-center gap-x-3 gap-y-2 border border-border bg-card px-4 py-3 shadow-[var(--surface-shadow)]",children:[e.jsx("span",{className:"text-[10.5px] font-semibold uppercase tracking-[0.06em] text-muted-foreground",children:i("workbench.flow.title")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[e.jsx("span",{className:"border border-border bg-secondary px-2.5 py-1 font-mono text-[11px]",children:i("workbench.flow.clientStep")}),e.jsx(ge,{className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0}),e.jsxs("span",{className:"border border-border bg-secondary px-2.5 py-1 text-[11px]",children:[i("workbench.flow.endpointStep")," ",e.jsx("span",{className:"font-mono",children:a})]}),e.jsx(ge,{className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0}),e.jsx("span",{className:"border border-primary bg-primary/5 px-2.5 py-1 text-[11px] font-semibold text-primary",children:i("workbench.flow.matchStep")}),e.jsx(ge,{className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0}),e.jsx("span",{className:"border border-border bg-secondary px-2.5 py-1 font-mono text-[11px]",children:t||i("workbench.flow.fallbackNote")})]})]})}function Ps({routing:a,endpoint:t,onRequestDeletePreset:i}){var u,d;const{t:s}=W(),n=a.presetsByEndpoint[t]??[],p=a.presetNameByEndpoint[t]??"",h=a.presetErrorByEndpoint[t],k=a.savingPresetFor===t,g=((u=a.applyingPreset)==null?void 0:u.endpoint)===t?a.applyingPreset.name:null,y=((d=a.deletingPreset)==null?void 0:d.endpoint)===t?a.deletingPreset.name:null,l=a.writingEndpoint===t;return e.jsx(He,{"data-testid":"routing-presets-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(qe,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h3",{className:"text-[13px] font-semibold",children:s("modelManagement.presets.title")}),e.jsx(q,{variant:"outline",size:"sm","data-testid":"save-preset",onClick:()=>void a.handleSavePreset(t),disabled:k||l,children:s(k?"modelManagement.presets.saving":"modelManagement.presets.save")})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:s("modelManagement.presets.description")}),e.jsx(fe,{"data-testid":"preset-name-input",value:p,onChange:w=>a.handlePresetNameChange(t,w.target.value),placeholder:s("modelManagement.presets.namePlaceholder"),disabled:k,className:"h-8 text-xs"}),h?e.jsx("p",{className:"text-xs text-destructive",children:h}):null,n.length===0?e.jsx("p",{className:"py-2 text-center text-[11px] text-muted-foreground",children:s("modelManagement.presets.empty")}):e.jsx(Vt,{children:e.jsx("div",{className:"grid grid-cols-1 gap-1.5 sm:grid-cols-2",children:n.map(w=>{const b=g===w.name,c=y===w.name,v=Object.entries(w.modelRoutes??{}),N=v.length;return e.jsxs("div",{"data-testid":"preset-row",className:"flex items-center justify-between gap-2 border border-border bg-secondary/40 px-2.5 py-2",children:[e.jsxs(_t,{children:[e.jsx(Kt,{asChild:!0,children:e.jsxs("div",{className:"min-w-0 flex-1 cursor-default",children:[e.jsx("span",{className:"block truncate text-[11px] font-medium",children:w.name}),e.jsx(oe,{variant:"outline",className:"mt-0.5 text-[10px] font-normal",children:N>0?s("modelManagement.presets.rulesCount",{count:N}):s("modelManagement.presets.noRules")})]})}),N>0?e.jsx(Qt,{side:"bottom",className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1 text-xs",children:[v.slice(0,5).map(([C,R])=>e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"truncate",children:C}),e.jsx(ge,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:R})]},C)),N>5?e.jsxs("div",{className:"text-muted-foreground",children:["…+",N-5]}):null]})}):null]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"apply-preset",className:"text-[11px] font-semibold text-primary hover:underline disabled:opacity-50",onClick:()=>a.setPresetDiffDialog({endpoint:t,preset:w}),disabled:b||c||l,children:s(b?"modelManagement.presets.applying":"modelManagement.presets.apply")}),e.jsx("button",{type:"button","data-testid":"delete-preset",className:"text-[11px] text-muted-foreground hover:text-destructive disabled:opacity-50","aria-label":s("common.delete"),onClick:()=>i(t,w),disabled:c||b||l,children:s(c?"modelManagement.presets.deleting":"modelManagement.presets.delete")})]})]},w.name)})})})]})})}function Es({entry:a,index:t,savingRoute:i,options:s,sourceListId:n,onRouteChange:p,onRemoveRoute:h}){const{t:k}=W(),{attributes:g,listeners:y,setNodeRef:l,setActivatorNodeRef:u,transform:d,transition:w,isDragging:b}=St({id:a.id});return e.jsxs("div",{ref:l,"data-testid":"route-rule-row","data-id":a.id,style:{transform:Pt.Transform.toString(d),transition:w},className:Ne("flex items-center gap-2 border border-border bg-card p-2",b&&"z-10 opacity-60 shadow-[var(--surface-shadow-lg)]"),children:[e.jsx("button",{ref:u,type:"button","data-testid":"route-rule-grip","aria-label":k("workbench.routing.dragHandle"),className:"flex h-7 w-4 shrink-0 cursor-grab touch-none items-center justify-center text-muted-foreground hover:text-foreground active:cursor-grabbing",...g,...y,children:e.jsx(Mt,{className:"h-4 w-4","aria-hidden":!0})}),e.jsx("span",{className:"w-4 shrink-0 text-center text-[10.5px] tabular-nums text-muted-foreground",children:t+1}),e.jsx(fe,{"data-testid":"route-rule-source",value:a.source,onChange:c=>p(a.id,"source",c.target.value),placeholder:k("settings.routing.sourcePlaceholder"),list:n,disabled:i,className:"h-8 min-w-0 flex-1 text-xs"}),e.jsx(ge,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground","aria-hidden":!0}),e.jsx("div",{"data-testid":"route-rule-target",className:"min-w-0 flex-[1.15]",children:e.jsx(_e,{value:a.target,onChange:c=>p(a.id,"target",c),options:s,disabled:i,ariaLabel:k("workbench.routing.targetLabel"),placeholder:k("settings.routing.targetPlaceholder")})}),e.jsx(q,{variant:"ghost",size:"icon","data-testid":"route-rule-delete",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>h(a.id),disabled:i,"aria-label":k("common.delete"),children:e.jsx(ft,{className:"h-3.5 w-3.5","aria-hidden":!0})})]})}function Ds({routing:a,endpoint:t,tabInfo:i}){var c;const{t:s}=W(),n=a.routesByEndpoint[t]||[],p=a.routeError[t],h=a.savingRouteFor===t,k=a.isDirtyByEndpoint[t]??!1,g=a.writingEndpoint===t,y=a.providerModelOptions,l=`route-source-${t}`,u=Et(ct(It,{activationConstraint:{distance:6}}),ct(Ft,{coordinateGetter:Lt})),d=v=>{const{active:N,over:C}=v;!C||N.id===C.id||a.handleReorderRules(t,String(N.id),String(C.id))},b=((c=i==null?void 0:i.protocols)==null?void 0:c.includes("anthropic"))??t==="anthropic"?vt:jt;return e.jsx(He,{"data-testid":"routing-rules-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(qe,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h3",{className:"flex items-center gap-2 text-[13px] font-semibold",children:[s("workbench.routing.rulesTitle"),e.jsx(oe,{variant:"outline",className:"text-[10.5px] font-normal tabular-nums",children:n.length})]}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:s("workbench.routing.rulesSubtitle")})]}),e.jsx(q,{variant:"outline",size:"sm","data-testid":"add-route",onClick:()=>a.handleAddRoute(t),disabled:h,children:s("settings.routing.add")})]}),p?e.jsx("p",{className:"text-xs text-destructive",children:p}):null,n.length===0?e.jsx(it,{compact:!0,title:s("workbench.routing.emptyTitle"),description:s("workbench.routing.emptyDescription"),action:e.jsx(q,{size:"sm",onClick:()=>a.handleAddRoute(t),disabled:h,children:s("workbench.routing.addFirst")})}):e.jsx(Dt,{sensors:u,collisionDetection:Rt,onDragEnd:d,children:e.jsx(Tt,{items:n.map(v=>v.id),strategy:Ot,children:e.jsx("div",{className:"flex flex-col gap-1.5",children:n.map((v,N)=>e.jsx(Es,{entry:v,index:N,savingRoute:h,options:y,sourceListId:l,onRouteChange:(C,R,Z)=>a.handleRouteChange(t,C,R,Z),onRemoveRoute:C=>a.handleRemoveRoute(t,C)},v.id))})})}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-t border-border/60 pt-3",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:s(k?"modelManagement.actions.footerDirtyHint":"modelManagement.actions.footerSavedHint")}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(q,{variant:"outline",size:"sm","data-testid":"reset-routes",onClick:()=>a.handleResetRoutes(t),disabled:h||!k,children:s("common.actions.reset")}),e.jsxs(q,{size:"sm","data-testid":"save-routes",onClick:()=>void a.handleSaveRoutes(t),disabled:h||g,className:"relative",children:[s(h?"common.actions.saving":"modelManagement.actions.saveRoutes"),k?e.jsx("span",{className:"absolute -right-1 -top-1 h-2 w-2 rounded-full bg-warning"}):null]})]})]}),e.jsx("datalist",{id:l,children:b.map(v=>e.jsx("option",{value:v},`${l}-${v}`))})]})})}const Rs={simulateRequest(a){return{url:"/api/routing/simulate",method:"POST",data:a}}},Ts=350;function Os(a,t){switch(a.kind){case"modelRoute":return{label:a.viaAlias?t("workbench.hitSim.reasonModelRouteAlias"):t("workbench.hitSim.reasonModelRoute"),tone:"hit"};case"directMatch":return{label:t("workbench.hitSim.reasonDirectMatch"),tone:"hit"};case"thinkingDefault":return{label:t("workbench.hitSim.reasonThinkingDefault"),tone:"hit"};case"completionDefault":return{label:t("workbench.hitSim.reasonCompletionDefault"),tone:"hit"};case"longContextDefault":return{label:t("workbench.hitSim.reasonLongContext"),tone:"hit",detail:t("workbench.hitSim.longContextDetail",{estimate:a.tokenEstimate.toLocaleString(),threshold:a.threshold.toLocaleString()})};case"fallback":return{label:t("workbench.hitSim.reasonFallback"),tone:"fallback"}}return{label:t("workbench.hitSim.reasonFallback"),tone:"fallback"}}function Ls({tabs:a,endpoint:t,onEndpointChange:i}){var C;const{t:s}=W(),n=a.filter(R=>R.key!=="providers"),[p,h]=f.useState(((C=n[0])==null?void 0:C.key)??"anthropic"),k=t??p,g=R=>{t&&i?i(R):h(R)},[y,l]=f.useState(""),[u,d]=f.useState(!1),[w,b]=f.useState("");f.useEffect(()=>{const R=setTimeout(()=>b(y.trim()),Ts);return()=>clearTimeout(R)},[y]);const{data:c,isFetching:v,error:N}=bt(["routing","simulate",k,w,u],Rs.simulateRequest({endpoint:k,model:w||void 0,thinking:u}),{retry:!1,refetchOnWindowFocus:!1,staleTime:1/0});return e.jsxs("section",{"data-testid":"routing-hit-simulator",className:"space-y-3 rounded-lg border border-border bg-card p-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm font-semibold text-foreground",children:s("workbench.hitSim.title")}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:s("workbench.hitSim.subtitle")})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-2",children:[t?null:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:s("workbench.hitSim.endpointLabel")}),e.jsxs(Qe,{value:k,onValueChange:g,children:[e.jsx(Ge,{className:"h-8 w-[168px]",children:e.jsx(We,{})}),e.jsx(Je,{children:n.map(R=>e.jsx(Fe,{value:R.key,children:R.label},R.key))})]})]}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(rt,{checked:u,onCheckedChange:d,"aria-label":s("workbench.hitSim.thinking")}),s("workbench.hitSim.thinking")]})]}),e.jsx(fe,{value:y,onChange:R=>l(R.target.value),placeholder:s("workbench.hitSim.modelPlaceholder"),className:"h-9 text-xs",spellCheck:!1,autoComplete:"off","aria-label":s("workbench.hitSim.modelPlaceholder")}),e.jsx(Fs,{result:c,loading:v,errorMessage:(N==null?void 0:N.message)??null,requestedModel:w})]})}function Fs({result:a,loading:t,errorMessage:i,requestedModel:s}){const{t:n}=W();if(i)return e.jsxs("p",{className:"text-xs text-muted-foreground",children:[n("workbench.hitSim.errorPrefix"),": ",i]});if(!a)return t?e.jsx("div",{className:"h-[72px] animate-pulse rounded-lg border border-border bg-secondary"}):e.jsx("p",{className:"text-xs text-muted-foreground",children:n("workbench.hitSim.empty")});const p=Os(a.reason,n),h=p.tone==="fallback",k=s||n("workbench.hitSim.anyModel");return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:h?"rounded-lg border border-border bg-secondary px-3 py-2.5":"rounded-lg border border-success bg-success-bg px-3 py-2.5",children:[e.jsx("div",{className:h?"text-[11px] font-semibold text-warning":"text-[11px] font-semibold text-success",children:p.label}),e.jsx("div",{className:"mt-1 text-xs text-foreground",children:k}),e.jsxs("div",{className:"mt-1 text-xs text-muted-foreground",children:["→ ",a.providerLabel,":",a.modelId]}),p.detail?e.jsx("div",{className:"mt-1 text-[11px] text-muted-foreground",children:p.detail}):null]}),h?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:n("workbench.hitSim.fallbackHint")}):null]})}function Is({routing:a,config:t,customEndpoints:i,selectedEndpointId:s,routeCounts:n,onSelectEndpoint:p,onCreateEndpoint:h,onEditEndpoint:k,onDeleteEndpoint:g,onRequestDeletePreset:y}){var b;W();const l=s??((b=a.endpointTabs[0])==null?void 0:b.key)??"anthropic",u=a.endpointTabs.find(c=>c.key===l),d=a.defaultsByEndpoint[l],w=(()=>{var v;if(l==="anthropic")return"/anthropic";if(l==="openai")return"/openai";const c=i.find(N=>N.id===l);return(v=c==null?void 0:c.paths)!=null&&v.length?c.paths[0].path:c!=null&&c.path?c.path:`/${l}`})();return e.jsxs("div",{"data-testid":"routing-workspace",className:"flex flex-col gap-3.5",children:[e.jsx(Ms,{endpointPath:w,defaultTarget:(d==null?void 0:d.completion)??null}),e.jsxs("div",{className:"grid items-start gap-3.5 lg:grid-cols-[200px_minmax(0,1fr)_288px]",children:[e.jsx(Ss,{tabs:a.endpointTabs,customEndpoints:i,routeCounts:n,selectedEndpointId:l,onSelect:p,onCreate:h,onEditEndpoint:k,onDeleteEndpoint:g}),e.jsxs("div",{className:"flex flex-col gap-3.5",children:[e.jsx(ws,{routing:a,endpoint:l}),e.jsx(Ds,{routing:a,endpoint:l,tabInfo:u}),e.jsx(Ps,{routing:a,endpoint:l,onRequestDeletePreset:y})]}),e.jsxs("div",{className:"flex flex-col gap-3.5",children:[e.jsx(Ls,{tabs:a.endpointTabs,endpoint:l,onEndpointChange:p}),e.jsx(Ns,{routing:a,endpoint:l,tabInfo:u,config:t,customEndpoints:i})]})]})]})}function As({open:a,provider:t,options:i,usePreset:s,preservedExtras:n,onPresetChange:p,onConfirm:h,onClose:k}){const{t:g}=W();return t?e.jsx(Xe,{open:a,onOpenChange:y=>!y&&k(),children:e.jsxs(Ye,{className:"max-w-2xl",onInteractOutside:y=>y.preventDefault(),children:[e.jsxs(Ze,{children:[e.jsx(et,{children:g("providers.testDialog.title")}),e.jsx(tt,{children:g("providers.testDialog.subtitle",{name:t.label||t.id})})]}),e.jsxs(st,{className:"space-y-4",children:[e.jsx("div",{className:"rounded-xl bg-accent p-4 text-sm text-primary",children:g("providers.testDialog.description")}),e.jsxs("div",{className:"space-y-4 rounded-xl bg-secondary/50 p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ye,{htmlFor:"provider-test-preset",children:g("providers.testDialog.presetLabel")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:g("providers.testDialog.presetDescription")})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(rt,{id:"provider-test-preset",checked:s,onCheckedChange:p})})]}),s?e.jsx("div",{className:"space-y-2",children:e.jsxs("details",{className:"rounded-xl border border-transparent bg-card p-2 text-xs shadow-[var(--surface-shadow)]",children:[e.jsx("summary",{className:"cursor-pointer text-primary hover:underline",children:g("providers.testDialog.presetPreviewSummary")}),e.jsx("div",{className:"mt-2 space-y-1",children:i.map(y=>e.jsxs("code",{className:"block rounded-lg bg-secondary px-2 py-1 text-xs",children:[y.key,": ",y.value]},y.key))})]})}):e.jsx("p",{className:"text-xs text-muted-foreground",children:g("providers.testDialog.presetDescription")})]}),Object.keys(n).length>0&&e.jsxs("div",{className:"space-y-2 rounded-xl bg-secondary/50 p-4 text-xs",children:[e.jsx("p",{className:"font-medium",children:g("providers.testDialog.preservedInfo")}),Object.entries(n).map(([y,l])=>e.jsxs("code",{className:"block rounded-lg border border-transparent bg-card px-2 py-1 shadow-[var(--surface-shadow)]",children:[y,": ",l]},y))]})]}),e.jsxs(at,{children:[e.jsx(q,{variant:"outline",onClick:k,children:g("providers.testDialog.cancel")}),e.jsx(q,{onClick:()=>void h(),children:g("providers.testDialog.primary")})]})]})}):null}function oa(){const{t:a}=W(),t=rs(),i=ms(t),s=ps(t,{sanitizeDraftsForProvider:i.sanitizeDraftsForProvider}),[n,p]=$t(),h=n.get("tab"),k=h==="routing"||h==="endpoints"?"routing":"providers";f.useEffect(()=>{h==="endpoints"&&p(M=>{const I=new URLSearchParams(M);return I.set("tab","routing"),I},{replace:!0})},[h,p]);const[g,y]=f.useState(!1),[l,u]=f.useState(void 0),[d,w]=f.useState(null),[b,c]=f.useState(!1),v=n.get("endpoint"),[N,C]=f.useState(v);f.useEffect(()=>{C(v)},[v]);const R=M=>{p(I=>{const H=new URLSearchParams(I);return H.set("tab","routing"),H.set("endpoint",M),H},{replace:!0})},Z=()=>{p(M=>{const I=new URLSearchParams(M);return I.delete("endpoint"),I},{replace:!0})};f.useEffect(()=>{N&&(t.customEndpointsQuery.isPending||i.endpointTabs.some(M=>M.key===N)||Z())},[N,i.endpointTabs,t.customEndpointsQuery.isPending]);const K=()=>{u(void 0),y(!0)},T=M=>{u(M),y(!0)},j=M=>{p(I=>{const H=new URLSearchParams(I);return M==="providers"?H.delete("tab"):H.set("tab",M),H},{replace:!0})},D=async()=>{if(d){c(!0);try{d.kind==="provider"?await s.handleDeleteProvider(d.provider):d.kind==="preset"?await i.handleDeletePreset(d.endpoint,d.preset):await i.handleDeleteEndpoint(d.endpoint.id),w(null)}finally{c(!1)}}},B=(d==null?void 0:d.kind)==="provider"?ns(t.config,t.customEndpoints,d.provider.id):0,z=(d==null?void 0:d.kind)==="provider"?a("providers.actions.delete"):(d==null?void 0:d.kind)==="preset"?a("modelManagement.presets.delete"):(d==null?void 0:d.kind)==="endpoint"?a("common.delete"):"",V=(d==null?void 0:d.kind)==="provider"?a("providers.confirm.delete",{name:d.provider.label||d.provider.id}):(d==null?void 0:d.kind)==="preset"?a("modelManagement.confirm.deletePreset",{name:d.preset.name}):(d==null?void 0:d.kind)==="endpoint"?a("modelManagement.deleteEndpointConfirm",{label:d.endpoint.label}):"",ae=(d==null?void 0:d.kind)==="provider"?d.provider.label||d.provider.id:(d==null?void 0:d.kind)==="preset"?d.preset.name:(d==null?void 0:d.kind)==="endpoint"?d.endpoint.label:"",A=Object.values(i.routesByEndpoint).reduce((M,I)=>M+((I==null?void 0:I.length)??0),0),ie=Object.fromEntries(Object.entries(i.routesByEndpoint).map(([M,I])=>[M,(I==null?void 0:I.length)??0])),X=[{value:"providers",icon:At,label:a("workbench.viewSwitch.providers"),description:a("workbench.viewSwitch.providersDesc"),count:s.providerCount},{value:"routing",icon:Bt,label:a("workbench.viewSwitch.routing"),description:a("workbench.viewSwitch.routingDesc"),count:A}];return e.jsxs("div",{className:"flex flex-col gap-6",children:[e.jsx(qt,{actions:k==="providers"?e.jsx(q,{size:"sm",onClick:s.handleOpenCreate,children:a("providers.actions.add")}):e.jsx(q,{size:"sm",onClick:K,children:a("workbench.endpoints.create")})}),e.jsx("div",{role:"tablist","aria-label":a("workbench.viewSwitch.label"),className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:X.map(M=>{const I=M.icon,H=k===M.value;return e.jsxs("button",{type:"button",role:"tab","aria-selected":H,onClick:()=>j(M.value),className:Ne("motion-surface flex items-center gap-3 rounded-xl border p-4 text-left",H?"border-primary/40 bg-primary/5":"border-border bg-card hover:bg-muted/40"),children:[e.jsx("span",{className:Ne("flex h-9 w-9 shrink-0 items-center justify-center rounded-lg",H?"bg-primary/10 text-primary":"bg-secondary text-muted-foreground"),children:e.jsx(I,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:Ne("text-sm font-semibold",H?"text-foreground":"text-muted-foreground"),children:M.label}),e.jsx(oe,{variant:H?"default":"secondary",className:"text-[10px]",children:M.count})]}),e.jsx("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",children:M.description})]})]},M.value)})}),k==="providers"?e.jsx(ys,{configPending:t.configQuery.isPending||!t.config&&t.configQuery.isFetching,testResults:s.testResults,filteredProviders:s.filteredProviders,providerSearch:s.providerSearch,providerTypeFilter:s.providerTypeFilter,providersLength:s.providers.length,defaultLabels:s.defaultLabels,config:t.config,customEndpoints:t.customEndpoints,onTest:M=>s.initiateTestConnection(M),onEdit:M=>s.handleOpenEdit(M),onProviderSearchChange:s.setProviderSearch,onProviderTypeChange:s.setProviderTypeFilter,onResetFilters:()=>{s.setProviderSearch(""),s.setProviderTypeFilter("all")}}):e.jsx(Is,{routing:i,config:t.config,customEndpoints:t.customEndpoints,routeCounts:ie,selectedEndpointId:N,onSelectEndpoint:R,onCreateEndpoint:K,onEditEndpoint:T,onDeleteEndpoint:M=>w({kind:"endpoint",endpoint:M}),onRequestDeletePreset:(M,I)=>w({kind:"preset",endpoint:M,preset:I})}),e.jsx(bs,{open:s.drawerOpen,mode:s.drawerMode,provider:s.drawerMode==="edit"?s.editingProvider:void 0,existingProviderIds:s.providers.map(M=>M.id).filter(M=>s.drawerMode==="edit"&&s.editingProvider?M!==s.editingProvider.id:!0),testResult:s.editingProvider?s.testResults[s.editingProvider.id]??null:null,testing:s.editingProvider?s.testingProviderId===s.editingProvider.id:!1,onTest:()=>{s.editingProvider&&s.handleTestConnection(s.editingProvider)},onDelete:()=>{s.drawerMode==="edit"&&s.editingProvider&&w({kind:"provider",provider:s.editingProvider})},onClose:()=>{s.setDrawerOpen(!1),s.setEditingProvider(void 0),s.setDrawerMode("create")},onSubmit:s.handleProviderSubmit}),e.jsx(As,{open:s.testDialogOpen,provider:s.testDialogProvider,options:s.anthropicTestHeaderOptions,preservedExtras:s.testDialogPreservedExtras,usePreset:s.testDialogUsePreset,onPresetChange:s.setTestDialogUsePreset,onConfirm:s.confirmTestDialog,onClose:s.closeTestDialog}),e.jsx(gs,{open:!!s.noModelDialogProvider,provider:s.noModelDialogProvider,onClose:()=>s.setNoModelDialogProvider(null),onEdit:M=>{s.setNoModelDialogProvider(null),s.handleOpenEdit(M)}}),e.jsx(xs,{open:g,endpoint:l,onClose:()=>{y(!1),u(void 0)},onSuccess:()=>{t.configQuery.refetch()}}),e.jsx(fs,{dialog:i.presetDiffDialog,currentRoutes:i.presetDiffDialog?i.routesByEndpoint[i.presetDiffDialog.endpoint]||[]:[],onConfirm:(M,I)=>{i.setPresetDiffDialog(null),i.handleApplyPreset(M,I)},onClose:()=>i.setPresetDiffDialog(null)}),e.jsx(Ht,{open:!!d,onOpenChange:M=>{!M&&!b&&w(null)},title:z,description:V,confirmLabel:a(b?"common.actions.loading":"common.delete"),cancelLabel:a("common.actions.cancel"),loading:b,onConfirm:D,children:ae?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"rounded-xl border border-destructive/20 bg-destructive/5 px-3 py-2 font-mono text-xs text-foreground",children:ae}),(d==null?void 0:d.kind)==="provider"&&B>0?e.jsx("p",{className:"text-xs text-muted-foreground",children:a("providers.confirm.deleteImpact",{count:B})}):null]}):null})]})}export{oa as default};
@@ -0,0 +1 @@
1
+ import{j as e,aW as Y,aP as xt,ak as ft,r as d}from"./vendor-CITafuNQ.js";import{C as He}from"./ConfirmDialog-CyTpXZeT.js";import{P as Ve}from"./PageState-CFLrRswm.js";import{P as bt}from"./PageToolbar-CWw40AFL.js";import{C as k,a as L}from"./card-D4YOc5eB.js";import{B as O,r as Ke,i as vt,d as yt,a as jt,c as De,q as Z}from"./app-Citq5KW4.js";import{B as V}from"./badge-DpUlf_NW.js";import{L as f,I as j}from"./label-DSVzZIex.js";import{S as B}from"./switch-7PH_rDz6.js";import{S as Nt,a as wt,b as Ct,c as Pt,d as kt}from"./select-sOwKYsgI.js";import{c as E}from"./global-BCehxTGJ.js";import{u as P}from"./i18n-PeX9kBVO.js";import{u as ee}from"./useAppMutation-CEN5Oa4S.js";import{g as qe}from"./gateway-i49olSPp.js";import{c as St}from"./clipboard-BnAnBk_-.js";import"./DialogShell-CM92wXHo.js";import"./radix-Bux_1C5J.js";import"./query-DZF7K6hv.js";import"./router-BoBrmro7.js";const Rt=[{value:"fatal",labelKey:"fatal"},{value:"error",labelKey:"error"},{value:"warn",labelKey:"warn"},{value:"info",labelKey:"info"},{value:"debug",labelKey:"debug"},{value:"trace",labelKey:"trace"}],oe=[{id:"section-basics",labelKey:"settings.sections.basics"},{id:"section-protocol",labelKey:"settings.sections.protocol"},{id:"section-security",labelKey:"settings.sections.security"},{id:"section-config-file",labelKey:"settings.sections.configFile"},{id:"section-cleanup",labelKey:"settings.sections.cleanup"}];function te(t){var o,m,l,i,a,p,y,A,T,u,M;const s=t.storePayloads,r=N=>typeof N=="boolean"?N:typeof s=="boolean"?s:!0;return{port:String(t.port??((o=t.http)==null?void 0:o.port)??""),host:t.host??((m=t.http)==null?void 0:m.host)??"127.0.0.1",logRetentionDays:String(t.logRetentionDays??30),logExportTimeoutSeconds:String(t.logExportTimeoutSeconds??60),storeRequestPayloads:r(t.storeRequestPayloads),storeResponsePayloads:r(t.storeResponsePayloads),logLevel:t.logLevel??"info",bodyLimitMb:(()=>{const N=t.bodyLimit;return typeof N=="number"&&Number.isFinite(N)&&N>0?String(Math.max(1,Math.round(N/(1024*1024)))):"10"})(),enableRoutingFallback:t.enableRoutingFallback===!0,httpEnabled:((l=t.http)==null?void 0:l.enabled)!==!1,httpPort:String(((i=t.http)==null?void 0:i.port)??t.port??4100),httpHost:((a=t.http)==null?void 0:a.host)??t.host??"127.0.0.1",httpsEnabled:((p=t.https)==null?void 0:p.enabled)===!0,httpsPort:String(((y=t.https)==null?void 0:y.port)??4443),httpsHost:((A=t.https)==null?void 0:A.host)??t.host??"127.0.0.1",httpsKeyPath:((T=t.https)==null?void 0:T.keyPath)??"",httpsCertPath:((u=t.https)==null?void 0:u.certPath)??"",httpsCaPath:((M=t.https)==null?void 0:M.caPath)??""}}function se(t){return{enabled:t.enabled,username:t.username??"",password:"",confirmPassword:""}}function Et({activeSection:t,onSelectSection:s}){const{t:r}=P();return e.jsxs(e.Fragment,{children:[e.jsx("nav",{className:"hidden xl:block",children:e.jsxs(k,{className:"sticky top-20 p-3.5",children:[e.jsx("p",{className:"mb-2.5 px-2 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground",children:r("settings.sections.jump")}),e.jsx("div",{className:"space-y-1.5",children:oe.map((o,m)=>e.jsxs("button",{type:"button",onClick:()=>s(o.id),className:E("flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-left text-sm font-semibold transition-all duration-200",t===o.id?"bg-secondary text-foreground":"text-muted-foreground hover:text-foreground"),children:[e.jsx("span",{className:E("flex h-7 w-7 items-center justify-center rounded-lg text-[11px] font-semibold",t===o.id?"bg-primary text-primary-foreground":"bg-secondary text-muted-foreground"),children:m+1}),e.jsx("span",{children:r(o.labelKey)})]},o.id))})]})}),e.jsx("div",{className:"xl:hidden",children:e.jsx("div",{className:"overflow-x-auto pb-1",children:e.jsx("div",{className:"flex w-max gap-2 px-1",children:oe.map(o=>e.jsx("button",{type:"button",onClick:()=>s(o.id),className:E("rounded-lg px-4 py-2 text-xs font-semibold transition-all duration-150",t===o.id?"bg-secondary text-foreground font-medium":"text-muted-foreground hover:text-foreground hover:bg-secondary/50"),children:r(o.labelKey)},o.id))})})})]})}function Lt({defaultsSummary:t,errors:s,form:r,onInputChange:o,onSetForm:m,sectionRef:l}){const{t:i}=P();return e.jsx(k,{id:"section-basics",ref:l,className:"bg-card shadow-[var(--surface-shadow)]",children:e.jsxs(L,{className:"pt-6",children:[e.jsxs("div",{className:"mb-4 flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:i("settings.sections.basics")}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:i("settings.description")})]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-3",children:[e.jsx(ae,{label:i("settings.fields.retention"),value:r.logRetentionDays}),e.jsx(ae,{label:i("settings.fields.logExportTimeout"),value:`${r.logExportTimeoutSeconds}s`}),e.jsx(ae,{label:i("settings.fields.bodyLimit"),value:`${r.bodyLimitMb} MB`})]})]}),e.jsxs("div",{className:"grid gap-5 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:i("settings.fields.port")}),e.jsx(j,{type:"number",min:1,max:65535,value:r.port,onChange:a=>o("port")(a.target.value),"aria-invalid":!!s.port}),s.port?e.jsx("p",{className:"text-xs text-destructive",children:s.port}):null]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:i("settings.fields.host")}),e.jsx(j,{value:r.host,onChange:a=>o("host")(a.target.value),placeholder:i("settings.fields.hostPlaceholder")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:i("settings.fields.retention")}),e.jsx(j,{type:"number",min:1,max:365,value:r.logRetentionDays,onChange:a=>o("logRetentionDays")(a.target.value),"aria-invalid":!!s.logRetentionDays}),s.logRetentionDays?e.jsx("p",{className:"text-xs text-destructive",children:s.logRetentionDays}):null]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:i("settings.fields.logExportTimeout")}),e.jsx(j,{type:"number",min:5,max:600,value:r.logExportTimeoutSeconds,onChange:a=>o("logExportTimeoutSeconds")(a.target.value),"aria-invalid":!!s.logExportTimeoutSeconds}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i("settings.fields.logExportTimeoutHint")}),s.logExportTimeoutSeconds?e.jsx("p",{className:"text-xs text-destructive",children:s.logExportTimeoutSeconds}):null]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:i("settings.fields.bodyLimit")}),e.jsx(j,{type:"number",min:1,max:2048,value:r.bodyLimitMb,onChange:a=>o("bodyLimitMb")(a.target.value),"aria-invalid":!!s.bodyLimitMb}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i("settings.fields.bodyLimitHint")}),s.bodyLimitMb?e.jsx("p",{className:"text-xs text-destructive",children:s.bodyLimitMb}):null]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:i("settings.fields.logLevel")}),e.jsxs(Nt,{value:r.logLevel,onValueChange:a=>m(p=>({...p,logLevel:a})),children:[e.jsx(wt,{children:e.jsx(Ct,{})}),e.jsx(Pt,{children:Rt.map(a=>e.jsx(kt,{value:a.value,children:i(`settings.fields.logLevelOption.${a.labelKey}`)},a.value))})]})]}),e.jsxs("div",{className:"grid gap-4 md:col-span-2 sm:grid-cols-2",children:[e.jsx(ne,{label:i("settings.fields.storeRequestPayloads"),hint:i("settings.fields.storeRequestPayloadsHint"),checked:r.storeRequestPayloads,onCheckedChange:a=>m(p=>({...p,storeRequestPayloads:a}))}),e.jsx(ne,{label:i("settings.fields.storeResponsePayloads"),hint:i("settings.fields.storeResponsePayloadsHint"),checked:r.storeResponsePayloads,onCheckedChange:a=>m(p=>({...p,storeResponsePayloads:a}))}),e.jsx(ne,{label:i("settings.fields.enableRoutingFallback"),hint:i("settings.fields.enableRoutingFallbackHint"),checked:r.enableRoutingFallback,onCheckedChange:a=>m(p=>({...p,enableRoutingFallback:a}))})]}),e.jsxs("div",{className:"rounded-xl bg-secondary px-4 py-5 md:col-span-2",children:[e.jsx(f,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:i("settings.fields.defaults")}),e.jsx("p",{className:"mt-2 text-sm",children:t??i("settings.defaults.none")})]})]})]})})}function At({errors:t,form:s,onSetForm:r,protocolChangesPending:o,sectionRef:m}){const{t:l}=P();return e.jsx(k,{id:"section-protocol",ref:m,className:"bg-card shadow-[var(--surface-shadow)]",children:e.jsxs(L,{className:"space-y-6 pt-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:l("settings.sections.protocol")}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:l("settings.protocol.description")})]}),o?e.jsx("div",{className:"rounded-xl bg-warning-bg ring-1 ring-warning/30 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Y,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-warning"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:l("settings.protocol.restartWarning")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l("settings.protocol.restartHint")}),e.jsx("code",{className:"block rounded-lg border border-border bg-secondary px-3 py-2 text-xs font-mono text-foreground",children:"cc-gw restart --daemon"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l("settings.protocol.restartTip")})]})]})}):null,t.protocol?e.jsxs("div",{className:"rounded-xl bg-destructive/10 ring-1 ring-destructive/30 p-4 text-sm text-destructive",children:[e.jsx(Y,{className:"mr-2 inline h-4 w-4"}),t.protocol]}):null,e.jsxs("div",{className:"rounded-xl bg-secondary p-5",children:[e.jsxs("div",{className:"mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(f,{className:"text-sm font-medium text-foreground",children:l("settings.protocol.http.enable")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l("settings.protocol.http.hint")})]}),e.jsx(B,{checked:s.httpEnabled,onCheckedChange:i=>r(a=>({...a,httpEnabled:i}))})]}),s.httpEnabled?e.jsxs("div",{className:"mt-4 grid gap-4 border-t border-border pt-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:l("settings.protocol.http.port")}),e.jsx(j,{type:"number",min:1,max:65535,value:s.httpPort,onChange:i=>r(a=>({...a,httpPort:i.target.value})),"aria-invalid":!!t.httpPort}),t.httpPort?e.jsx("p",{className:"text-xs text-destructive",children:t.httpPort}):null]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:l("settings.protocol.http.host")}),e.jsx(j,{value:s.httpHost,onChange:i=>r(a=>({...a,httpHost:i.target.value})),placeholder:"127.0.0.1"})]})]}):null]}),e.jsxs("div",{className:"rounded-xl bg-secondary p-5",children:[e.jsxs("div",{className:"mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(f,{className:"text-sm font-medium text-foreground",children:l("settings.protocol.https.enable")}),e.jsx(xt,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l("settings.protocol.https.hint")})]}),e.jsx(B,{checked:s.httpsEnabled,onCheckedChange:i=>r(a=>({...a,httpsEnabled:i}))})]}),s.httpsEnabled?e.jsxs("div",{className:"mt-4 space-y-4 border-t border-border pt-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:l("settings.protocol.https.port")}),e.jsx(j,{type:"number",min:1,max:65535,value:s.httpsPort,onChange:i=>r(a=>({...a,httpsPort:i.target.value})),"aria-invalid":!!t.httpsPort}),t.httpsPort?e.jsx("p",{className:"text-xs text-destructive",children:t.httpsPort}):null]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:l("settings.protocol.https.host")}),e.jsx(j,{value:s.httpsHost,onChange:i=>r(a=>({...a,httpsHost:i.target.value})),placeholder:"127.0.0.1"})]})]}),e.jsx(le,{label:l("settings.protocol.https.keyPath"),value:s.httpsKeyPath,onChange:i=>r(a=>({...a,httpsKeyPath:i})),placeholder:"~/.cc-gw/certs/key.pem"}),e.jsx(le,{label:l("settings.protocol.https.certPath"),value:s.httpsCertPath,onChange:i=>r(a=>({...a,httpsCertPath:i})),placeholder:"~/.cc-gw/certs/cert.pem"}),e.jsx(le,{label:l("settings.protocol.https.caPath"),value:s.httpsCaPath,onChange:i=>r(a=>({...a,httpsCaPath:i})),placeholder:"留空则不使用"}),e.jsx("div",{className:"rounded-xl bg-warning-bg ring-1 ring-warning/30 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Y,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-warning"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx("p",{className:"text-sm font-medium text-warning",children:l("settings.protocol.https.warning")}),e.jsx("p",{className:"text-xs leading-relaxed text-warning",children:l("settings.protocol.https.tip")})]})]})})]}):null]})]})})}function Tt({authErrors:t,authForm:s,authLoading:r,authSettings:o,needsPassword:m,onSetAuthForm:l,sectionRef:i}){const{t:a}=P();return e.jsx(k,{id:"section-security",ref:i,className:"bg-card shadow-[var(--surface-shadow)]",children:e.jsxs(L,{className:"space-y-5 pt-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:a("settings.sections.security")}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:a("settings.auth.description")})]}),r&&!o?e.jsx(Ve,{compact:!0,label:a("common.loading")}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-4 rounded-xl bg-secondary p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{className:"text-sm font-medium",children:a("settings.auth.enable")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:a("settings.auth.enableHint")}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-xs font-medium text-muted-foreground",children:[e.jsx("span",{className:"rounded-lg bg-secondary px-3 py-1 text-[11px] tracking-[0.08em]",children:"/ui"}),e.jsx("span",{className:"rounded-lg bg-secondary px-3 py-1 text-[11px] tracking-[0.08em]",children:"/api/*"}),e.jsx("span",{className:"rounded-lg bg-secondary px-3 py-1 text-[11px] tracking-[0.08em]",children:"Cookie Session"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 self-start sm:self-auto",children:[e.jsx(V,{variant:s.enabled?"success":"secondary",children:s.enabled?a("settings.auth.statusEnabled"):a("settings.auth.statusDisabled")}),e.jsx(B,{checked:s.enabled,onCheckedChange:p=>l(y=>({...y,enabled:p}))})]})]}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,0.85fr)]",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(f,{children:a("settings.auth.username")}),e.jsx(j,{value:s.username,onChange:p=>l(y=>({...y,username:p.target.value})),placeholder:a("settings.auth.usernamePlaceholder")}),t.username?e.jsx("p",{className:"text-xs text-destructive",children:t.username}):null]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:a("settings.auth.password")}),e.jsx(j,{type:"password",value:s.password,disabled:!s.enabled,onChange:p=>l(y=>({...y,password:p.target.value})),placeholder:a("settings.auth.passwordPlaceholder")}),t.password?e.jsx("p",{className:"text-xs text-destructive",children:t.password}):e.jsx("p",{className:"text-xs text-muted-foreground",children:a(m?"settings.auth.passwordHintRequired":"settings.auth.passwordHintOptional")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:a("settings.auth.confirmPassword")}),e.jsx(j,{type:"password",value:s.confirmPassword,disabled:!s.enabled,onChange:p=>l(y=>({...y,confirmPassword:p.target.value})),placeholder:a("settings.auth.confirmPasswordPlaceholder")}),t.confirmPassword?e.jsx("p",{className:"text-xs text-destructive",children:t.confirmPassword}):null]})]}),e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"rounded-xl bg-secondary p-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.34em] text-muted-foreground",children:a("settings.auth.status")}),e.jsx("p",{className:"mt-2 text-base font-semibold",children:o!=null&&o.enabled?a("settings.auth.statusEnabled"):a("settings.auth.statusDisabled")}),o!=null&&o.username?e.jsxs("div",{className:"mt-3 rounded-lg bg-accent px-3 py-2 text-xs font-medium text-primary",children:[a("settings.auth.username"),": ",o.username]}):null]}),e.jsx("div",{className:"rounded-xl bg-secondary px-4 py-3 text-xs text-muted-foreground",children:a(m?"settings.auth.passwordHintRequired":"settings.auth.passwordHintOptional")})]})]})]})]})})}function Mt({configPath:t,onCopyPath:s,sectionRef:r}){const{t:o}=P();return e.jsx(k,{id:"section-config-file",ref:r,className:"bg-card shadow-[var(--surface-shadow)]",children:e.jsxs(L,{className:"space-y-3 pt-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:o("settings.sections.configFile")}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:o("settings.file.description")})]}),e.jsxs(O,{variant:"outline",size:"sm",onClick:s,className:"w-full sm:w-auto",children:[e.jsx(ft,{className:"mr-2 h-4 w-4"}),o("common.actions.copy")]})]}),e.jsx("code",{className:"block break-all rounded-lg bg-secondary px-4 py-3 text-xs font-mono text-muted-foreground",children:t||o("settings.file.unknown")}),e.jsx("div",{className:"rounded-lg bg-secondary px-4 py-3 text-xs text-muted-foreground",children:o("help.note")})]})})}function Ot({cleaning:t,clearingAll:s,onOpenCleanup:r,onOpenClearAll:o,sectionRef:m}){const{t:l}=P();return e.jsx(k,{id:"section-cleanup",ref:m,className:"bg-card shadow-[var(--surface-shadow)]",children:e.jsxs(L,{className:"space-y-4 pt-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:l("settings.sections.cleanup")}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:l("settings.cleanup.description")})]}),e.jsx("div",{className:"rounded-lg bg-secondary px-4 py-3 text-xs text-muted-foreground",children:l("settings.cleanup.confirmCleanup")}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsx("div",{className:"rounded-xl border border-warning/30 bg-warning-bg p-5",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(V,{variant:"warning",children:l("settings.cleanup.softLabel")}),e.jsx("p",{className:"text-sm font-medium",children:l("settings.cleanup.softTitle")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l("settings.cleanup.softDescription")}),e.jsx(O,{variant:"outline",onClick:r,disabled:t,className:"w-full sm:w-auto",children:l(t?"common.actions.cleaning":"common.actions.cleanup")})]})}),e.jsx("div",{className:"rounded-xl border border-destructive/30 bg-destructive/10 p-5 text-destructive",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(V,{variant:"outline",className:"border-destructive/40 bg-destructive/10 text-destructive",children:l("settings.cleanup.hardLabel")}),e.jsx("p",{className:"text-sm font-medium",children:l("settings.cleanup.hardTitle")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l("settings.cleanup.clearAllWarning")}),e.jsx(O,{variant:"destructive",onClick:o,disabled:s,className:"w-full sm:w-auto",children:l(s?"settings.cleanup.clearingAll":"settings.cleanup.clearAll")})]})})]})]})})}function Ft({dirtyCount:t,protocolChangesPending:s,onReset:r,onSave:o,saving:m}){const{t:l}=P();return t===0?null:e.jsxs("div",{className:"sticky bottom-4 z-20 flex flex-col gap-3 rounded-xl bg-card border border-border px-6 py-5 shadow-[var(--surface-shadow-lg)] md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(V,{variant:"secondary",children:l("settings.overview.unsavedCount",{count:t})}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l(s?"settings.toast.protocolRestartRequired":"modelManagement.actions.footerDirtyHint")})]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2 lg:flex lg:flex-wrap lg:items-center",children:[e.jsx(O,{variant:"outline",onClick:r,disabled:m,className:"w-full lg:w-auto",children:l("common.actions.reset")}),e.jsx(O,{onClick:o,disabled:m,className:"w-full lg:w-auto",children:l(m?"common.actions.saving":"common.actions.save")})]})]})}function ae({label:t,value:s}){return e.jsxs("div",{className:"rounded-lg bg-secondary px-3 py-2 text-center",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.3em] text-muted-foreground",children:t}),e.jsx("p",{className:"mt-1 text-sm font-semibold text-foreground",children:s})]})}function ne({checked:t,className:s,hint:r,hintClassName:o,label:m,labelClassName:l,onCheckedChange:i}){return e.jsxs("div",{className:E("flex flex-col gap-3 rounded-xl bg-secondary p-4 sm:flex-row sm:items-center sm:justify-between",s),children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(f,{className:E("text-sm font-semibold text-foreground",l),children:m}),e.jsx("p",{className:E("text-xs text-muted-foreground",o),children:r})]}),e.jsx(B,{checked:t,onCheckedChange:i,className:"self-start sm:self-auto"})]})}function le({label:t,onChange:s,placeholder:r,value:o}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:t}),e.jsx(j,{value:o,onChange:m=>s(m.target.value),placeholder:r,className:"font-mono text-xs"})]})}const q={authStatusRequest(){return{url:"/api/auth/web",method:"GET"}},saveWebAuth:async t=>vt(yt.post("/api/auth/web",t)),cleanupLogs:async()=>Ke({url:"/api/logs/cleanup",method:"POST"}),clearLogs:async()=>Ke({url:"/api/logs/clear",method:"POST"})};function Ht(){const{t}=P(),{pushToast:s}=jt(),[r,o]=d.useState(oe[0].id),m=d.useRef(new Map),l=d.useCallback(n=>{const h=m.current.get(n);h&&h.scrollIntoView({behavior:"smooth",block:"start"})},[]),i=d.useCallback(n=>h=>{h?m.current.set(n,h):m.current.delete(n)},[]),a=De(Z.config.info(),qe.configInfoRequest()),p=De(Z.auth.web(),q.authStatusRequest()),y=ee({mutationFn:q.saveWebAuth,successToast:()=>({title:t("settings.auth.toast.success")}),errorToast:n=>({title:t("settings.auth.toast.failure",{message:n.message})}),invalidateKeys:[Z.auth.web()]}),A=ee({mutationFn:q.cleanupLogs,successToast:n=>({title:n.deleted>0?t("settings.toast.cleanupSuccess",{count:n.deleted}):t("settings.toast.cleanupNone")}),errorToast:n=>({title:t("settings.toast.cleanupFailure",{message:n.message})}),invalidateKeys:[["logs"],["dashboard"],["db"]]}),T=ee({mutationFn:q.clearLogs,successToast:n=>({title:t("settings.toast.clearAllSuccess",{logs:n.deleted,metrics:n.metricsCleared})}),errorToast:n=>({title:t("settings.toast.clearAllFailure",{message:n.message})}),invalidateKeys:[["logs"],["stats"],["dashboard"],["db"]]}),[u,M]=d.useState(null),[N,Be]=d.useState(""),[c,F]=d.useState({port:"",host:"",logRetentionDays:"",logExportTimeoutSeconds:"60",storeRequestPayloads:!0,storeResponsePayloads:!0,logLevel:"info",bodyLimitMb:"10",enableRoutingFallback:!1,httpEnabled:!0,httpPort:"4100",httpHost:"127.0.0.1",httpsEnabled:!1,httpsPort:"4443",httpsHost:"127.0.0.1",httpsKeyPath:"",httpsCertPath:"",httpsCaPath:""}),[Ie,I]=d.useState({}),[We,ie]=d.useState(!1),[Je,re]=d.useState(!1),[Qe,ce]=d.useState(!1),[_e,ze]=d.useState(!1),[Ge,$e]=d.useState(!1),[b,de]=d.useState(null),[g,H]=d.useState({enabled:!1,username:"",password:"",confirmPassword:""}),[Ue,K]=d.useState({}),[Xe,ue]=d.useState(!1),Ye=d.useMemo(()=>{if(!(u!=null&&u.defaults))return null;const n=[];return u.defaults.completion&&n.push(t("settings.defaults.completion",{model:u.defaults.completion})),u.defaults.reasoning&&n.push(t("settings.defaults.reasoning",{model:u.defaults.reasoning})),u.defaults.background&&n.push(t("settings.defaults.background",{model:u.defaults.background})),n.length>0?n.join(" | "):t("settings.defaults.none")},[u,t]),Ze=d.useMemo(()=>c.httpEnabled&&c.httpsEnabled?t("settings.overview.values.httpAndHttps"):c.httpsEnabled?t("settings.overview.values.httpsOnly"):t("settings.overview.values.httpOnly"),[c.httpEnabled,c.httpsEnabled,t]),et=d.useMemo(()=>g.enabled?b!=null&&b.hasPassword?g.username.trim()!==(b.username??""):!0:!1,[g.enabled,g.username,b]),S=d.useMemo(()=>u?te(u):null,[u]),W=d.useMemo(()=>S?JSON.stringify(c)!==JSON.stringify(S):!1,[c,S]),J=d.useMemo(()=>b?se(b):null,[b]),Q=d.useMemo(()=>J?JSON.stringify(g)!==JSON.stringify(J):!1,[g,J]),tt=d.useMemo(()=>S?["httpEnabled","httpPort","httpHost","httpsEnabled","httpsPort","httpsHost","httpsKeyPath","httpsCertPath","httpsCaPath","port","host"].some(h=>c[h]!==S[h]):!1,[c,S]);d.useEffect(()=>{a.data&&(M(a.data.config),Be(a.data.path),F(te(a.data.config)))},[a.data]),d.useEffect(()=>{p.data&&(de(p.data),H(se(p.data)),K({}))},[p.data]),d.useEffect(()=>{!a.isError||!a.error||s({title:t("settings.toast.loadFailure",{message:a.error.message}),variant:"error"})},[a.error,a.isError,s,t]),d.useEffect(()=>{!p.isError||!p.error||s({title:t("settings.toast.authLoadFailure",{message:p.error.message}),variant:"error"})},[p.error,p.isError,s,t]);const st=d.useCallback(n=>h=>{F(v=>({...v,[n]:h}))},[]),pe=d.useCallback(()=>{const n={};if(!c.httpEnabled&&!c.httpsEnabled&&(n.protocol=t("settings.validation.protocolRequired")),c.httpEnabled){const C=Number(c.httpPort);(!Number.isFinite(C)||C<1||C>65535)&&(n.httpPort=t("settings.validation.httpPort"))}if(c.httpsEnabled){const C=Number(c.httpsPort);(!Number.isFinite(C)||C<1||C>65535)&&(n.httpsPort=t("settings.validation.httpsPort")),(!c.httpsKeyPath||!c.httpsCertPath)&&(n.protocol=t("settings.validation.httpsCertificate"))}const h=Number(c.port);(!Number.isFinite(h)||h<1||h>65535)&&(n.port=t("settings.validation.port"));const v=Number(c.logRetentionDays);(!Number.isFinite(v)||v<1||v>365)&&(n.logRetentionDays=t("settings.validation.retention"));const w=Number(c.logExportTimeoutSeconds);(!Number.isFinite(w)||w<5||w>600)&&(n.logExportTimeoutSeconds=t("settings.validation.logExportTimeout"));const R=Number(c.bodyLimitMb);return(!Number.isFinite(R)||R<1||R>2048)&&(n.bodyLimitMb=t("settings.validation.bodyLimit")),I(n),Object.keys(n).length===0},[c,t]),me=d.useCallback(()=>{const n={},h=g.username.trim(),v=b?h!==(b.username??""):!0,w=g.enabled&&(!(b!=null&&b.hasPassword)||v);return g.enabled&&!h&&(n.username=t("settings.auth.validation.username")),g.password&&g.password.length<6&&(n.password=t("settings.auth.validation.minLength")),w&&!g.password&&(n.password=t("settings.auth.validation.passwordRequired")),(g.password||g.confirmPassword)&&g.password!==g.confirmPassword&&(n.confirmPassword=t("settings.auth.validation.confirmMismatch")),K(n),Object.keys(n).length===0},[g,b,t]),_=d.useCallback(async()=>{var n,h,v,w,R,C,he,ge,xe,fe,be,ve,ye,je,Ne,we,Ce,Pe,ke,Se,Re,Ee,Le,Ae,Te,Me;if(!u){s({title:t("settings.toast.loadFailure",{message:t("settings.toast.missingConfig")}),variant:"error"});return}if(pe()){ie(!0);try{const D=Number(c.port),rt=Number(c.logRetentionDays),ct=Number(c.logExportTimeoutSeconds),dt=Number(c.bodyLimitMb),x={...u,http:{enabled:c.httpEnabled,port:Number(c.httpPort),host:c.httpHost.trim()||"127.0.0.1"},https:{enabled:c.httpsEnabled,port:Number(c.httpsPort),host:c.httpsHost.trim()||"127.0.0.1",keyPath:c.httpsKeyPath.trim(),certPath:c.httpsCertPath.trim(),caPath:c.httpsCaPath.trim()||void 0},port:D,host:c.host.trim()||void 0,logRetentionDays:rt,logExportTimeoutSeconds:Math.min(Math.max(Math.round(ct),5),600),storeRequestPayloads:c.storeRequestPayloads,storeResponsePayloads:c.storeResponsePayloads,logLevel:c.logLevel,bodyLimit:Math.max(1,Math.floor(dt*1024*1024)),enableRoutingFallback:c.enableRoutingFallback};delete x.requestLogging,delete x.responseLogging;const Oe={...x};delete Oe.webAuth,await qe.saveConfig(Oe),M({...x,webAuth:u.webAuth});const Fe=X=>(X==null?void 0:X.trim())||void 0,ut=u.port??((n=u.http)==null?void 0:n.port)??4100,pt=x.port??((h=x.http)==null?void 0:h.port)??4100,mt=((v=u.host)==null?void 0:v.trim())||((R=(w=u.http)==null?void 0:w.host)==null?void 0:R.trim())||"127.0.0.1",ht=((C=x.host)==null?void 0:C.trim())||((ge=(he=x.http)==null?void 0:he.host)==null?void 0:ge.trim())||"127.0.0.1",gt=ut!==pt||mt!==ht||((xe=u.http)==null?void 0:xe.enabled)!==((fe=x.http)==null?void 0:fe.enabled)||((be=u.http)==null?void 0:be.port)!==((ve=x.http)==null?void 0:ve.port)||(((ye=u.http)==null?void 0:ye.host)??u.host??"127.0.0.1")!==(((je=x.http)==null?void 0:je.host)??x.host??"127.0.0.1")||((Ne=u.https)==null?void 0:Ne.enabled)!==((we=x.https)==null?void 0:we.enabled)||((Ce=u.https)==null?void 0:Ce.port)!==((Pe=x.https)==null?void 0:Pe.port)||(((ke=u.https)==null?void 0:ke.host)??u.host??"127.0.0.1")!==(((Se=x.https)==null?void 0:Se.host)??x.host??"127.0.0.1")||((Re=u.https)==null?void 0:Re.keyPath)!==((Ee=x.https)==null?void 0:Ee.keyPath)||((Le=u.https)==null?void 0:Le.certPath)!==((Ae=x.https)==null?void 0:Ae.certPath)||Fe((Te=u.https)==null?void 0:Te.caPath)!==Fe((Me=x.https)==null?void 0:Me.caPath);s({title:t(gt?"settings.toast.protocolRestartRequired":"settings.toast.saveSuccess"),variant:"success"}),a.refetch()}catch(D){s({title:t("settings.toast.saveFailure",{message:D instanceof Error?D.message:"unknown"}),variant:"error"})}finally{ie(!1)}}},[u,a,c,s,t,pe]),z=d.useCallback(()=>{u&&(F(te(u)),I({}))},[u]),G=d.useCallback(async()=>{if(me()){ue(!0);try{const n={enabled:g.enabled,username:g.username.trim()||void 0};g.password&&(n.password=g.password);const h=await y.mutateAsync(n);h.auth&&(de(h.auth),H({enabled:h.auth.enabled,username:h.auth.username??"",password:"",confirmPassword:""}),K({})),p.refetch()}catch{}finally{ue(!1)}}},[g,p,y,me]),$=d.useCallback(()=>{b&&(H(se(b)),K({}))},[b]),at=d.useCallback(async()=>{W&&await _(),Q&&await G()},[G,_,Q,W]),nt=d.useCallback(()=>{z(),$()},[$,z]),lt=d.useCallback(async()=>{if(!N){s({title:t("settings.toast.copyFailure",{message:t("settings.file.unknown")}),variant:"error"});return}try{await St(N),s({title:t("settings.toast.copySuccess"),variant:"success"})}catch(n){s({title:t("settings.toast.copyFailure",{message:n instanceof Error?n.message:"unknown"}),variant:"error"})}},[N,s,t]),ot=d.useCallback(async()=>{re(!0);try{await A.mutateAsync()}catch{}finally{re(!1)}},[A]),it=d.useCallback(async()=>{ce(!0);try{await T.mutateAsync()}catch{}finally{ce(!1)}},[T]),U=a.isPending||!u&&a.isFetching;return d.useEffect(()=>{if(U)return;const n=Array.from(m.current.values());if(n.length===0)return;const h=new IntersectionObserver(v=>{for(const w of v)if(w.isIntersecting){o(w.target.id);break}},{rootMargin:"-80px 0px -60% 0px",threshold:0});for(const v of n)h.observe(v);return()=>h.disconnect()},[U]),{activeSection:r,authErrors:Ue,authForm:g,authQuery:p,authSettings:b,clearingAll:Qe,cleaning:Je,config:u,configPath:N,configQuery:a,confirmCleanupOpen:_e,confirmClearAllOpen:Ge,defaultsSummary:Ye,errors:Ie,form:c,handleAuthReset:$,handleAuthSave:G,handleCleanupLogs:ot,handleClearAllLogs:it,handleCopyPath:lt,handleInputChange:st,handleReset:z,handleResetAll:nt,handleSave:_,handleSaveAll:at,handleSectionClick:l,isAuthDirty:Q,isConfigDirty:W,isLoading:U,needsPassword:et,protocolSummaryLabel:Ze,protocolChangesPending:tt,saving:We,savingAuth:Xe,sectionRefs:m,setAuthForm:H,setConfirmCleanupOpen:ze,setConfirmClearAllOpen:$e,setErrors:I,setForm:F,setSectionRef:i,t}}function ss(){const{t}=P(),s=Ht(),r=Number(s.isConfigDirty)+Number(s.isAuthDirty);return e.jsxs("div",{className:"flex flex-col gap-6",children:[e.jsx(bt,{info:r>0?e.jsx("span",{className:"rounded-lg bg-warning-bg px-2.5 py-1 text-xs font-medium text-warning",children:t("settings.overview.unsavedCount",{count:r})}):null,status:s.config?e.jsx("span",{className:"text-xs text-muted-foreground",children:s.protocolChangesPending?t("settings.protocol.restartWarning"):t("common.status.success")}):null,actions:null}),s.isLoading?e.jsx(Ve,{label:t("common.loading")}):s.config?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-6 xl:grid-cols-[200px_1fr]",children:[e.jsx(Et,{activeSection:s.activeSection,onSelectSection:s.handleSectionClick}),e.jsxs("div",{className:"flex flex-col gap-6",children:[e.jsx(Lt,{defaultsSummary:s.defaultsSummary,errors:s.errors,form:s.form,onInputChange:s.handleInputChange,onSetForm:s.setForm,sectionRef:s.setSectionRef("section-basics")}),e.jsx(At,{errors:s.errors,form:s.form,onSetForm:s.setForm,protocolChangesPending:s.protocolChangesPending,sectionRef:s.setSectionRef("section-protocol")}),e.jsx(Tt,{authErrors:s.authErrors,authForm:s.authForm,authLoading:s.authQuery.isPending||!s.authSettings&&s.authQuery.isFetching,authSettings:s.authSettings,needsPassword:s.needsPassword,onSetAuthForm:s.setAuthForm,sectionRef:s.setSectionRef("section-security")}),e.jsx(Mt,{configPath:s.configPath,onCopyPath:()=>void s.handleCopyPath(),sectionRef:s.setSectionRef("section-config-file")}),e.jsx(Ot,{cleaning:s.cleaning,clearingAll:s.clearingAll,onOpenCleanup:()=>s.setConfirmCleanupOpen(!0),onOpenClearAll:()=>s.setConfirmClearAllOpen(!0),sectionRef:s.setSectionRef("section-cleanup")})]})]}),e.jsx(Ft,{dirtyCount:r,protocolChangesPending:s.protocolChangesPending,onReset:s.handleResetAll,onSave:()=>void s.handleSaveAll(),saving:s.saving||s.savingAuth})]}):e.jsx(k,{children:e.jsx(L,{className:"pt-6",children:e.jsx("p",{className:"text-sm font-medium text-destructive",children:t("settings.toast.missingConfig")})})}),e.jsx(He,{open:s.confirmCleanupOpen,onOpenChange:o=>{!o&&!s.cleaning&&s.setConfirmCleanupOpen(!1)},title:t("settings.cleanup.confirmTitle"),description:t("settings.cleanup.confirmDescription"),confirmLabel:s.cleaning?t("common.actions.cleaning"):t("common.actions.cleanup"),cancelLabel:t("common.actions.cancel"),loading:s.cleaning,onConfirm:async()=>{await s.handleCleanupLogs(),s.setConfirmCleanupOpen(!1)}}),e.jsx(He,{open:s.confirmClearAllOpen,onOpenChange:o=>{!o&&!s.clearingAll&&s.setConfirmClearAllOpen(!1)},title:t("settings.cleanup.clearAllTitle"),description:t("settings.cleanup.clearAllWarning"),confirmLabel:s.clearingAll?t("settings.cleanup.clearingAll"):t("settings.cleanup.clearAll"),cancelLabel:t("common.actions.cancel"),loading:s.clearingAll,onConfirm:async()=>{await s.handleClearAllLogs(),s.setConfirmClearAllOpen(!1)}})]})}export{ss as default};
@@ -0,0 +1,2 @@
1
+ import{j as e,$ as he,ak as Q,r as d}from"./vendor-CITafuNQ.js";import{B as h,t as z,L as ge}from"./app-Citq5KW4.js";import{C as ve,b as ye,d as fe,e as je,a as Se}from"./card-D4YOc5eB.js";import{u as Ce,B as Ne,M as be,C as ke,T as Re,n as Ke,g as Pe,m as we,S as Me}from"./useProviderForm-DZEYuRhD.js";import{L as C,I as R}from"./label-DSVzZIex.js";import{u as Te,E as Ee}from"./shared-Cuakym23.js";import{u as N}from"./i18n-PeX9kBVO.js";import{S as Ae,a as Ie,b as He,c as Oe,d as Fe}from"./select-sOwKYsgI.js";import{a as $e}from"./apiKeys-k1jIJuDa.js";import{g as G}from"./gateway-i49olSPp.js";import{c as Le}from"./clipboard-BnAnBk_-.js";import{u as Ue}from"./router-BoBrmro7.js";import"./global-BCehxTGJ.js";import"./query-DZF7K6hv.js";import"./radix-Bux_1C5J.js";import"./disclosure-l5qsWhr7.js";import"./switch-7PH_rDz6.js";import"./badge-DpUlf_NW.js";function Be({state:c}){const{t}=N(),r=Te(),{keyName:s,setKeyName:n,keyEndpoints:l,setKeyEndpoints:p,keyMaxConcurrency:x,setKeyMaxConcurrency:g,creatingKey:u,createdKey:m,createApiKey:y,copyCreatedKey:i}=c;return m?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-lg bg-success-bg text-success",children:e.jsx(he,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsx("p",{className:"text-sm font-semibold",children:t("apiKeys.keyCreated")})]}),e.jsx("p",{className:"text-sm font-medium text-warning",children:t("apiKeys.saveKeyWarning")}),e.jsx("div",{className:"break-all rounded-lg border border-border bg-secondary px-4 py-3 font-mono text-sm",children:m.key}),e.jsx("div",{children:e.jsxs(h,{type:"button",onClick:()=>void i(m.key),children:[e.jsx(Q,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),t("common.actions.copy")]})})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(C,{htmlFor:"setupKeyName",children:[t("apiKeys.keyNamePlaceholder")," *"]}),e.jsx(R,{id:"setupKeyName",value:s,onChange:f=>n(f.target.value),placeholder:t("apiKeys.keyNamePlaceholder")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(C,{children:t("apiKeys.allowedEndpoints")}),e.jsx(Ee,{available:r,selected:l,onChange:p,hint:t("apiKeys.selectEndpoints")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(C,{htmlFor:"setupMaxConcurrency",children:t("apiKeys.maxConcurrency")}),e.jsx(R,{id:"setupMaxConcurrency",type:"number",min:"0",value:x,onChange:f=>g(f.target.value),placeholder:t("apiKeys.maxConcurrencyPlaceholder")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t("apiKeys.maxConcurrencyHelper")})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(h,{type:"button",onClick:()=>void y(),disabled:u||s.trim().length===0,children:t(u?"setup.steps.apiKey.creating":"setup.steps.apiKey.create")})})]})}function De({existingProviderIds:c,saving:t,onSave:r}){const{t:s}=N(),n=Ce({mode:"create",existingProviderIds:c}),l={form:n.form,errors:n.errors,isCreate:!0,advancedOpen:n.advancedOpen,onAdvancedOpenChange:n.setAdvancedOpen,idInputRef:n.providerIdRef,onProviderIdChange:n.handleProviderIdChange,onFieldChange:n.handleFieldChange,onTypeChange:n.handleTypeChange,onAuthModeChange:n.handleAuthModeChange,onNonStreamViaStreamChange:n.handleProviderNonStreamViaStreamChange,onUseAbsoluteUrlChange:n.handleUseAbsoluteUrlChange,onAddHeader:n.handleAddHeader,onRemoveHeader:n.handleRemoveHeader,onHeaderChange:n.handleHeaderChange,onModelIdChange:n.handleModelIdChange,onModelChange:n.handleModelChange,onAddModel:n.handleAddModel,onRemoveModel:n.handleRemoveModel,onModelNonStreamViaStreamChange:n.handleModelNonStreamViaStreamChange,onSetDefaultModel:n.handleSetDefaultModel},p=()=>{n.validate()&&r(n.serialize())};return e.jsxs("div",{className:"space-y-8",children:[e.jsx(Ne,{...l}),e.jsx(be,{...l}),e.jsx("div",{className:"flex justify-end",children:e.jsx(h,{type:"button",onClick:p,disabled:t,children:s(t?"common.actions.saving":"setup.steps.provider.saveAndContinue")})})]})}function _e({state:c,onSaved:t}){const{t:r}=N(),{providers:s,setupProvider:n,setSetupProviderId:l,savingProvider:p,saveProvider:x}=c,[g,u]=d.useState(null),m=g??s.length===0,y=i=>{x(i).then(f=>{f&&t()})};return e.jsxs("div",{className:"space-y-6",children:[s.length>0?e.jsxs("div",{className:"space-y-3 rounded-xl bg-secondary/50 p-4",children:[e.jsx("p",{className:"text-sm font-semibold",children:r("setup.steps.provider.existingTitle",{count:s.length})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:r("setup.steps.provider.existingHint")}),e.jsxs(C,{className:"flex flex-col gap-2 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:r("setup.steps.provider.chooseLabel")}),e.jsxs(Ae,{value:(n==null?void 0:n.id)??"",onValueChange:l,children:[e.jsx(Ie,{children:e.jsx(He,{})}),e.jsx(Oe,{children:s.map(i=>e.jsx(Fe,{value:i.id,children:i.label||i.id},i.id))})]})]})]}):null,m?e.jsx(De,{existingProviderIds:s.map(i=>i.id),saving:p,onSave:y}):e.jsx("div",{children:e.jsx(h,{type:"button",variant:"outline",onClick:()=>u(!0),children:r("setup.steps.provider.addAnother")})}),m&&s.length>0?e.jsx("div",{children:e.jsx(h,{type:"button",variant:"ghost",size:"sm",onClick:()=>u(!1),children:r("setup.steps.provider.backToList")})}):null]})}const Ve=ke.slice(0,3);function qe({state:c}){const{t}=N(),{setupProvider:r,anthropicRoutes:s,routeSource:n,setRouteSource:l,routeTarget:p,setRouteTarget:x,savingRoute:g,saveDefaultRoute:u}=c,m=Object.entries(s),y=!!r&&n.trim().length>0&&p.trim().length>0&&!g;return e.jsxs("div",{className:"space-y-6",children:[m.length>0?e.jsxs("section",{className:"space-y-3","aria-labelledby":"setup-existing-routes",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{id:"setup-existing-routes",className:"text-sm font-semibold",children:t("setup.steps.routing.existingTitle")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t("setup.steps.routing.existingHint")})]}),e.jsx("div",{className:"divide-y divide-border rounded-xl border border-border",children:m.map(([i,f])=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 px-4 py-2.5 text-xs",children:[e.jsx("code",{className:"font-mono text-foreground",children:i}),e.jsxs("code",{className:"font-mono text-muted-foreground",children:["→ ",f]})]},i))})]}):e.jsx("p",{className:"rounded-xl bg-secondary/50 px-4 py-3 text-xs text-muted-foreground",children:t("setup.steps.routing.emptyHint")}),e.jsxs("section",{className:"space-y-4","aria-labelledby":"setup-new-route",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs(C,{className:"flex flex-col gap-2 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:t("setup.steps.routing.sourceLabel")}),e.jsx(R,{value:n,onChange:i=>l(i.target.value)})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:Ve.map(i=>e.jsx(h,{type:"button",variant:"outline",size:"sm",className:"h-7 rounded-md px-2.5 text-[11px] font-normal",onClick:()=>l(i),children:i},i))}),e.jsx("p",{className:"text-xs leading-5 text-muted-foreground",children:t("setup.steps.routing.sourceHint")})]}),e.jsxs(C,{className:"flex flex-col gap-2 text-sm",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:t("setup.steps.routing.targetLabel")}),e.jsx(R,{value:p,onChange:i=>x(i.target.value)})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(h,{type:"button",onClick:()=>void u(),disabled:!y,children:t(g?"setup.steps.routing.saving":"setup.steps.routing.save")})})]})]})}function ze({state:c}){const{t}=N(),{setupProvider:r,testingProvider:s,testResult:n,testSetupProvider:l,anthropicBaseUrl:p,createdKey:x,copyCreatedKey:g}=c;if(!r)return e.jsx("p",{className:"rounded-xl bg-secondary/50 px-4 py-3 text-xs text-muted-foreground",children:t("setup.steps.verify.noProvider")});const u=[`export ANTHROPIC_BASE_URL=${p}`,`export ANTHROPIC_API_KEY=${(x==null?void 0:x.key)??"<your-api-key>"}`].join(`
2
+ `);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("section",{className:"space-y-3","aria-labelledby":"setup-verify-connection",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{id:"setup-verify-connection",className:"text-sm font-semibold",children:t("workbench.drawer.verifyTitle")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t("setup.steps.verify.testingProvider",{name:r.label||r.id})})]}),e.jsxs("div",{className:"space-y-3 rounded-xl border border-transparent bg-card p-4 shadow-[var(--surface-shadow)]",children:[e.jsx(h,{type:"button",variant:"outline",size:"sm",onClick:()=>void l(),disabled:s,children:t(s?"common.actions.testingConnection":"workbench.drawer.verifyRun")}),n?e.jsx(Re,{result:n}):null]})]}),e.jsxs("section",{className:"space-y-3","aria-labelledby":"setup-verify-first-request",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{id:"setup-verify-first-request",className:"text-sm font-semibold",children:t("setup.steps.verify.envTitle")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t("setup.steps.verify.envHint")})]}),e.jsx("pre",{className:"overflow-x-auto rounded-lg border border-border bg-secondary px-4 py-3 font-mono text-xs",children:u}),e.jsx("div",{children:e.jsxs(h,{type:"button",variant:"outline",size:"sm",onClick:()=>void g(u),children:[e.jsx(Q,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),t("common.actions.copy")]})})]})]})}const b=["provider","routing","apiKey","verify"];function Ge(){var U;const c=Ke(),{t,pushToast:r,config:s,setConfig:n,configQuery:l,customEndpoints:p,ensureConfig:x}=c,g=Ue(),[u,m]=d.useState(0),[y,i]=d.useState(null),[f,T]=d.useState(!1),[E,W]=d.useState(""),[Y,J]=d.useState(null),[X,A]=d.useState(!1),[K,Z]=d.useState(""),[P,ee]=d.useState(["anthropic"]),[I,te]=d.useState(""),[se,H]=d.useState(!1),[O,ne]=d.useState(null),[ae,F]=d.useState(!1),[re,w]=d.useState(null),S=d.useMemo(()=>(s==null?void 0:s.providers)??[],[s]),j=d.useMemo(()=>S.find(a=>a.id===y)??S[0]??null,[S,y]),M=d.useMemo(()=>s?Pe(s,p,"anthropic"):{},[s,p]),$=Object.keys(M).length,oe=d.useMemo(()=>{var o,v;if(!j)return"";const a=j.defaultModel??((v=(o=j.models)==null?void 0:o.find(k=>k.id.trim().length>0))==null?void 0:v.id);return a?`${j.id}:${a}`:`${j.id}:*`},[j]),L=Y??oe,ie=async a=>{if(!s||!x())return!1;const o={...s,providers:[...S,a]};T(!0);try{return await G.saveConfig(o),n(o),l.refetch(),i(a.id),r({title:t("providers.toast.createSuccess",{name:a.label||a.id}),variant:"success"}),!0}catch(v){return r({title:t("providers.drawer.toast.saveFailure",{message:v instanceof Error?v.message:"unknown"}),variant:"error"}),!1}finally{T(!1)}},ce=async()=>{var B,D,_,V;if(!s||!x())return;const a=E.trim(),o=L.trim();if(!a||!o)return;const v={...M,[a]:o},k={...s,endpointRouting:{...s.endpointRouting??{},anthropic:{defaults:((D=(B=s.endpointRouting)==null?void 0:B.anthropic)==null?void 0:D.defaults)??s.defaults,modelRoutes:v,compatibility:(V=(_=s.endpointRouting)==null?void 0:_.anthropic)==null?void 0:V.compatibility}},modelRoutes:v};A(!0);try{await G.saveConfig(k),n(k),l.refetch(),r({title:t("modelManagement.toast.routesSaved"),variant:"success"})}catch(q){r({title:t("modelManagement.toast.routesSaveFailure",{message:q instanceof Error?q.message:"unknown"}),variant:"error"})}finally{A(!1)}},de=async()=>{if(!K.trim()){r({title:t("apiKeys.errors.nameRequired"),variant:"error"});return}const a=I.trim();if(a&&(!Number.isInteger(Number(a))||Number(a)<1)){r({title:t("apiKeys.errors.maxConcurrencyInvalid"),variant:"error"});return}H(!0);try{const o=await $e.create({name:K.trim(),allowedEndpoints:P.length>0?P:void 0,maxConcurrency:a?Number(a):null});ne(o)}catch(o){const v=z(o);r({title:t("setup.steps.apiKey.createFailed",{message:v.message}),variant:"error"})}finally{H(!1)}},le=async a=>{try{await Le(a),r({title:t("apiKeys.toast.keyCopied"),variant:"success"})}catch(o){r({title:t("apiKeys.toast.copyFailure"),description:o instanceof Error?o.message:t("common.unknownError"),variant:"error"})}},ue=async()=>{if(j){F(!0);try{const a=await we.testProvider(j.id);if(a.ok){w({ok:!0,status:a.status,statusText:a.statusText,durationMs:a.durationMs,testedAt:Date.now()});return}w({ok:!1,status:a.status,statusText:a.statusText,durationMs:a.durationMs,message:`${a.status} ${a.statusText}`,testedAt:Date.now()})}catch(a){const o=z(a);w({ok:!1,status:o.status,message:o.status?`${o.status} ${o.message}`:o.message,testedAt:Date.now()})}finally{F(!1)}}},pe=`http://127.0.0.1:${((U=s==null?void 0:s.http)==null?void 0:U.port)??(s==null?void 0:s.port)??4100}/anthropic`,me=b[u],xe={provider:S.length>0,routing:$>0,apiKey:O!==null,verify:!0};return{...c,stepIndex:u,activeStep:me,canProceed:xe,goNext:()=>{m(a=>Math.min(a+1,b.length-1))},goBack:()=>{m(a=>Math.max(a-1,0))},goToStep:a=>{const o=b.indexOf(a);o>=0&&o<=u&&m(o)},finish:()=>{g("/")},providers:S,setupProvider:j,setupProviderId:y,setSetupProviderId:i,savingProvider:f,saveProvider:ie,anthropicRoutes:M,anthropicRouteCount:$,routeSource:E,setRouteSource:W,routeTarget:L,setRouteTarget:J,savingRoute:X,saveDefaultRoute:ce,keyName:K,setKeyName:Z,keyEndpoints:P,setKeyEndpoints:ee,keyMaxConcurrency:I,setKeyMaxConcurrency:te,creatingKey:se,createdKey:O,createApiKey:de,copyCreatedKey:le,testingProvider:ae,testResult:re,testSetupProvider:ue,anthropicBaseUrl:pe}}function vt(){const{t:c}=N(),t=Ge();if(t.configQuery.isPending&&!t.config)return e.jsx(ge,{});const r=b.map((n,l)=>({id:n,label:c(`setup.steps.${n}.navLabel`),status:l<t.stepIndex?"complete":l===t.stepIndex?"current":"upcoming"})),s=t.stepIndex===b.length-1;return e.jsxs("div",{className:"mx-auto flex w-full max-w-3xl flex-col gap-6",children:[e.jsxs("header",{className:"space-y-1.5",children:[e.jsx("h1",{className:"text-xl font-semibold tracking-[-0.02em]",children:c("setup.title")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c("setup.description")})]}),e.jsx(Me,{steps:r,current:t.activeStep,onSelect:t.goToStep}),e.jsxs(ve,{children:[e.jsxs(ye,{children:[e.jsx(fe,{children:c(`setup.steps.${t.activeStep}.title`)}),e.jsx(je,{children:c(`setup.steps.${t.activeStep}.description`)})]}),e.jsxs(Se,{children:[t.activeStep==="provider"?e.jsx(_e,{state:t,onSaved:t.goNext}):null,t.activeStep==="routing"?e.jsx(qe,{state:t}):null,t.activeStep==="apiKey"?e.jsx(Be,{state:t}):null,t.activeStep==="verify"?e.jsx(ze,{state:t}):null]})]}),e.jsxs("footer",{className:"flex items-center justify-between",children:[e.jsx(h,{type:"button",variant:"outline",onClick:t.goBack,disabled:t.stepIndex===0,children:c("common.actions.previous")}),s?e.jsx(h,{type:"button",onClick:t.finish,children:c("setup.actions.finish")}):e.jsx(h,{type:"button",onClick:t.goNext,disabled:!t.canProceed[t.activeStep],children:c("common.actions.next")})]})]})}export{vt as default};
@@ -0,0 +1 @@
1
+ import{r,i as s,d as t}from"./app-Citq5KW4.js";const i={listRequest(){return{url:"/api/keys",method:"GET"}},overviewRequest(e){return{url:"/api/stats/api-keys/overview",method:"GET",params:{days:e}}},usageRequest(e,a=10){return{url:"/api/stats/api-keys/usage",method:"GET",params:{days:e,limit:a}}},customEndpointOptionsRequest(){return{url:"/api/custom-endpoints",method:"GET"}},create:async e=>s(t.post("/api/keys",e)),update:async(e,a)=>{await s(t.patch(`/api/keys/${e}`,a))},delete:async e=>{await s(t.delete(`/api/keys/${e}`))},reveal:async e=>r({url:`/api/keys/${e}/reveal`,method:"GET"})};export{i as a};