@chenpu17/cc-gw 0.8.28 → 0.8.30

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 (84) hide show
  1. package/package.json +5 -5
  2. package/src/cli/dist/index.js +15 -1
  3. package/src/web/dist/assets/About-CGQXnQXw.js +1 -0
  4. package/src/web/dist/assets/ApiKeys-Cse0CWpH.js +1 -0
  5. package/src/web/dist/assets/{ConfirmDialog-BKK6xsPe.js → ConfirmDialog-VrbumD7j.js} +1 -1
  6. package/src/web/dist/assets/Dashboard-CtOgjfmM.js +1 -0
  7. package/src/web/dist/assets/{DialogShell-C0YGDw-Y.js → DialogShell-TRFN3c58.js} +1 -1
  8. package/src/web/dist/assets/EChart-CZqGiync.js +1 -0
  9. package/src/web/dist/assets/Events-C14a-qPg.js +1 -0
  10. package/src/web/dist/assets/Help-BiuR792b.js +4 -0
  11. package/src/web/dist/assets/Login-B-xiAusP.js +1 -0
  12. package/src/web/dist/assets/Logs-oNopHEDO.js +1 -0
  13. package/src/web/dist/assets/PageSection-D1vbxAKK.js +1 -0
  14. package/src/web/dist/assets/{PageState-B8pYAtQ5.js → PageState-CPKqNFG7.js} +1 -1
  15. package/src/web/dist/assets/{PageToolbar-DATSQ0uI.js → PageToolbar-DzpjQ7SY.js} +1 -1
  16. package/src/web/dist/assets/ProvidersWorkbench-B5g4UvTf.js +1 -0
  17. package/src/web/dist/assets/Settings-CPpQt_UL.js +1 -0
  18. package/src/web/dist/assets/Setup-DNJ1W4sK.js +2 -0
  19. package/src/web/dist/assets/apiKeys-Dl_vgy_U.js +1 -0
  20. package/src/web/dist/assets/app-CeLCVbqy.js +61 -0
  21. package/src/web/dist/assets/card-DS9KKz-k.js +1 -0
  22. package/src/web/dist/assets/{charts-core-CK8TVJro.js → charts-core-CAVUzIcU.js} +1 -1
  23. package/src/web/dist/assets/{charts-engine-CWjgwbj5.js → charts-engine-BRCKiVl4.js} +1 -1
  24. package/src/web/dist/assets/{charts-react-CmmN-08P.js → charts-react-B-D6Gq0w.js} +1 -1
  25. package/src/web/dist/assets/disclosure-CqU8C-ET.js +1 -0
  26. package/src/web/dist/assets/{gateway-0dI95Pk4.js → gateway-Bt6lPuXq.js} +1 -1
  27. package/src/web/dist/assets/global-B1Xg1dWA.css +1 -0
  28. package/src/web/dist/assets/{global-DA-0y145.js → global-zt8jbW7F.js} +1 -1
  29. package/src/web/dist/assets/{i18n-C8tBby0x.js → i18n-DWfLgqoF.js} +1 -1
  30. package/src/web/dist/assets/label-CWq3wWgE.js +1 -0
  31. package/src/web/dist/assets/landing-D6Ek28oa.js +17 -0
  32. package/src/web/dist/assets/metric-card-CueQ0u3Z.js +1 -0
  33. package/src/web/dist/assets/package-CdOrNWtP.js +1 -0
  34. package/src/web/dist/assets/popover-0fHMO-3Y.js +1 -0
  35. package/src/web/dist/assets/{query-QCek5MsK.js → query-CZuclkQv.js} +1 -1
  36. package/src/web/dist/assets/queryKeys-BlGm18Nk.js +1 -0
  37. package/src/web/dist/assets/radix-OaJStcH-.js +5 -0
  38. package/src/web/dist/assets/router-C1-ppOz7.js +19 -0
  39. package/src/web/dist/assets/segmented-control-do2mQidJ.js +1 -0
  40. package/src/web/dist/assets/select-CxIEo3DN.js +1 -0
  41. package/src/web/dist/assets/shared-fOyVvn5H.js +1 -0
  42. package/src/web/dist/assets/{switch-W7ZoAE3i.js → switch-B2cQk2bS.js} +1 -1
  43. package/src/web/dist/assets/table-BxCEZcKF.js +1 -0
  44. package/src/web/dist/assets/tabs-BOjStrRw.js +1 -0
  45. package/src/web/dist/assets/useAppMutation-DY1JJByx.js +1 -0
  46. package/src/web/dist/assets/useEventStream-DeEWwZq0.js +1 -0
  47. package/src/web/dist/assets/useProviderForm-DlALMLaD.js +1 -0
  48. package/src/web/dist/assets/utils-DrKJJFzS.js +3 -0
  49. package/src/web/dist/assets/vendor-m8O77Czp.js +390 -0
  50. package/src/web/dist/index.html +8 -8
  51. package/src/web/dist/landing.html +5 -5
  52. package/src/web/dist/assets/About-BKiMaHb0.js +0 -1
  53. package/src/web/dist/assets/ApiKeys-BTcIIgmL.js +0 -1
  54. package/src/web/dist/assets/Dashboard-B3kEUYKY.js +0 -1
  55. package/src/web/dist/assets/Events-BH7AnRJM.js +0 -1
  56. package/src/web/dist/assets/Help-BvQpcGeD.js +0 -4
  57. package/src/web/dist/assets/Login-B44jDA1h.js +0 -1
  58. package/src/web/dist/assets/Logs-CtJDEq1D.js +0 -1
  59. package/src/web/dist/assets/ModelManagement-DuQUQprh.js +0 -1
  60. package/src/web/dist/assets/PageSection-D4eaagP4.js +0 -1
  61. package/src/web/dist/assets/Profiler-aNY5CbJF.js +0 -1
  62. package/src/web/dist/assets/RoutingManagement-BU_t7qZ5.js +0 -1
  63. package/src/web/dist/assets/Settings-DYNFf-x2.js +0 -1
  64. package/src/web/dist/assets/Skeleton-9Z0ltPLO.js +0 -1
  65. package/src/web/dist/assets/app-D2luR0w8.js +0 -61
  66. package/src/web/dist/assets/card-DPI7HeM2.js +0 -1
  67. package/src/web/dist/assets/global-DvELjyJN.css +0 -1
  68. package/src/web/dist/assets/input-CRm3Lt3O.js +0 -1
  69. package/src/web/dist/assets/label-D0KXM_V7.js +0 -1
  70. package/src/web/dist/assets/landing-CF3whjCU.js +0 -17
  71. package/src/web/dist/assets/live-en-events-DJwaP-WW.png +0 -0
  72. package/src/web/dist/assets/live-events-D_njD291.png +0 -0
  73. package/src/web/dist/assets/package-DglEFv2B.js +0 -1
  74. package/src/web/dist/assets/popover-DVsRdElU.js +0 -1
  75. package/src/web/dist/assets/queryKeys-DLyolp-A.js +0 -1
  76. package/src/web/dist/assets/radix-C0Bt6n-I.js +0 -5
  77. package/src/web/dist/assets/router-D2Fb4U0L.js +0 -19
  78. package/src/web/dist/assets/select-C4IDwhTu.js +0 -1
  79. package/src/web/dist/assets/table-BGY9lGZo.js +0 -1
  80. package/src/web/dist/assets/useApiQuery-B4UkNdxl.js +0 -1
  81. package/src/web/dist/assets/useAppMutation-CT0ETbRx.js +0 -1
  82. package/src/web/dist/assets/useModelManagementState-CO7s8w5p.js +0 -1
  83. package/src/web/dist/assets/utils-DNPbJsD2.js +0 -3
  84. package/src/web/dist/assets/vendor-DdPBfMMb.js +0 -437
@@ -0,0 +1 @@
1
+ import{r as f,j as e,au as Et,aq as it,a9 as Ee,N as Dt,Z as Nt,ah as Rt,av as wt,aw as Tt,ax as Ot,ay as Lt}from"./vendor-m8O77Czp.js";import{c as It}from"./router-C1-ppOz7.js";import{C as Ft}from"./ConfirmDialog-VrbumD7j.js";import{P as At}from"./PageToolbar-DzpjQ7SY.js";import{t as je,d as Ge,B,b as Bt,s as Ht,T as $t,e as zt,f as Ut,g as qt}from"./app-CeLCVbqy.js";import{q as De,B as X,u as Vt}from"./queryKeys-BlGm18Nk.js";import{c as Re}from"./global-zt8jbW7F.js";import{d as gt,g as ft,a as bt,b as _t,c as vt,e as jt,r as Kt,f as Ke,m as st,h as Qt,i as Gt,T as Wt,u as Jt,P as dt,j as Xt,k as Fe,S as Yt,B as Zt,M as es,l as ts,C as ss,O as as,n as kt,o as ns,p as rs}from"./useProviderForm-DlALMLaD.js";import{u as os}from"./query-CZuclkQv.js";import{g as Ae}from"./gateway-Bt6lPuXq.js";import{u as at}from"./useAppMutation-DY1JJByx.js";import{D as Be,A as He,a as $e,b as ze,c as Ue,d as qe,e as Ve}from"./DialogShell-TRFN3c58.js";import{L as ue,I as Ce}from"./label-CWq3wWgE.js";import{S as ct,a as mt,b as ut,c as pt,d as Qe}from"./select-CxIEo3DN.js";import{S as xt}from"./switch-B2cQk2bS.js";import{u as me}from"./i18n-DWfLgqoF.js";import{C as nt,a as rt}from"./card-DS9KKz-k.js";import{a as ht}from"./PageState-CPKqNFG7.js";import{T as Ct,a as Pt,b as ot,c as ie,d as St,e as de}from"./table-BxCEZcKF.js";import{D as Ze}from"./disclosure-CqU8C-ET.js";import{P as ls,c as is,b as ds}from"./popover-0fHMO-3Y.js";import"./radix-OaJStcH-.js";function cs(i){const{t:n,pushToast:p,config:s,setConfig:t,configQuery:y,customEndpoints:g,tabs:C,ensureConfig:w}=i,l=os(),[o,c]=f.useState({}),[d,b]=f.useState({}),[N,x]=f.useState(null),[P,h]=f.useState({}),[v,R]=f.useState({}),[L,q]=f.useState({}),[Y,k]=f.useState(null),[F,V]=f.useState(null),[se,Z]=f.useState(null),[ae,I]=f.useState(!1),[U,ne]=f.useState({}),[he,xe]=f.useState(null),[E,u]=f.useState({}),[$,fe]=f.useState(null),ee=f.useRef(null),[Pe,be]=f.useState(null),J=a=>{ee.current=a,be(a)},O=()=>{ee.current=null,be(null)},K=f.useMemo(()=>C.filter(a=>a.key!=="providers"),[C]);f.useEffect(()=>{if(!y.data)return;const a=y.data;c(m=>{const r=gt(a,g);if(!m||Object.keys(m).length===0)return r;const j={...r};for(const[T,A]of Object.entries(m)){if(!(T in r))continue;const H=ft(a,g,T);if(bt(A,H))j[T]=A;else{const le=new Map(A.map(Q=>[Q.source,Q.id]));j[T]=r[T].map(Q=>({...Q,id:le.get(Q.source)??Q.id}))}}return j}),u(m=>{const r=_t(a,g);if(!m||Object.keys(m).length===0)return r;const j={...r};for(const[T,A]of Object.entries(m)){if(!(T in r))continue;const H=vt(a,g,T);JSON.stringify(A)!==JSON.stringify(H)&&(j[T]=A)}return j}),b({}),h(jt(a,g))},[y.data,g]);const re=(s==null?void 0:s.providers)??[],ye=f.useMemo(()=>{const a=[],m=new Set;for(const r of re){const j=r.label&&r.label!==r.id?`${r.label} (${r.id})`:r.id,T=r.models??[];if(T.length>0)for(const H of T){const le=`${r.id}:${H.id}`;m.has(le)||(m.add(le),a.push({value:le,label:`${j} · ${H.label??H.id}`,providerId:r.id,providerLabel:j,modelId:H.id,modelLabel:H.label??H.id,kind:"model",isDefault:r.defaultModel===H.id}))}else if(r.defaultModel){const H=`${r.id}:${r.defaultModel}`;m.has(H)||(m.add(H),a.push({value:H,label:`${j} · ${r.defaultModel}`,providerId:r.id,providerLabel:j,modelId:r.defaultModel,modelLabel:r.defaultModel,kind:"model",isDefault:!0}))}const A=`${r.id}:*`;m.has(A)||(m.add(A),a.push({value:A,label:n("settings.routing.providerPassthroughOption",{provider:j}),providerId:r.id,providerLabel:j,modelId:"*",modelLabel:"*",kind:"passthrough"}))}for(const r of Object.values(o).flat()){const j=r.target.trim();j&&!m.has(j)&&(m.add(j),a.push({value:j,label:j,modelId:j,modelLabel:j,kind:"custom"}))}return a},[re,o,n]),Ne=a=>s?ft(s,g,a):{},_e=f.useMemo(()=>{const a={};for(const m of K){const r=o[m.key]||[];a[m.key]=bt(r,Ne(m.key))}return a},[s,g,o,K]),Te=f.useMemo(()=>{const a={};if(!s)return a;for(const m of K){const r=E[m.key];if(!r){a[m.key]=!1;continue}const j=vt(s,g,m.key);a[m.key]=JSON.stringify(r)!==JSON.stringify(j)}return a},[s,g,E,K]),We=(a,m,r)=>{u(j=>({...j,[a]:{...j[a]??{completion:null,reasoning:null,background:null,longContextThreshold:6e4},[m]:r}}))},Je=async a=>{var j,T,A,H,le,Q,G,ce;if(!w()||ee.current)return;const m=E[a];if(!m)return;const r={completion:(j=m.completion)!=null&&j.trim()?m.completion.trim():null,reasoning:(T=m.reasoning)!=null&&T.trim()?m.reasoning.trim():null,background:(A=m.background)!=null&&A.trim()?m.background.trim():null,longContextThreshold:Number.isFinite(m.longContextThreshold)&&m.longContextThreshold>0?Math.floor(m.longContextThreshold):s.defaults.longContextThreshold};fe(a),J(a);try{const te=g.find(W=>W.id===a);if(te){const W={...te.routing??{},defaults:r,modelRoutes:((H=te.routing)==null?void 0:H.modelRoutes)??{}};await Ge.update(a,{routing:W}),t(pe=>{if(!pe)return pe;const Ye=[...pe.customEndpoints??[]],lt=Ye.findIndex(Mt=>Mt.id===a);return lt===-1?pe:(Ye[lt]={...Ye[lt],routing:W},{...pe,customEndpoints:Ye})}),await l.invalidateQueries({queryKey:De.customEndpoints.all()})}else{const W=a,pe={...s,endpointRouting:{...s.endpointRouting??{},[W]:{defaults:r,modelRoutes:((Q=(le=s.endpointRouting)==null?void 0:le[W])==null?void 0:Q.modelRoutes)??(W==="anthropic"?s.modelRoutes??{}:{}),compatibility:(ce=(G=s.endpointRouting)==null?void 0:G[W])==null?void 0:ce.compatibility}}};await Ae.saveConfig(pe),t(pe)}u(W=>({...W,[a]:r})),p({title:n("workbench.defaults.saveSuccess"),variant:"success"}),y.refetch()}catch(te){p({title:n("workbench.defaults.saveFailure",{message:je(te).message}),variant:"error"})}finally{fe(null),O()}},D=(a,m)=>{h(r=>({...r,[a]:m})),t(r=>{if(!r)return r;if(a==="anthropic"||a==="openai")return{...r,routingPresets:{...r.routingPresets,[a]:m}};const j=[...r.customEndpoints??[]],T=j.findIndex(A=>A.id===a);return T===-1?r:(j[T]={...j[T],routingPresets:m},{...r,customEndpoints:j})})},z=(a,m)=>{R(r=>({...r,[a]:m})),m.trim()&&q(r=>({...r,[a]:null}))},M=async a=>{if(!w()||ee.current)return;const m=(v[a]??"").trim();if(!m){q(r=>({...r,[a]:n("modelManagement.validation.presetName")}));return}if((P[a]??[]).some(r=>r.name.toLowerCase()===m.toLowerCase())){q(r=>({...r,[a]:n("modelManagement.validation.presetDuplicate",{name:m})}));return}k(a),J(a);try{const j=(await st.savePreset(a,m)).presets??[];D(a,j),R(T=>({...T,[a]:""})),q(T=>({...T,[a]:null})),p({title:n("modelManagement.toast.presetSaved",{name:m}),variant:"success"})}catch(r){p({title:n("modelManagement.toast.presetSaveFailure",{message:je(r).message}),variant:"error"})}finally{k(null),O(),y.refetch()}},S=async(a,m)=>{if(w()&&!ee.current){V({endpoint:a,name:m.name}),J(a);try{const j=(await st.applyPreset(a,m.name)).config;t(j);const T=gt(j,g);c(A=>({...A,[a]:T[a]??[]})),h(jt(j,g)),a!=="anthropic"&&a!=="openai"&&await l.invalidateQueries({queryKey:De.customEndpoints.all()}),p({title:n("modelManagement.toast.presetApplySuccess",{name:m.name}),variant:"success"})}catch(r){p({title:n("modelManagement.toast.presetApplyFailure",{message:je(r).message}),variant:"error"})}finally{V(null),O(),y.refetch()}}},_=async(a,m)=>{if(w()&&!ee.current){Z({endpoint:a,name:m.name}),J(a);try{const r=await st.deletePreset(a,m.name);D(a,r.presets??[]),p({title:n("modelManagement.toast.presetDeleteSuccess",{name:m.name}),variant:"success"})}catch(r){p({title:n("modelManagement.toast.presetDeleteFailure",{message:je(r).message}),variant:"error"})}finally{Z(null),O(),y.refetch()}}},we=async a=>{const m=g.find(r=>r.id===a);if(!(!m||m.deletable===!1))try{await Ge.delete(a),await l.invalidateQueries({queryKey:De.customEndpoints.all()}),t(r=>r&&{...r,customEndpoints:(r.customEndpoints??[]).filter(j=>j.id!==a)}),y.refetch(),p({title:n("modelManagement.deleteEndpointSuccess"),variant:"success"})}catch(r){const j=je(r);p({title:n("modelManagement.deleteEndpointError",{error:j.message}),variant:"error"})}},Oe=a=>{c(m=>({...m,[a]:[...m[a]||[],{id:Ke(),source:"",target:""}]})),b(m=>({...m,[a]:null}))},Se=async(a,m)=>{if(w()&&!ee.current){I(!0),J(a);try{if(a==="anthropic"||a==="openai"){const r=a,j=s.endpointRouting?{...s.endpointRouting}:{},T=j[r]??{defaults:s.defaults,modelRoutes:(r==="anthropic"?s.modelRoutes:{})??{}},A={defaults:T.defaults??s.defaults,modelRoutes:T.modelRoutes??{}},H={...s,endpointRouting:{...j,[r]:m?{...A,compatibility:{enabled:!0}}:{...A}}};await Ae.saveConfig(H),t(H)}else{const r=[...s.customEndpoints??[]],j=r.findIndex(le=>le.id===a);if(j===-1)throw new Error(n("modelManagement.toast.endpointNotFound"));const T=r[j],A=T.routing??{defaults:s.defaults,modelRoutes:{}};r[j]={...T,routing:m?{...A,compatibility:{enabled:!0}}:{defaults:A.defaults,modelRoutes:A.modelRoutes}};const H={...s,customEndpoints:r};await Ae.saveConfig(H),t(H)}p({title:n("modelManagement.toast.compatibilitySaved",{state:n(m?"common.status.enabled":"common.status.disabled")}),variant:"success"}),y.refetch()}catch(r){const j=je(r);p({title:n("modelManagement.toast.compatibilitySaveFailure",{message:j.message}),variant:"error"})}finally{I(!1),O()}}},oe=(a,m)=>{c(r=>{const j=r[a]||[];return j.some(T=>T.source.trim()===m.trim())?r:{...r,[a]:[...j,{id:Ke(),source:m,target:""}]}}),b(r=>({...r,[a]:null}))},ke=(a,m,r,j)=>{c(T=>({...T,[a]:(T[a]||[]).map(A=>A.id===m?{...A,[r]:j}:A)})),b(T=>({...T,[a]:null}))},Le=(a,m)=>{c(r=>({...r,[a]:(r[a]||[]).filter(j=>j.id!==m)})),b(r=>({...r,[a]:null}))},Me=a=>{var r;if(!s)return;const m=(s.customEndpoints??g).find(j=>j.id===a);if(m)c(j=>{var T;return{...j,[a]:Object.entries(((T=m.routing)==null?void 0:T.modelRoutes)??{}).map(([A,H])=>({id:Ke(),source:A,target:H}))}});else{const j=s.endpointRouting??{},T=a,A=T==="anthropic"?s.modelRoutes??{}:{},H=((r=j[T])==null?void 0:r.modelRoutes)??A;c(le=>({...le,[a]:Object.entries(H).map(([Q,G])=>({id:Ke(),source:Q,target:G}))}))}b(j=>({...j,[a]:null}))},Ie=at({mutationFn:async a=>(await Ae.saveConfig(a.nextConfig),a)}),Xe=at({mutationFn:async a=>(await Ge.update(a.endpoint,{routing:a.routing}),a)});return{endpointTabs:K,routesByEndpoint:o,setRoutesByEndpoint:c,routeError:d,savingRouteFor:N,presetsByEndpoint:P,presetNameByEndpoint:v,presetErrorByEndpoint:L,savingPresetFor:Y,applyingPreset:F,deletingPreset:se,savingCompatibilityPolicy:ae,writingEndpoint:Pe,presetsExpanded:U,setPresetsExpanded:ne,presetDiffDialog:he,setPresetDiffDialog:xe,providerModelOptions:ye,isDirtyByEndpoint:_e,defaultsByEndpoint:E,isDefaultsDirtyByEndpoint:Te,savingDefaultsFor:$,handleDefaultsChange:We,handleSaveDefaults:Je,handlePresetNameChange:z,handleSavePreset:M,handleApplyPreset:S,handleDeletePreset:_,handleDeleteEndpoint:we,handleAddRoute:Oe,handleAddSuggestion:oe,handleRouteChange:ke,handleRemoveRoute:Le,handleResetRoutes:Me,handleSaveRoutes:async a=>{var j,T,A,H,le;if(!w()||ee.current)return;const m=o[a]||[],r={};for(const Q of m){const G=Q.source.trim(),ce=Q.target.trim();if(!(!G&&!ce)){if(!G||!ce){b(te=>({...te,[a]:n("settings.validation.routePair")}));return}if(r[G]){b(te=>({...te,[a]:n("settings.validation.routeDuplicate",{model:G})}));return}r[G]=ce}}b(Q=>({...Q,[a]:null})),x(a),J(a);try{const Q=g.find(G=>G.id===a);if(Q){const G={...Q.routing??{},modelRoutes:r,defaults:((j=Q.routing)==null?void 0:j.defaults)||s.defaults};await Xe.mutateAsync({endpoint:a,routing:G}),t(ce=>{if(!ce)return ce;const te=[...ce.customEndpoints??[]],W=te.findIndex(pe=>pe.id===a);return W===-1?ce:(te[W]={...te[W],routing:G},{...ce,customEndpoints:te})}),await l.invalidateQueries({queryKey:De.customEndpoints.all()})}else{const G={...s,endpointRouting:{...s.endpointRouting??{},[a]:{defaults:((A=(T=s.endpointRouting)==null?void 0:T[a])==null?void 0:A.defaults)??s.defaults,modelRoutes:r,compatibility:(le=(H=s.endpointRouting)==null?void 0:H[a])==null?void 0:le.compatibility}},modelRoutes:a==="anthropic"?r:s.modelRoutes??{}};await Ie.mutateAsync({endpoint:a,nextConfig:G}),t(G)}c(G=>{const ce=G[a]??[],te=new Map(ce.map(W=>[W.source.trim(),W.id]));return{...G,[a]:Object.entries(r).map(([W,pe])=>({id:te.get(W.trim())??Ke(),source:W,target:pe}))}}),p({title:n("modelManagement.toast.routesSaved"),variant:"success"}),y.refetch()}catch(Q){p({title:n("modelManagement.toast.routesSaveFailure",{message:je(Q).message}),variant:"error"})}finally{x(null),O()}},handleCompatibilityEnabledChange:Se,sanitizeDraftsForProvider:a=>{c(m=>{const r={};for(const[j,T]of Object.entries(m))r[j]=T.filter(A=>!Kt(A.target.trim(),a));return r})}}}function ms(i,n){const{t:p,pushToast:s,config:t,setConfig:y,configQuery:g,customEndpoints:C,ensureConfig:w}=i,{sanitizeDraftsForProvider:l}=n??{},[o,c]=f.useState(""),[d,b]=f.useState("all"),[N,x]=f.useState(!1),[P,h]=f.useState("create"),[v,R]=f.useState(void 0),[L,q]=f.useState(null),[Y,k]=f.useState(null),[F,V]=f.useState({}),[se,Z]=f.useState(!1),[ae,I]=f.useState(null),[U,ne]=f.useState(!0),[he,xe]=f.useState({}),[E,u]=f.useState(null),$=(t==null?void 0:t.providers)??[],fe=$.length,ee=f.useMemo(()=>$.filter(D=>{var _;if(!(d==="all"||(D.type??"custom")===d))return!1;const M=o.trim().toLowerCase();return M?[D.id,D.label??"",D.baseUrl,D.defaultModel??"",...((_=D.models)==null?void 0:_.map(we=>we.id))??[]].join(" ").toLowerCase().includes(M):!0}),[o,d,$]),Pe=f.useMemo(()=>$.find(D=>D.id===L)??null,[$,L]),be=f.useMemo(()=>{const D=new Map;for(const z of $){if(!z.defaultModel||!z.models)continue;const M=z.models.find(S=>S.id===z.defaultModel);M&&D.set(z.id,Qt(M))}return D},[$]),J=f.useMemo(()=>[{key:"anthropic-beta",value:"claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14",label:p("providers.testDialog.options.beta.label"),description:p("providers.testDialog.options.beta.description")}],[p]),O=()=>{w()&&(h("create"),R(void 0),x(!0))},K=D=>{w()&&(h("edit"),R(D),x(!0))},re=async D=>{if(!t)throw new Error(p("settings.toast.missingConfig"));const z=P==="create"?[...$,D]:$.map(S=>v&&S.id===v.id?{...D,id:v.id}:S),M={...t,providers:z};await Ae.saveConfig(M),y(M),g.refetch(),P==="create"&&q(D.id),s({title:P==="create"?p("providers.toast.createSuccess",{name:D.label||D.id}):p("providers.toast.updateSuccess",{name:D.label||D.id}),variant:"success"})},ye=(D,z)=>{V(M=>({...M,[D]:z}))},Ne=async(D,z)=>{k(D.id);try{const M=z&&(z.headers||z.query)?{headers:z.headers&&Object.keys(z.headers).length>0?z.headers:void 0,query:z.query&&z.query.trim().length>0?z.query.trim():void 0}:void 0,S=await st.testProvider(D.id,M);if(S.ok){ye(D.id,{ok:!0,status:S.status,statusText:S.statusText,durationMs:S.durationMs,testedAt:Date.now()}),s({title:p("providers.toast.testSuccess"),description:p("providers.toast.testSuccessDesc",{status:S.status,duration:S.durationMs?`${S.durationMs} ms`:"—"}),variant:"success"});return}ye(D.id,{ok:!1,status:S.status,statusText:S.statusText,durationMs:S.durationMs,message:`${S.status} ${S.statusText}`,testedAt:Date.now()}),s({title:p("providers.toast.testFailure",{message:`${S.status} ${S.statusText}`}),variant:"error"})}catch(M){const S=je(M),_=S.status?`${S.status} ${S.message}`:S.message;ye(D.id,{ok:!1,status:S.status,message:_,testedAt:Date.now()}),s({title:p("providers.toast.testFailure",{message:_}),variant:"error"})}finally{k(null)}},_e=D=>{var Oe,Se;if(!(!!((Oe=D.defaultModel)!=null&&Oe.trim())||!!((Se=D.models)!=null&&Se.some(oe=>oe.id.trim().length>0)))){u(D);return}if(D.type!=="anthropic"){Ne(D);return}const M=D.extraHeaders??{},S=new Map(J.map(oe=>[oe.key.toLowerCase(),oe])),_={};let we=!0;for(const oe of J){const ke=Object.entries(M).find(([Ie])=>Ie.toLowerCase()===oe.key.toLowerCase());if(!ke)continue;const[Le,Me]=ke;String(Me??"")!==oe.value&&(we=!1,_[Le]=String(Me??""))}for(const[oe,ke]of Object.entries(M))S.has(oe.toLowerCase())||(_[oe]=String(ke??""));xe(_),ne(we),I(D),Z(!0)},Te=()=>{Z(!1),I(null),ne(!0),xe({})};return{providers:$,providerCount:fe,filteredProviders:ee,providerSearch:o,setProviderSearch:c,providerTypeFilter:d,setProviderTypeFilter:b,defaultLabels:be,selectedProvider:Pe,setSelectedProviderId:q,drawerOpen:N,setDrawerOpen:x,drawerMode:P,setDrawerMode:h,editingProvider:v,setEditingProvider:R,testingProviderId:Y,testResults:F,testDialogOpen:se,testDialogProvider:ae,testDialogUsePreset:U,setTestDialogUsePreset:ne,testDialogPreservedExtras:he,noModelDialogProvider:E,setNoModelDialogProvider:u,anthropicTestHeaderOptions:J,handleOpenCreate:O,handleOpenEdit:K,handleProviderSubmit:re,handleDeleteProvider:async D=>{var oe,ke,Le,Me,Ie,Xe;if(!w())return;const z=$.filter(ge=>ge.id!==D.id),M=ge=>{const ve={};if(!ge)return ve;for(const[a,m]of Object.entries(ge)){if(!m)continue;const[r]=m.split(":");r&&r===D.id||m===D.id||(ve[a]=m)}return ve},S=(t==null?void 0:t.endpointRouting)??{},_=M(((oe=S.anthropic)==null?void 0:oe.modelRoutes)??(t==null?void 0:t.modelRoutes)??{}),we=M(((ke=S.openai)==null?void 0:ke.modelRoutes)??{}),Oe=((t==null?void 0:t.customEndpoints)??C).map(ge=>{const ve=ge.routing,a=ve==null?void 0:ve.modelRoutes;return a?{...ge,routing:{...ve,defaults:ve.defaults??t.defaults,modelRoutes:M(a)}}:ge}),Se={...t,providers:z,modelRoutes:_,customEndpoints:Oe,endpointRouting:{anthropic:{defaults:((Le=S.anthropic)==null?void 0:Le.defaults)??t.defaults,modelRoutes:_,compatibility:(Me=S.anthropic)==null?void 0:Me.compatibility},openai:{defaults:((Ie=S.openai)==null?void 0:Ie.defaults)??t.defaults,modelRoutes:we,compatibility:(Xe=S.openai)==null?void 0:Xe.compatibility}}};try{await Ae.saveConfig(Se),y(Se),l==null||l(D.id),L===D.id&&q(null),s({title:p("providers.toast.deleteSuccess",{name:D.label||D.id}),variant:"success"}),g.refetch()}catch(ge){s({title:p("providers.toast.deleteFailure",{message:je(ge).message}),variant:"error"})}},handleTestConnection:Ne,initiateTestConnection:_e,closeTestDialog:Te,confirmTestDialog:async()=>{if(!ae)return;const D={};if(U)for(const S of J)D[S.key]=S.value;const z=new Map(J.map(S=>[S.key.toLowerCase(),S]));for(const[S,_]of Object.entries(he))z.get(S.toLowerCase())&&U||(D[S]=_);const M=ae;Te(),await Ne(M,{headers:Object.keys(D).length>0?D:void 0})}}}const us=["anthropic","openai-auto","openai-chat","openai-responses"];function ps({open:i,endpoint:n,onClose:p,onSuccess:s}){const{t}=me(),[y,g]=f.useState({id:"",label:"",paths:[{path:"",protocol:"openai-auto"}],enabled:!0});f.useEffect(()=>{if(i){if(n){const x=n.paths&&n.paths.length>0?n.paths:n.path&&n.protocol?[{path:n.path,protocol:n.protocol}]:[{path:"",protocol:"openai-auto"}];g({id:n.id,label:n.label,paths:x,enabled:n.enabled!==!1});return}g({id:"",label:"",paths:[{path:"",protocol:"openai-auto"}],enabled:!0})}},[n,i]);const C=at({mutationFn:Ge.create,invalidateKeys:[De.customEndpoints.all()],successToast:()=>({title:t("modelManagement.createEndpointSuccess")}),errorToast:x=>({title:t("modelManagement.createEndpointError",{error:x.message})}),onSuccess:async()=>{s(),p()}}),w=at({mutationFn:x=>Ge.update(x.id,x.updates),invalidateKeys:[De.customEndpoints.all()],successToast:()=>({title:t("modelManagement.updateEndpointSuccess")}),errorToast:x=>({title:t("modelManagement.updateEndpointError",{error:x.message})}),onSuccess:async()=>{s(),p()}}),l=()=>{g(x=>({...x,paths:[...x.paths,{path:"",protocol:"anthropic"}]}))},o=x=>{y.paths.length!==1&&g(P=>({...P,paths:P.paths.filter((h,v)=>v!==x)}))},c=(x,P,h)=>{g(v=>{const R=[...v.paths];return R[x]={...R[x],[P]:h},{...v,paths:R}})},d=x=>{if(x==null||x.preventDefault(),!y.id.trim()||!y.label.trim())return;for(const h of y.paths)if(!h.path.trim())return;const P=y.paths.map(h=>({path:h.path.trim(),protocol:h.protocol}));if(n){w.mutate({id:n.id,updates:{label:y.label.trim(),paths:P,enabled:y.enabled}});return}C.mutate({id:y.id.trim(),label:y.label.trim(),paths:P,enabled:y.enabled})},b=C.isPending||w.isPending,N=y.paths.length===0?t("modelManagement.atLeastOnePath"):!y.id.trim()||!y.label.trim()?t("modelManagement.endpointValidationError"):y.paths.some(x=>!x.path.trim())?t("modelManagement.pathValidationError"):null;return e.jsx(Be,{open:i,onOpenChange:x=>!x&&p(),children:e.jsxs(He,{className:"max-w-lg",onInteractOutside:x=>x.preventDefault(),children:[e.jsxs($e,{children:[e.jsx(ze,{children:t(n?"modelManagement.editEndpoint":"modelManagement.createEndpoint")}),e.jsx(Ue,{className:"truncate font-mono text-xs",children:n?n.id:t("modelManagement.endpointRoutingHint")})]}),e.jsx(qe,{children:e.jsxs("form",{id:"endpoint-form",onSubmit:d,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ue,{children:[t("modelManagement.endpointId")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(Ce,{value:y.id,onChange:x=>g(P=>({...P,id:x.target.value})),placeholder:t("modelManagement.endpointIdPlaceholder"),disabled:!!n,required:!0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t("modelManagement.endpointIdHint")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ue,{children:[t("modelManagement.endpointLabel")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(Ce,{value:y.label,onChange:x=>g(P=>({...P,label:x.target.value})),placeholder:t("modelManagement.endpointLabelPlaceholder"),required:!0})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ue,{children:[t("modelManagement.endpointPaths")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsxs(B,{type:"button",variant:"ghost",size:"sm",onClick:l,children:[e.jsx(Et,{className:"mr-1 h-3 w-3"}),t("modelManagement.addPath")]})]}),e.jsx("div",{className:"space-y-3",children:y.paths.map((x,P)=>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(Ce,{value:x.path,onChange:h=>c(P,"path",h.target.value),placeholder:t("modelManagement.endpointPathPlaceholder"),required:!0}),e.jsxs(ct,{value:x.protocol,onValueChange:h=>c(P,"protocol",h),children:[e.jsx(mt,{children:e.jsx(ut,{})}),e.jsx(pt,{children:us.map(h=>e.jsx(Qe,{value:h,children:t(h==="anthropic"?"modelManagement.protocolAnthropic":h==="openai-auto"?"modelManagement.protocolOpenAI":h==="openai-chat"?"modelManagement.protocolOpenAIChat":"modelManagement.protocolOpenAIResponses")},h))})]})]}),y.paths.length>1?e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>o(P),className:"text-destructive",children:e.jsx(it,{className:"h-4 w-4"})}):null]}),e.jsxs("div",{className:"space-y-1 text-xs text-muted-foreground",children:[P===0?e.jsx("p",{children:t("modelManagement.endpointPathHint")}):null,e.jsx("p",{children:t(`modelManagement.protocolHints.${x.protocol}`)})]})]},`${x.protocol}-${P}`))}),N?e.jsx("p",{className:"text-xs text-destructive",children:N}):null]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(xt,{id:"endpoint-enabled",checked:y.enabled,onCheckedChange:x=>g(P=>({...P,enabled:x}))}),e.jsx(ue,{htmlFor:"endpoint-enabled",children:t("modelManagement.endpointEnabled")})]}),n?null:e.jsx("div",{className:"rounded-xl bg-accent p-4",children:e.jsx("p",{className:"text-sm text-primary",children:t("modelManagement.endpointRoutingHint")})})]})}),e.jsxs(Ve,{children:[e.jsx(B,{variant:"outline",onClick:p,disabled:b,children:t("common.cancel")}),e.jsx(B,{type:"submit",form:"endpoint-form",disabled:b,children:t(b?"common.saving":n?"common.save":"common.create")})]})]})})}function hs({provider:i,defaultModel:n,config:p,customEndpoints:s,tabs:t,testResult:y,isTesting:g,onClose:C,onEdit:w,onTest:l,onDelete:o,onViewRoute:c,onAddRule:d}){var v;const{t:b}=me(),N=f.useMemo(()=>i?Gt(p,s,i.id):[],[p,s,i]),x=R=>{var L;return((L=t.find(q=>q.key===R))==null?void 0:L.label)??R};if(!i)return null;const P=xs(i,b),h=((v=i.models)==null?void 0:v.length)??0;return e.jsx(Be,{open:!0,onOpenChange:R=>!R&&C(),children:e.jsxs(He,{className:"max-w-xl",children:[e.jsxs($e,{children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(ze,{className:"truncate",title:i.label||i.id,children:i.label||i.id}),e.jsx(X,{variant:n?"success":"warning",className:"shrink-0 rounded-full px-2 py-0.5 text-[10px]",children:b(n?"providers.status.ready":"providers.status.needsDefault")})]}),e.jsx(Ue,{className:"truncate font-mono text-xs",children:i.id})]}),e.jsxs(qe,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-2 rounded-xl bg-secondary/60 p-3 text-xs sm:grid-cols-2",children:[e.jsx(et,{label:b("providers.card.authMode"),value:P}),e.jsx(et,{label:b("providers.card.modelsTitle"),value:h>0?b("providers.card.modelCount",{count:h}):b("providers.card.passthrough")}),e.jsx(et,{label:b("providers.card.baseUrl"),value:i.baseUrl,mono:!0}),e.jsx(et,{label:b("providers.card.defaultModelLabel"),value:n??b("providers.card.noDefault"),mono:!!n})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground/75",children:b("workbench.testResult.title")}),y?e.jsx(Wt,{result:y}):e.jsx("p",{className:"rounded-lg bg-secondary/50 px-3 py-2 text-xs text-muted-foreground",children:b("workbench.testResult.never")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground/75",children:b("workbench.detail.routesTitle")}),N.length===0?e.jsxs("div",{className:"space-y-2 rounded-lg bg-secondary/50 px-3 py-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:b("workbench.detail.routesEmptyHint")}),e.jsx(B,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:d,children:b("workbench.detail.addRuleCta")})]}):e.jsx("div",{className:"space-y-1.5",children:N.map(R=>e.jsxs("button",{type:"button",onClick:()=>c(R.endpoint),title:b("workbench.detail.viewRoute"),className:"flex w-full min-w-0 items-center gap-2 rounded-lg bg-secondary/50 px-3 py-2 text-left text-xs transition-colors hover:bg-accent",children:[e.jsx(X,{variant:"outline",className:"shrink-0 text-[10px]",children:x(R.endpoint)}),e.jsx("code",{className:"min-w-0 truncate text-foreground",children:R.source}),e.jsx(Ee,{className:"h-3 w-3 shrink-0 text-muted-foreground","aria-hidden":!0}),e.jsx("code",{className:"min-w-0 truncate text-muted-foreground",children:R.target})]},`${R.endpoint}-${R.source}`))})]})]}),e.jsxs(Ve,{className:"sm:justify-between",children:[e.jsx(B,{variant:"outline",onClick:o,className:"text-destructive hover:bg-destructive/10 hover:text-destructive",children:b("providers.actions.delete")}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"outline",onClick:l,disabled:g,children:g?e.jsxs(e.Fragment,{children:[e.jsx(Dt,{className:"mr-1 h-3.5 w-3.5 animate-spin","aria-hidden":!0}),b("common.actions.testingConnection")]}):b("providers.actions.test")}),e.jsx(B,{onClick:w,children:b("providers.actions.edit")})]})]})]})})}function et({label:i,value:n,mono:p}){return e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.14em] text-muted-foreground/70",children:i}),p?e.jsx("code",{className:"block truncate text-foreground",title:n,children:n}):e.jsx("p",{className:"truncate text-foreground",title:n,children:n})]})}function xs(i,n){const p=i.authMode??(i.type==="anthropic"?"authToken":"apiKey");return p==="authToken"?"Bearer":p==="xAuthToken"?"X-Auth-Token":i.type==="anthropic"?"X-API-Key":n("providers.card.providerDefault")}function gs({open:i,provider:n,onClose:p,onEdit:s}){const{t}=me();return n?e.jsx(Be,{open:i,onOpenChange:y=>!y&&p(),children:e.jsxs(He,{className:"max-w-md",children:[e.jsxs($e,{children:[e.jsx(ze,{children:t("providers.noModelDialog.title")}),e.jsx(Ue,{children:t("providers.noModelDialog.subtitle",{name:n.label||n.id})})]}),e.jsxs(qe,{className:"space-y-4",children:[e.jsx("div",{className:"rounded-xl bg-accent p-4 text-sm text-primary",children:t("providers.noModelDialog.description")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:t("providers.noModelDialog.hint")})]}),e.jsxs(Ve,{children:[e.jsx(B,{variant:"outline",onClick:p,children:t("common.actions.close")}),e.jsx(B,{onClick:()=>s(n),children:t("providers.noModelDialog.primary")})]})]})}):null}function fs({dialog:i,currentRoutes:n,onConfirm:p,onClose:s}){const{t}=me();if(!i)return null;const{endpoint:y,preset:g}=i,C=g.modelRoutes??{},w={};for(const N of n){const x=N.source.trim(),P=N.target.trim();x&&P&&(w[x]=P)}const l=new Set([...Object.keys(w),...Object.keys(C)]),o=[],c=[],d=[];for(const N of l){const x=N in w,P=N in C;P&&!x?o.push([N,C[N]]):x&&!P?c.push([N,w[N]]):x&&P&&w[N]!==C[N]&&d.push([N,w[N],C[N]])}const b=o.length>0||c.length>0||d.length>0;return e.jsx(Be,{open:!0,onOpenChange:N=>!N&&s(),children:e.jsxs(He,{className:"max-w-2xl",children:[e.jsxs($e,{children:[e.jsx(ze,{children:t("modelManagement.presets.diffTitle")}),e.jsx(Ue,{children:t("modelManagement.presets.diffDescription",{name:g.name})})]}),e.jsx(qe,{children:b?e.jsxs("div",{className:"max-h-80 space-y-2 rounded-xl bg-secondary/50 p-3 text-sm",children:[o.map(([N,x])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-emerald-50 px-2 py-1.5 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-200",children:[e.jsx(X,{variant:"outline",className:"border-emerald-300 text-xs dark:border-emerald-700",children:t("modelManagement.presets.diffAdded")}),e.jsx("span",{className:"truncate",children:N}),e.jsx(Ee,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:x})]},`add-${N}`)),c.map(([N,x])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-red-50 px-2 py-1.5 text-red-800 dark:bg-red-950 dark:text-red-200",children:[e.jsx(X,{variant:"outline",className:"border-red-300 text-xs dark:border-red-700",children:t("modelManagement.presets.diffRemoved")}),e.jsx("span",{className:"truncate",children:N}),e.jsx(Ee,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:x})]},`rm-${N}`)),d.map(([N,x,P])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-amber-50 px-2 py-1.5 text-amber-800 dark:bg-amber-950 dark:text-amber-200",children:[e.jsx(X,{variant:"outline",className:"border-amber-300 text-xs dark:border-amber-700",children:t("modelManagement.presets.diffChanged")}),e.jsx("span",{className:"truncate",children:N}),e.jsx(Ee,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate line-through opacity-60",children:x}),e.jsx(Ee,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:P})]},`chg-${N}`))]}):e.jsx("p",{className:"rounded-xl bg-secondary/50 py-8 text-center text-sm text-muted-foreground",children:t("modelManagement.presets.diffEmpty")})}),e.jsxs(Ve,{children:[e.jsx(B,{variant:"outline",onClick:s,children:t("common.cancel")}),e.jsx(B,{onClick:()=>p(y,g),disabled:!b,children:t("modelManagement.presets.diffConfirm")})]})]})})}function bs({open:i,mode:n,provider:p,existingProviderIds:s,onClose:t,onSubmit:y,testResult:g,testing:C,onTest:w}){const{t:l}=me(),o=Jt({mode:n,provider:p,existingProviderIds:s}),{form:c,errors:d,advancedOpen:b,providerIdRef:N}=o,[x,P]=f.useState(!1),[h,v]=f.useState(null),[R,L]=f.useState("basics"),q=f.useRef(null),Y=f.useRef(null);f.useEffect(()=>{i&&(o.resetForm(),v(null),P(!1),L("basics"))},[i,p,n,o.resetForm]),f.useEffect(()=>{if(!i)return;const O=K=>{K.key==="Escape"&&t()};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[i,t]),f.useEffect(()=>{if(i){if(n==="create"&&N.current){N.current.focus();return}Y.current&&Y.current.focus()}},[i,n]);const k=n==="create",F=f.useMemo(()=>c.models.filter(O=>O.id.trim().length>0),[c.models]),V=f.useMemo(()=>{var O;return((O=dt.find(K=>K.value===c.type))==null?void 0:O.label)??"Custom"},[c.type]),se=c.label.trim()||c.id.trim()||l("providers.drawer.summary.untitled"),Z=f.useMemo(()=>[{label:l("providers.drawer.summary.type"),value:V},{label:l("providers.drawer.summary.auth"),value:Xt(c.type,c.authMode,l)},{label:l("providers.drawer.summary.models"),value:F.length.toLocaleString()}],[F.length,c.authMode,c.type,V,l]),ae=async()=>{v(null);const O=o.validateErrors();if(Object.keys(O).length>0){O.baseUrl||O.id||O.extraHeaders?(L("basics"),O.extraHeaders&&o.setAdvancedOpen(!0)):O.models&&L("models");return}P(!0);try{const K=o.serialize();await y(K)}catch(K){v(l("providers.drawer.toast.saveFailure",{message:je(K).message})),P(!1);return}P(!1),t()};if(!i)return null;const I=Fe.findIndex(O=>O.id===R),U=I===Fe.length-1,ne=c.id.trim(),he=ne.length>0&&(n==="edit"||!s.includes(ne)),xe=c.baseUrl.trim();let E=xe.length>0;if(E)try{new URL(xe)}catch{E=!1}let u=!c.defaultModel||c.models.some(O=>O.id===c.defaultModel);if(u){const O=new Set;u=!c.models.some(K=>{const re=K.id.trim();return re.length===0||O.has(re)?!0:(O.add(re),!1)})}const $={basics:he&&E,models:u},fe=Fe.map((O,K)=>{let re;return K===I?re="current":K<I?re=$[O.id]?"complete":"error":re="upcoming",{id:O.id,label:l(O.labelKey),status:re}}),ee=O=>{L(O)},Pe=()=>{I<Fe.length-1&&L(Fe[I+1].id)},be=()=>{I>0&&L(Fe[I-1].id)},J={form:c,errors:d,isCreate:k,advancedOpen:b,onAdvancedOpenChange:o.setAdvancedOpen,idInputRef:N,onProviderIdChange:o.handleProviderIdChange,onFieldChange:o.handleFieldChange,onTypeChange:o.handleTypeChange,onAuthModeChange:o.handleAuthModeChange,onNonStreamViaStreamChange:o.handleProviderNonStreamViaStreamChange,onUseAbsoluteUrlChange:o.handleUseAbsoluteUrlChange,onAddHeader:o.handleAddHeader,onRemoveHeader:o.handleRemoveHeader,onHeaderChange:o.handleHeaderChange,onModelIdChange:o.handleModelIdChange,onModelChange:o.handleModelChange,onAddModel:o.handleAddModel,onRemoveModel:o.handleRemoveModel,onModelNonStreamViaStreamChange:o.handleModelNonStreamViaStreamChange,onSetDefaultModel:o.handleSetDefaultModel,testVerification:w?{available:n==="edit",testing:C??!1,result:g??null,onTest:w}:void 0};return e.jsxs("div",{className:"fixed inset-0 z-50 flex",children:[e.jsx("div",{className:"flex-1 bg-background/80 backdrop-blur-sm","aria-hidden":"true"}),e.jsxs("aside",{ref:q,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)] backdrop-blur",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(k?"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(k?"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(B,{type:"button",ref:Y,variant:"outline",onClick:t,className:"bg-card",children:l("common.actions.close")})]}),e.jsx("div",{className:"mt-4 grid gap-3 md:grid-cols-3",children:Z.map(O=>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:O.label}),e.jsx("p",{className:"mt-2 text-sm font-semibold text-foreground",children:O.value})]},O.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(Yt,{steps:fe,current:R,onSelect:ee,className:"mb-6"}),R==="basics"?e.jsx(Zt,{...J}):null,R==="models"?e.jsx(es,{...J}):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:se}),e.jsx("div",{className:"mt-4 space-y-3 text-sm",children:Z.map(O=>e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("span",{className:"text-muted-foreground",children:O.label}),e.jsx("span",{className:"text-right font-medium",children:O.value})]},O.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.jsx("div",{className:"flex flex-col text-xs text-destructive","aria-live":"polite",children:h?e.jsx("span",{children:h}):null}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{type:"button",variant:"outline",onClick:t,disabled:x,className:"bg-card",children:l("common.actions.cancel")}),e.jsx(B,{type:"button",variant:"outline",onClick:be,disabled:x||I===0,className:"bg-card",children:l("common.actions.previous")}),U?null:e.jsx(B,{type:"button",onClick:Pe,disabled:x,children:l("common.actions.next")}),e.jsx(B,{type:"button",onClick:ae,disabled:x,children:l(x?"common.actions.saving":"common.actions.save")})]})]})]})]})}function vs({providersLength:i,filteredProviders:n,testResults:p,providerSearch:s,providerTypeFilter:t,configPending:y,defaultLabels:g,onSelect:C,onProviderSearchChange:w,onProviderTypeChange:l,onResetFilters:o}){const{t:c}=me(),[d,b]=f.useState("usage"),N=Vt(De.stats.model(7,50),{url:"/api/stats/model",method:"GET",params:{days:7,limit:50}},{retry:!1}),x=f.useMemo(()=>{const h=new Map;for(const v of N.data??[])h.set(v.provider,(h.get(v.provider)??0)+v.requests);return h},[N.data]),P=f.useMemo(()=>{const h=[...n],v=(R,L)=>(R.label||R.id).localeCompare(L.label||L.id);return d==="usage"&&N.isSuccess?h.sort((R,L)=>(x.get(L.id)??0)-(x.get(R.id)??0)||v(R,L)):h.sort(v),h},[n,d,N.isSuccess,x]);return e.jsx(nt,{className:"overflow-hidden",children:e.jsxs(rt,{className:"p-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-b border-border bg-secondary/50 px-4 py-3",children:[e.jsx(Ce,{value:s,onChange:h=>w(h.target.value),placeholder:c("providers.filters.searchPlaceholder"),className:"h-9 w-full sm:w-64"}),e.jsxs(ct,{value:t,onValueChange:l,children:[e.jsx(mt,{className:"h-9 w-[130px] text-xs",children:e.jsx(ut,{})}),e.jsxs(pt,{children:[e.jsx(Qe,{value:"all",children:c("providers.filters.typeAll")}),dt.map(h=>e.jsx(Qe,{value:h.value??"custom",children:h.label},h.value??"custom"))]})]}),e.jsxs(ct,{value:d,onValueChange:h=>b(h),children:[e.jsx(mt,{className:"h-9 w-[104px] text-xs","aria-label":c("providers.list.sortLabel"),children:e.jsx(ut,{})}),e.jsxs(pt,{children:[e.jsx(Qe,{value:"usage",children:c("providers.list.sortUsage")}),e.jsx(Qe,{value:"name",children:c("providers.list.sortName")})]})]}),e.jsx(X,{variant:"secondary",className:"shrink-0 rounded-full px-2.5 py-1 text-[11px]",children:n.length}),e.jsx(B,{variant:"ghost",size:"sm",onClick:o,disabled:!s.trim()&&t==="all",className:"h-9 shrink-0 rounded-full px-2.5 text-xs",children:c("common.actions.reset")})]}),y?e.jsx("div",{className:"flex min-h-[160px] items-center justify-center text-sm text-muted-foreground",children:c("common.loading")}):i===0?e.jsx(ht,{compact:!0,title:c("providers.emptyState"),description:e.jsxs(e.Fragment,{children:[e.jsx("p",{children:c("providers.emptyStateSub")}),e.jsx("p",{className:"mt-1",children:c("workbench.list.emptyHint")})]})}):n.length===0?e.jsx(ht,{compact:!0,title:c("providers.emptyFiltered")}):e.jsxs(Ct,{children:[e.jsx(Pt,{children:e.jsxs(ot,{className:"hover:bg-transparent",children:[e.jsx(ie,{className:"w-10 px-4",children:e.jsx("span",{className:"sr-only",children:c("providers.table.status")})}),e.jsx(ie,{children:c("providers.table.name")}),e.jsx(ie,{children:c("providers.table.type")}),e.jsx(ie,{className:"hidden md:table-cell",children:c("providers.table.baseUrl")}),e.jsx(ie,{className:"text-right",children:c("providers.table.models")}),e.jsx(ie,{className:"hidden lg:table-cell",children:c("providers.table.defaultModel")}),e.jsx(ie,{className:"text-right",children:c("providers.table.requests7d")}),e.jsx(ie,{className:"w-8 px-2",children:e.jsx("span",{className:"sr-only",children:c("providers.table.viewDetail")})})]})}),e.jsx(St,{children:P.map(h=>{var k,F;const v=p[h.id],R=((k=h.models)==null?void 0:k.length)??0,L=N.isSuccess?x.get(h.id)??0:null,q=g.get(h.id),Y=((F=dt.find(V=>V.value===(h.type??"custom")))==null?void 0:F.label)??h.type??"custom";return e.jsxs(ot,{"data-testid":"provider-row",tabIndex:0,onClick:()=>C(h),onKeyDown:V=>{(V.key==="Enter"||V.key===" ")&&(V.preventDefault(),C(h))},className:"cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",children:[e.jsx(de,{className:"px-4",children:e.jsx("span",{title:v?v.ok?c("providers.list.testOk"):c("providers.list.testFailed"):c("providers.list.untested"),className:Re("block h-2 w-2 rounded-full",v?v.ok?"bg-success":"bg-destructive":"bg-muted-foreground/40")})}),e.jsxs(de,{className:"max-w-[220px]",children:[e.jsx("p",{className:"truncate text-sm font-medium text-foreground",title:h.label||h.id,children:h.label||h.id}),h.label&&h.label!==h.id?e.jsx("code",{className:"block truncate text-[11px] text-muted-foreground",title:h.id,children:h.id}):null]}),e.jsx(de,{children:e.jsx(X,{variant:"outline",className:"rounded-full px-2 py-0.5 text-[10px] font-normal text-muted-foreground",children:Y})}),e.jsx(de,{className:"hidden max-w-[240px] md:table-cell",children:e.jsx("code",{className:"block truncate text-xs text-muted-foreground",title:h.baseUrl,children:h.baseUrl})}),e.jsx(de,{className:"text-right tabular-nums text-muted-foreground",children:R}),e.jsx(de,{className:"hidden max-w-[200px] lg:table-cell",children:q?e.jsx("code",{className:"block truncate text-xs text-foreground",title:q,children:q}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(de,{className:"metric-number text-right text-muted-foreground",title:L!=null?c("providers.list.requests7d",{count:L}):void 0,children:L!=null?L.toLocaleString():"—"}),e.jsx(de,{className:"px-2",children:e.jsx(Nt,{className:"h-4 w-4 text-muted-foreground/60 transition-transform group-hover:translate-x-0.5 group-hover:text-muted-foreground","aria-hidden":!0})})]},h.id)})})]})]})})}const yt=6;function tt({value:i,onChange:n,options:p,disabled:s,placeholder:t,ariaLabel:y}){const{t:g}=me(),C=f.useId(),[w,l]=f.useState(!1),[o,c]=f.useState(""),d=f.useRef(null),b=f.useRef(!1),[N,x]=Bt(Ht.modelManagement.recentRouteTargets,[]),P=f.useMemo(()=>{const k=new Map;for(const F of p)k.set(F.value,F);return k},[p]),h=(k,F)=>F?[k.label,k.value,k.providerId??"",k.providerLabel??"",k.modelId??"",k.modelLabel??""].join(" ").toLowerCase().includes(F):!0,v=f.useMemo(()=>{const k=o.trim().toLowerCase(),F=p.filter(I=>h(I,k)),V=N.map(I=>P.get(I)??(k?void 0:{value:I,label:I,kind:"custom"})).filter(I=>!!I).filter(I=>h(I,k)).slice(0,yt),se=[];V.length>0&&se.push({key:"recent",label:g("modelManagement.targetPicker.recent"),options:V});const Z=new Map,ae=[];for(const I of F){if(I.kind==="custom"||!I.providerId){ae.push(I);continue}const U=`provider:${I.providerId}`,ne=Z.get(U);ne?ne.options.push(I):Z.set(U,{key:U,label:I.providerLabel??I.providerId,options:[I]})}return se.push(...Z.values()),ae.length>0&&se.push({key:"custom",label:g("modelManagement.targetPicker.custom"),options:ae,muted:!0}),se},[P,p,N,o,g]),R=v.reduce((k,F)=>k+F.options.length,0),L=k=>{n(k),x(F=>[k,...F.filter(V=>V!==k)].slice(0,yt)),c(""),b.current=!0,typeof document<"u"&&document.activeElement instanceof HTMLElement&&document.activeElement.blur(),l(!1),typeof window<"u"?window.requestAnimationFrame(()=>{b.current=!1}):b.current=!1},q=k=>k.kind==="passthrough"?g("modelManagement.targetPicker.passthrough"):k.kind==="custom"?g("modelManagement.targetPicker.customValue"):g("modelManagement.targetPicker.model"),Y=k=>k.kind==="passthrough"||k.kind==="custom"?k.label:k.modelLabel??k.label;return e.jsxs(ls,{open:w,onOpenChange:k=>{k&&b.current||(l(k),k&&c(""))},children:[e.jsx(is,{asChild:!0,children:e.jsx(Ce,{value:i,onChange:k=>{n(k.target.value),c(k.target.value),w||l(!0)},onFocus:()=>{c(""),l(!0)},onClick:()=>{w||l(!0)},placeholder:t,disabled:s,autoComplete:"off",role:"combobox","aria-label":y,"aria-expanded":w,"aria-controls":C,"aria-autocomplete":"list"})}),e.jsxs(ds,{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)] backdrop-blur",style:{width:"max(var(--radix-popover-trigger-width), 360px)"},align:"start",onOpenAutoFocus:k=>{var F;k.preventDefault(),(F=d.current)==null||F.focus()},onCloseAutoFocus:k=>{k.preventDefault()},children:[e.jsxs("div",{className:"space-y-2 border-b border-border/70 px-3 py-3",children:[e.jsx(Ce,{ref:d,value:o,onChange:k=>c(k.target.value),placeholder:g("modelManagement.targetPicker.searchPlaceholder"),className:"h-9",autoComplete:"off"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:o.trim()?g("modelManagement.targetPicker.matchCount",{count:R}):g("modelManagement.targetPicker.helper")})]}),R===0?e.jsx("div",{className:"px-3 py-4 text-center text-xs text-muted-foreground",children:g("common.noMatches")}):e.jsx("div",{id:C,role:"listbox",className:"min-h-0 flex-1 overflow-y-auto p-1.5",children:v.map(k=>e.jsxs("div",{className:"py-1",children:[e.jsxs("div",{className:Re("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 backdrop-blur",k.muted&&"opacity-80"),children:[e.jsx("span",{className:"truncate",children:k.label}),e.jsx("span",{children:k.options.length})]}),e.jsx("div",{className:"space-y-1",children:k.options.map(F=>e.jsxs("button",{type:"button",role:"option","aria-selected":F.value===i.trim(),className:Re("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",F.value===i.trim()&&"bg-accent/90 text-accent-foreground"),onMouseDown:V=>{V.preventDefault()},onClick:()=>L(F.value),children:[e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate font-medium",children:Y(F)}),e.jsx("span",{className:"block truncate text-xs text-muted-foreground",children:F.value})]}),e.jsxs("span",{className:"flex shrink-0 items-center gap-1",children:[F.isDefault?e.jsx(X,{variant:"secondary",className:"text-[10px]",children:g("modelManagement.targetPicker.default")}):null,e.jsx(X,{variant:F.kind==="passthrough"?"outline":"secondary",className:"text-[10px]",children:q(F)})]})]},`${k.key}-${F.value}`))})]},k.key))})]})]})}function js({endpoint:i,tabInfo:n,config:p,customEndpoints:s,routes:t,routeError:y,savingRoute:g,isDirty:C,defaults:w,defaultsDirty:l,savingDefaults:o,presets:c,presetName:d,presetError:b,savingPreset:N,applyingPreset:x,deletingPreset:P,presetsExpanded:h,savingCompatibilityPolicy:v,writing:R,providerModelOptions:L,onDefaultsChange:q,onSaveDefaults:Y,onTogglePresetsExpanded:k,onPresetNameChange:F,onSavePreset:V,onRequestPresetDiff:se,onRequestDeletePreset:Z,onCompatibilityEnabledChange:ae,onRouteChange:I,onRemoveRoute:U,onAddSuggestion:ne,onAddRoute:he,onResetRoutes:xe,onSaveRoutes:E}){var D,z;const{t:u}=me(),fe=((D=n==null?void 0:n.protocols)==null?void 0:D.includes("anthropic"))??i==="anthropic"?ss:as,ee=`route-source-${i}`,Pe=((z=n==null?void 0:n.protocols)==null?void 0:z.some(M=>M.startsWith("openai")))??i==="openai",be=ts(i,p,s),J=Pe?(be==null?void 0:be.enabled)??!1:!1,O=new Set(t.map(M=>M.source.trim()).filter(Boolean)),[K,re]=f.useState(!1),ye=f.useRef(new Map),Ne=f.useRef(!1),_e=()=>{Ne.current=!0,he()};f.useEffect(()=>{if(!Ne.current)return;const M=t[t.length-1];if(!M)return;const S=ye.current.get(M.id);S&&(Ne.current=!1,S.focus())},[t]);const Te=J?e.jsx(X,{variant:"secondary",className:"text-[11px]",children:u("modelManagement.openaiCompatibility.toggleLabel")}):null,We=e.jsx(ys,{presets:c,presetName:d,presetError:b,savingPreset:N,applyingPreset:x,deletingPreset:P,writing:R,expanded:h,onToggleExpanded:k,onPresetNameChange:F,onSavePreset:V,onRequestPresetDiff:se,onRequestDeletePreset:Z}),Je=Pe?e.jsx(Ze,{variant:"card",summary:e.jsx("span",{className:"text-sm font-medium text-primary",children:u("modelManagement.openaiCompatibility.title")}),badge:Te,summaryClassName:"px-4 py-3",contentClassName:"space-y-5 border-t border-border px-4 py-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium text-primary",children:u("modelManagement.openaiCompatibility.title")}),e.jsx("p",{className:"max-w-2xl text-xs leading-5 text-muted-foreground",children:u("modelManagement.openaiCompatibility.description")})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-primary/15 bg-card px-3 py-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(ue,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-primary/70",children:u("modelManagement.openaiCompatibility.toggleLabel")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u(J?"modelManagement.openaiCompatibility.enabledHint":"modelManagement.openaiCompatibility.disabledHint")})]}),e.jsx(xt,{checked:J,onCheckedChange:ae,disabled:v||R,"aria-label":u("modelManagement.openaiCompatibility.toggleLabel")})]})]})}):null;return e.jsxs("div",{className:"space-y-4",children:[e.jsx(nt,{children:e.jsxs(rt,{className:"space-y-4 pt-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"text-base font-semibold text-foreground",children:u("workbench.defaults.title")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u("workbench.defaults.description")})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:u("workbench.defaults.completionLabel")}),e.jsx(tt,{value:(w==null?void 0:w.completion)??"",onChange:M=>q("completion",M),options:L,disabled:o,ariaLabel:u("workbench.defaults.completionLabel"),placeholder:u("workbench.defaults.targetPlaceholder")})]}),e.jsxs(Ze,{summary:e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:u("workbench.defaults.moreLabel")}),summaryClassName:"px-0 py-1",contentClassName:"mt-3 space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:u("workbench.defaults.reasoningLabel")}),e.jsx(tt,{value:(w==null?void 0:w.reasoning)??"",onChange:M=>q("reasoning",M),options:L,disabled:o,ariaLabel:u("workbench.defaults.reasoningLabel"),placeholder:u("workbench.defaults.targetPlaceholder")})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:u("workbench.defaults.backgroundLabel")}),e.jsx(tt,{value:(w==null?void 0:w.background)??"",onChange:M=>q("background",M),options:L,disabled:o,ariaLabel:u("workbench.defaults.backgroundLabel"),placeholder:u("workbench.defaults.targetPlaceholder")})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ue,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:u("workbench.defaults.thresholdLabel")}),e.jsx(Ce,{type:"number",min:1,value:(w==null?void 0:w.longContextThreshold)??"",onChange:M=>{const S=Number.parseInt(M.target.value,10);q("longContextThreshold",Number.isFinite(S)?S:0)},disabled:o,className:"md:w-56"})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:u(l?"modelManagement.actions.footerDirtyHint":"modelManagement.actions.footerSavedHint")}),e.jsxs(B,{size:"sm",onClick:Y,disabled:o||!l||R,className:"relative",children:[u(o?"common.actions.saving":"workbench.defaults.save"),l?e.jsx("span",{className:"absolute -right-1 -top-1 h-2 w-2 rounded-full bg-amber-500"}):null]})]})]})}),e.jsx(nt,{children:e.jsxs(rt,{className:"space-y-6 pt-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("h3",{className:"text-base font-semibold text-foreground",children:u("workbench.specific.title")}),e.jsxs(X,{variant:"outline",children:[t.length," active"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u("workbench.specific.description")})]}),y?e.jsx("p",{className:"text-sm text-destructive",children:y}):null,e.jsxs("div",{className:"space-y-3 rounded-xl bg-secondary/50 p-4",children:[e.jsx("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsx(ue,{className:"text-sm font-semibold text-foreground",children:u("workbench.routing.rulesTitle")})})}),t.length===0?e.jsx(ht,{compact:!0,title:u("workbench.routing.emptyTitle"),description:u("workbench.routing.emptyDescription"),action:e.jsx(B,{size:"sm",onClick:_e,disabled:g,children:u("workbench.routing.addFirst")})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"hidden grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)_auto] items-center gap-3 px-1 text-xs font-medium text-muted-foreground md:grid",children:[e.jsx("span",{children:u("workbench.routing.sourceLabel")}),e.jsx("span",{}),e.jsx("span",{children:u("workbench.routing.targetLabel")}),e.jsx("span",{})]}),t.map((M,S)=>e.jsxs("div",{className:"rounded-xl bg-card p-3 shadow-sm",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between md:hidden",children:[e.jsxs(X,{variant:"outline",className:"text-[11px]",children:["#",S+1]}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",onClick:()=>U(M.id),disabled:g,"aria-label":u("common.delete"),children:e.jsx(it,{className:"h-4 w-4","aria-hidden":!0})})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)_auto] md:items-center",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(ue,{className:"text-[11px] uppercase tracking-[0.16em] text-muted-foreground md:hidden",children:u("workbench.routing.sourceLabel")}),e.jsx(Ce,{ref:_=>{_?ye.current.set(M.id,_):ye.current.delete(M.id)},value:M.source,onChange:_=>I(M.id,"source",_.target.value),placeholder:u("settings.routing.sourcePlaceholder"),list:ee,disabled:g,"aria-label":`route-source-${S+1}`})]}),e.jsx(Ee,{className:"hidden h-4 w-4 flex-shrink-0 text-muted-foreground md:block"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ue,{className:"text-[11px] uppercase tracking-[0.16em] text-muted-foreground md:hidden",children:u("workbench.routing.targetLabel")}),e.jsx(tt,{value:M.target,onChange:_=>I(M.id,"target",_),options:L,disabled:g,ariaLabel:u("workbench.routing.targetLabel"),placeholder:u("settings.routing.targetPlaceholder")})]}),e.jsx(B,{variant:"ghost",size:"icon",className:"hidden h-8 w-8 text-muted-foreground hover:text-destructive md:inline-flex",onClick:()=>U(M.id),disabled:g,"aria-label":u("common.delete"),children:e.jsx(it,{className:"h-4 w-4","aria-hidden":!0})})]})]},M.id))]})]}),e.jsxs("div",{className:"flex flex-col gap-3 rounded-xl bg-card p-4 shadow-[var(--surface-shadow)] md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium",children:u("modelManagement.actions.footerTitle")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u(C?"modelManagement.actions.footerDirtyHint":"modelManagement.actions.footerSavedHint")})]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-3 md:flex md:flex-wrap md:items-center",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:he,disabled:g,className:"w-full md:w-auto",children:u("settings.routing.add")}),e.jsx(B,{variant:"outline",size:"sm",onClick:xe,disabled:g||!C,className:"w-full md:w-auto",children:u("common.actions.reset")}),e.jsxs(B,{size:"sm",onClick:E,disabled:g||R,className:"relative w-full md:w-auto",children:[u(g?"common.actions.saving":"modelManagement.actions.saveRoutes"),C?e.jsx("span",{className:"absolute -right-1 -top-1 h-2 w-2 rounded-full bg-amber-500"}):null]})]})]}),e.jsxs(Ze,{open:K,onOpenChange:re,summary:e.jsxs("span",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:u("settings.routing.suggested")}),e.jsx(X,{variant:"outline",className:"text-[11px]",children:fe.length})]}),className:"rounded-xl bg-secondary/50 px-4 py-3",summaryClassName:"px-0 py-0",contentClassName:"mt-3",children:[e.jsx("p",{className:"mb-2 text-[11px] text-muted-foreground",children:u("modelManagement.overview.suggestionHint")}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:fe.map(M=>{const S=O.has(M);return e.jsx(B,{variant:S?"ghost":"outline",size:"sm",onClick:()=>ne(M),disabled:g||S,className:Re("h-7 rounded-md px-2.5 text-[11px] font-normal",S?"opacity-45":"bg-background"),children:M},`${i}-${M}`)})})]}),e.jsx("datalist",{id:ee,children:fe.map(M=>e.jsx("option",{value:M},`${ee}-${M}`))})]})}),e.jsxs(Ze,{variant:"card",summary:e.jsx("span",{className:"text-sm font-medium text-foreground",children:u("workbench.advanced.title")}),summaryClassName:"px-4 py-3",contentClassName:"space-y-4 border-t border-border px-4 py-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:u("workbench.advanced.wildcardHint")}),Je,We]})]})}function ys({presets:i,presetName:n,presetError:p,savingPreset:s,applyingPreset:t,deletingPreset:y,writing:g,expanded:C,onToggleExpanded:w,onPresetNameChange:l,onSavePreset:o,onRequestPresetDiff:c,onRequestDeletePreset:d}){const{t:b}=me();return e.jsxs("div",{className:"rounded-xl bg-card shadow-[var(--surface-shadow)]",children:[e.jsx("button",{type:"button",className:"flex w-full items-center justify-between gap-3 rounded-xl p-4 text-left transition-colors hover:bg-accent",onClick:w,children:e.jsxs("div",{className:"flex items-center gap-2",children:[C?e.jsx(Rt,{className:"h-4 w-4"}):e.jsx(Nt,{className:"h-4 w-4"}),e.jsx("h3",{className:"font-medium",children:b("modelManagement.presets.title")}),e.jsx(X,{variant:"secondary",className:"text-xs",children:i.length})]})}),C?e.jsxs("div",{className:"space-y-4 border-t border-border/45 px-4 pb-4 pt-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:b("modelManagement.presets.description")}),e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center",children:[e.jsx(Ce,{value:n,onChange:N=>l(N.target.value),placeholder:b("modelManagement.presets.namePlaceholder"),disabled:s,className:"w-full md:w-48"}),e.jsx(B,{onClick:o,disabled:s||g,className:"w-full md:w-auto",children:b(s?"modelManagement.presets.saving":"modelManagement.presets.save")})]}),p?e.jsx("p",{className:"text-sm text-destructive",children:p}):null,i.length===0?e.jsx("p",{className:"py-4 text-center text-sm text-muted-foreground",children:b("modelManagement.presets.empty")}):e.jsx($t,{children:e.jsx("div",{className:"grid gap-2 sm:grid-cols-2 lg:grid-cols-3",children:i.map(N=>{const x=t===N.name,P=y===N.name,h=Object.entries(N.modelRoutes??{}),v=h.length;return e.jsxs("div",{className:"flex flex-col gap-3 rounded-xl bg-secondary/50 px-4 py-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs(zt,{children:[e.jsx(Ut,{asChild:!0,children:e.jsxs("div",{className:"min-w-0 flex-1 cursor-default",children:[e.jsx("span",{className:"block truncate text-sm font-medium",children:N.name}),e.jsx(X,{variant:"outline",className:"mt-1 text-xs",children:v>0?b("modelManagement.presets.rulesCount",{count:v}):b("modelManagement.presets.noRules")})]})}),v>0?e.jsx(qt,{side:"bottom",className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1 text-xs",children:[h.slice(0,5).map(([R,L])=>e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"truncate",children:R}),e.jsx(Ee,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:L})]},R)),v>5?e.jsxs("div",{className:"text-muted-foreground",children:["…+",v-5]}):null]})}):null]}),e.jsxs("div",{className:"grid flex-shrink-0 gap-2 sm:flex sm:items-center",children:[e.jsx(B,{size:"sm",onClick:()=>c(N),disabled:x||P||g,className:"w-full sm:w-auto",children:b(x?"modelManagement.presets.applying":"modelManagement.presets.apply")}),e.jsx(B,{variant:"destructive",size:"sm",onClick:()=>d(N),disabled:P||x||g,className:"w-full sm:w-auto",children:b(P?"modelManagement.presets.deleting":"modelManagement.presets.delete")})]})]},N.name)})})})]}):null]})}function Ns({endpoint:i,tabs:n,config:p,customEndpoints:s,routing:t,onRequestDeletePreset:y,onClose:g}){var P,h;const{t:C}=me(),[w,l]=f.useState(i);i&&i!==w&&l(i);const o=i??w,c=o?n.find(v=>v.key===o):void 0,d=(c==null?void 0:c.protocols)??[],b=d.find(v=>v.startsWith("openai"))??d[0],N=b?kt(b,C):C("modelManagement.tabs.customEndpoint"),x=o?(t.isDirtyByEndpoint[o]??!1)||(t.isDefaultsDirtyByEndpoint[o]??!1):!1;return e.jsx(Be,{modal:!1,open:i!==null,onOpenChange:v=>!v&&g(),children:e.jsx(He,{className:"max-w-4xl","data-testid":"route-editor-dialog",onInteractOutside:v=>v.preventDefault(),onOpenAutoFocus:v=>v.preventDefault(),children:o?e.jsxs(e.Fragment,{children:[e.jsxs($e,{children:[e.jsxs(ze,{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:(c==null?void 0:c.label)??o}),e.jsx(X,{variant:"outline",className:"shrink-0 rounded-full px-2 py-0.5 text-[10px] font-normal",children:N})]}),e.jsx(Ue,{className:"truncate font-mono text-xs",children:o})]}),e.jsx(qe,{children:e.jsx(js,{endpoint:o,tabInfo:c,config:p,customEndpoints:s,routes:t.routesByEndpoint[o]||[],routeError:t.routeError[o],savingRoute:t.savingRouteFor===o,isDirty:t.isDirtyByEndpoint[o]??!1,defaults:t.defaultsByEndpoint[o]??null,defaultsDirty:t.isDefaultsDirtyByEndpoint[o]??!1,savingDefaults:t.savingDefaultsFor===o,presets:t.presetsByEndpoint[o]??[],presetName:t.presetNameByEndpoint[o]??"",presetError:t.presetErrorByEndpoint[o],savingPreset:t.savingPresetFor===o,applyingPreset:((P=t.applyingPreset)==null?void 0:P.endpoint)===o?t.applyingPreset.name:null,deletingPreset:((h=t.deletingPreset)==null?void 0:h.endpoint)===o?t.deletingPreset.name:null,presetsExpanded:t.presetsExpanded[o]===!0,savingCompatibilityPolicy:t.savingCompatibilityPolicy,writing:t.writingEndpoint===o,providerModelOptions:t.providerModelOptions,onDefaultsChange:(v,R)=>t.handleDefaultsChange(o,v,R),onSaveDefaults:()=>void t.handleSaveDefaults(o),onTogglePresetsExpanded:()=>t.setPresetsExpanded(v=>({...v,[o]:!v[o]})),onPresetNameChange:v=>t.handlePresetNameChange(o,v),onSavePreset:()=>void t.handleSavePreset(o),onRequestPresetDiff:v=>t.setPresetDiffDialog({endpoint:o,preset:v}),onRequestDeletePreset:v=>y(o,v),onCompatibilityEnabledChange:v=>void t.handleCompatibilityEnabledChange(o,v),onRouteChange:(v,R,L)=>t.handleRouteChange(o,v,R,L),onRemoveRoute:v=>t.handleRemoveRoute(o,v),onAddSuggestion:v=>t.handleAddSuggestion(o,v),onAddRoute:()=>t.handleAddRoute(o),onResetRoutes:()=>t.handleResetRoutes(o),onSaveRoutes:()=>void t.handleSaveRoutes(o)})}),e.jsxs(Ve,{children:[e.jsx("p",{className:"mr-auto self-center text-xs text-muted-foreground",children:C(x?"modelManagement.actions.footerDirtyHint":"modelManagement.actions.footerSavedHint")}),e.jsx(B,{variant:"outline",onClick:g,children:C("common.actions.close")})]})]}):null})})}const ws={anthropic:["/anthropic/v1/messages"],openai:["/openai/v1/chat/completions","/openai/v1/responses"]};function ks(i){var n;return(n=i.paths)!=null&&n.length?i.paths:i.path&&i.protocol?[{path:i.path,protocol:i.protocol}]:i.path?[{path:i.path,protocol:"anthropic"}]:[]}function Cs({tabs:i,customEndpoints:n,routeCounts:p,defaultsByEndpoint:s,onEditRoute:t,onEditEndpoint:y,onDeleteEndpoint:g}){const{t:C}=me(),w=i.map(l=>{const o=n.find(d=>d.id===l.key);if(!o)return{key:l.key,label:l.label,protocols:l.protocols??[],pathSummary:(ws[l.key]??[]).join(" "),enabled:!0};const c=ks(o);return{key:l.key,label:o.label||o.id,protocols:[...new Set(c.map(d=>d.protocol))],pathSummary:c.map(d=>d.path).join(" "),enabled:o.enabled!==!1,custom:o}});return e.jsx(nt,{className:"overflow-hidden",children:e.jsx(rt,{className:"p-0",children:e.jsxs(Ct,{children:[e.jsx(Pt,{children:e.jsxs(ot,{className:"hover:bg-transparent",children:[e.jsx(ie,{className:"px-4",children:C("workbench.endpoints.table.name")}),e.jsx(ie,{children:C("workbench.endpoints.table.protocol")}),e.jsx(ie,{className:"hidden md:table-cell",children:C("workbench.endpoints.table.paths")}),e.jsx(ie,{className:"whitespace-nowrap text-right",children:C("workbench.endpoints.table.rules")}),e.jsx(ie,{className:"hidden lg:table-cell",children:C("workbench.endpoints.table.defaultTarget")}),e.jsx(ie,{children:C("workbench.endpoints.table.status")}),e.jsx(ie,{className:"text-right",children:C("workbench.endpoints.table.actions")})]})}),e.jsx(St,{children:w.map(l=>{var c;const o=(c=s[l.key])==null?void 0:c.completion;return e.jsxs(ot,{"data-testid":"endpoint-row",onClick:()=>t(l.key),className:"cursor-pointer",children:[e.jsxs(de,{className:"max-w-[220px] px-4",children:[e.jsx("p",{className:"truncate text-sm font-medium text-foreground",title:l.label,children:l.label}),l.label!==l.key?e.jsx("code",{className:"block truncate text-[11px] text-muted-foreground",title:l.key,children:l.key}):null]}),e.jsx(de,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:l.protocols.length>0?l.protocols.map(d=>e.jsx(X,{variant:"outline",className:"rounded-full px-2 py-0.5 text-[10px] font-normal text-muted-foreground",children:kt(d,C)},d)):e.jsx("span",{className:"text-muted-foreground",children:"—"})})}),e.jsx(de,{className:"hidden max-w-[280px] md:table-cell",children:l.pathSummary?e.jsx("code",{className:"block truncate text-xs text-muted-foreground",title:l.pathSummary,children:l.pathSummary}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(de,{className:"text-right tabular-nums text-muted-foreground",children:p[l.key]??0}),e.jsx(de,{className:"hidden max-w-[220px] lg:table-cell",children:o?e.jsx("code",{className:"block truncate text-xs text-muted-foreground",title:o,children:o}):e.jsx("span",{className:"text-xs text-muted-foreground",children:C("workbench.endpoints.defaultUnset")})}),e.jsx(de,{children:e.jsx(X,{variant:l.enabled?"success":"secondary",className:"whitespace-nowrap rounded-full border-0 px-2 py-0.5 text-[10px]",children:l.enabled?C("modelManagement.overview.endpointEnabled"):C("modelManagement.overview.endpointDisabled")})}),e.jsx(de,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"h-8 text-muted-foreground hover:text-foreground",onClick:()=>t(l.key),children:[e.jsx(wt,{className:"mr-1 h-3.5 w-3.5","aria-hidden":!0}),C("workbench.endpoints.editRoute")]}),l.custom?e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-foreground",title:C("common.edit"),onClick:d=>{d.stopPropagation(),y(l.custom)},children:e.jsx(Tt,{className:"h-3.5 w-3.5","aria-hidden":!0})}):null,l.custom&&l.custom.deletable!==!1?e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",title:C("common.delete"),onClick:d=>{d.stopPropagation(),g(l.custom)},children:e.jsx(Ot,{className:"h-3.5 w-3.5","aria-hidden":!0})}):null]})})]},l.key)})})]})})})}function Ps({tabs:i,customEndpoints:n,routeCounts:p,defaultsByEndpoint:s,onEditRoute:t,onEditEndpoint:y,onDeleteEndpoint:g}){const{t:C}=me();return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1 rounded-lg border bg-card px-4 py-3 text-xs text-muted-foreground",children:[e.jsx("p",{children:C("workbench.routingGuide.flow")}),e.jsx("p",{children:C("workbench.routingGuide.hint")})]}),e.jsx(Cs,{tabs:i,customEndpoints:n,routeCounts:p,defaultsByEndpoint:s,onEditRoute:t,onEditEndpoint:y,onDeleteEndpoint:g})]})}function Ss({open:i,provider:n,options:p,usePreset:s,preservedExtras:t,onPresetChange:y,onConfirm:g,onClose:C}){const{t:w}=me();return n?e.jsx(Be,{open:i,onOpenChange:l=>!l&&C(),children:e.jsxs(He,{className:"max-w-2xl",onInteractOutside:l=>l.preventDefault(),children:[e.jsxs($e,{children:[e.jsx(ze,{children:w("providers.testDialog.title")}),e.jsx(Ue,{children:w("providers.testDialog.subtitle",{name:n.label||n.id})})]}),e.jsxs(qe,{className:"space-y-4",children:[e.jsx("div",{className:"rounded-xl bg-accent p-4 text-sm text-primary",children:w("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(ue,{htmlFor:"provider-test-preset",children:w("providers.testDialog.presetLabel")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:w("providers.testDialog.presetDescription")})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(xt,{id:"provider-test-preset",checked:s,onCheckedChange:y})})]}),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:w("providers.testDialog.presetPreviewSummary")}),e.jsx("div",{className:"mt-2 space-y-1",children:p.map(l=>e.jsxs("code",{className:"block rounded-lg bg-secondary px-2 py-1 text-xs",children:[l.key,": ",l.value]},l.key))})]})}):e.jsx("p",{className:"text-xs text-muted-foreground",children:w("providers.testDialog.presetDescription")})]}),Object.keys(t).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:w("providers.testDialog.preservedInfo")}),Object.entries(t).map(([l,o])=>e.jsxs("code",{className:"block rounded-lg border border-transparent bg-card px-2 py-1 shadow-[var(--surface-shadow)]",children:[l,": ",o]},l))]})]}),e.jsxs(Ve,{children:[e.jsx(B,{variant:"outline",onClick:C,children:w("providers.testDialog.cancel")}),e.jsx(B,{onClick:()=>void g(),children:w("providers.testDialog.primary")})]})]})}):null}function Js(){const{t:i}=me(),n=ns(),p=cs(n),s=ms(n,{sanitizeDraftsForProvider:p.sanitizeDraftsForProvider}),[t,y]=It(),g=t.get("tab"),C=g==="routing"||g==="endpoints"?"routing":"providers";f.useEffect(()=>{g==="endpoints"&&y(E=>{const u=new URLSearchParams(E);return u.set("tab","routing"),u},{replace:!0})},[g,y]);const[w,l]=f.useState(!1),[o,c]=f.useState(void 0),[d,b]=f.useState(null),[N,x]=f.useState(!1),P=t.get("endpoint"),[h,v]=f.useState(P);f.useEffect(()=>{v(P)},[P]);const R=()=>{y(E=>{const u=new URLSearchParams(E);return u.delete("endpoint"),u},{replace:!0})};f.useEffect(()=>{h&&(n.customEndpointsQuery.isPending||p.endpointTabs.some(E=>E.key===h)||R())},[h,p.endpointTabs,n.customEndpointsQuery.isPending]);const L=()=>{c(void 0),l(!0)},q=E=>{c(E),l(!0)},Y=E=>{y(u=>{const $=new URLSearchParams(u);return $.set("tab","routing"),$.set("endpoint",E),$},{replace:!0})},k=E=>{s.setSelectedProviderId(null),y(u=>{const $=new URLSearchParams(u);return E==="providers"?$.delete("tab"):$.set("tab",E),$},{replace:!0})},F=()=>{y(E=>{const u=new URLSearchParams(E);return u.set("tab","routing"),u},{replace:!0})},V=async()=>{if(d){x(!0);try{d.kind==="provider"?await s.handleDeleteProvider(d.provider):d.kind==="preset"?await p.handleDeletePreset(d.endpoint,d.preset):await p.handleDeleteEndpoint(d.endpoint.id),b(null)}finally{x(!1)}}},se=(d==null?void 0:d.kind)==="provider"?rs(n.config,n.customEndpoints,d.provider.id):0,Z=(d==null?void 0:d.kind)==="provider"?i("providers.actions.delete"):(d==null?void 0:d.kind)==="preset"?i("modelManagement.presets.delete"):(d==null?void 0:d.kind)==="endpoint"?i("common.delete"):"",ae=(d==null?void 0:d.kind)==="provider"?i("providers.confirm.delete",{name:d.provider.label||d.provider.id}):(d==null?void 0:d.kind)==="preset"?i("modelManagement.confirm.deletePreset",{name:d.preset.name}):(d==null?void 0:d.kind)==="endpoint"?i("modelManagement.deleteEndpointConfirm",{label:d.endpoint.label}):"",I=(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:"",U=s.selectedProvider,ne=Object.values(p.routesByEndpoint).reduce((E,u)=>E+((u==null?void 0:u.length)??0),0),he=Object.fromEntries(Object.entries(p.routesByEndpoint).map(([E,u])=>[E,(u==null?void 0:u.length)??0])),xe=[{value:"providers",icon:Lt,label:i("workbench.viewSwitch.providers"),description:i("workbench.viewSwitch.providersDesc"),count:s.providerCount},{value:"routing",icon:wt,label:i("workbench.viewSwitch.routing"),description:i("workbench.viewSwitch.routingDesc"),count:ne}];return e.jsxs("div",{className:"flex flex-col gap-6",children:[e.jsx(At,{actions:C==="providers"?e.jsx(B,{size:"sm",onClick:s.handleOpenCreate,children:i("providers.actions.add")}):e.jsx(B,{size:"sm",onClick:L,children:i("workbench.endpoints.create")})}),e.jsx("div",{role:"tablist","aria-label":i("workbench.viewSwitch.label"),className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:xe.map(E=>{const u=E.icon,$=C===E.value;return e.jsxs("button",{type:"button",role:"tab","aria-selected":$,onClick:()=>k(E.value),className:Re("motion-surface flex items-center gap-3 rounded-xl border p-4 text-left",$?"border-primary/40 bg-primary/5":"border-border bg-card hover:bg-muted/40"),children:[e.jsx("span",{className:Re("flex h-9 w-9 shrink-0 items-center justify-center rounded-lg",$?"bg-primary/10 text-primary":"bg-secondary text-muted-foreground"),children:e.jsx(u,{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:Re("text-sm font-semibold",$?"text-foreground":"text-muted-foreground"),children:E.label}),e.jsx(X,{variant:$?"default":"secondary",className:"text-[10px]",children:E.count})]}),e.jsx("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",children:E.description})]})]},E.value)})}),C==="providers"?e.jsx(vs,{configPending:n.configQuery.isPending||!n.config&&n.configQuery.isFetching,testResults:s.testResults,filteredProviders:s.filteredProviders,providerSearch:s.providerSearch,providerTypeFilter:s.providerTypeFilter,providersLength:s.providers.length,defaultLabels:s.defaultLabels,onSelect:E=>s.setSelectedProviderId(E.id),onProviderSearchChange:s.setProviderSearch,onProviderTypeChange:s.setProviderTypeFilter,onResetFilters:()=>{s.setProviderSearch(""),s.setProviderTypeFilter("all")}}):e.jsx(Ps,{tabs:p.endpointTabs,customEndpoints:n.customEndpoints,routeCounts:he,defaultsByEndpoint:p.defaultsByEndpoint,onEditRoute:Y,onEditEndpoint:q,onDeleteEndpoint:E=>b({kind:"endpoint",endpoint:E})}),e.jsx(Ns,{endpoint:h,tabs:p.endpointTabs,config:n.config,customEndpoints:n.customEndpoints,routing:p,onRequestDeletePreset:(E,u)=>b({kind:"preset",endpoint:E,preset:u}),onClose:R}),e.jsx(hs,{provider:U,defaultModel:U?s.defaultLabels.get(U.id):void 0,config:n.config,customEndpoints:n.customEndpoints,tabs:n.tabs,testResult:U?s.testResults[U.id]??null:null,isTesting:U?s.testingProviderId===U.id:!1,onClose:()=>s.setSelectedProviderId(null),onEdit:()=>{U&&(s.setSelectedProviderId(null),s.handleOpenEdit(U))},onTest:()=>{U&&s.initiateTestConnection(U)},onDelete:()=>{U&&b({kind:"provider",provider:U})},onViewRoute:E=>{s.setSelectedProviderId(null),Y(E)},onAddRule:()=>{s.setSelectedProviderId(null),F()}}),e.jsx(bs,{open:s.drawerOpen,mode:s.drawerMode,provider:s.drawerMode==="edit"?s.editingProvider:void 0,existingProviderIds:s.providers.map(E=>E.id).filter(E=>s.drawerMode==="edit"&&s.editingProvider?E!==s.editingProvider.id:!0),testResult:s.editingProvider?s.testResults[s.editingProvider.id]??null:null,testing:s.editingProvider?s.testingProviderId===s.editingProvider.id:!1,onTest:()=>{s.editingProvider&&s.handleTestConnection(s.editingProvider)},onClose:()=>{s.setDrawerOpen(!1),s.setEditingProvider(void 0),s.setDrawerMode("create")},onSubmit:s.handleProviderSubmit}),e.jsx(Ss,{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:E=>{s.setNoModelDialogProvider(null),s.handleOpenEdit(E)}}),e.jsx(ps,{open:w,endpoint:o,onClose:()=>{l(!1),c(void 0)},onSuccess:()=>{n.configQuery.refetch()}}),e.jsx(fs,{dialog:p.presetDiffDialog,currentRoutes:p.presetDiffDialog?p.routesByEndpoint[p.presetDiffDialog.endpoint]||[]:[],onConfirm:(E,u)=>{p.setPresetDiffDialog(null),p.handleApplyPreset(E,u)},onClose:()=>p.setPresetDiffDialog(null)}),e.jsx(Ft,{open:!!d,onOpenChange:E=>{!E&&!N&&b(null)},title:Z,description:ae,confirmLabel:i(N?"common.actions.loading":"common.delete"),cancelLabel:i("common.actions.cancel"),loading:N,onConfirm:V,children:I?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:I}),(d==null?void 0:d.kind)==="provider"&&se>0?e.jsx("p",{className:"text-xs text-muted-foreground",children:i("providers.confirm.deleteImpact",{count:se})}):null]}):null})]})}export{Js as default};
@@ -0,0 +1 @@
1
+ import{j as e,aG as Y,az as gt,ai as ft,r as d}from"./vendor-m8O77Czp.js";import{C as He}from"./ConfirmDialog-VrbumD7j.js";import{P as Ve}from"./PageState-CPKqNFG7.js";import{P as bt}from"./PageToolbar-DzpjQ7SY.js";import{C as k,a as L}from"./card-DS9KKz-k.js";import{B as O,r as De,h as yt,c as vt,a as jt}from"./app-CeLCVbqy.js";import{B as V,u as Ke,q as Z}from"./queryKeys-BlGm18Nk.js";import{L as f,I as j}from"./label-CWq3wWgE.js";import{S as B}from"./switch-B2cQk2bS.js";import{S as Nt,a as Ct,b as wt,c as Pt,d as kt}from"./select-CxIEo3DN.js";import{c as E}from"./global-zt8jbW7F.js";import{u as P}from"./i18n-DWfLgqoF.js";import{u as ee}from"./useAppMutation-DY1JJByx.js";import{g as qe}from"./gateway-Bt6lPuXq.js";import{c as St}from"./clipboard-BnAnBk_-.js";import"./DialogShell-TRFN3c58.js";import"./radix-OaJStcH-.js";import"./query-CZuclkQv.js";import"./router-C1-ppOz7.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,p,l,r,a,m,v,A,T,u,M;const s=t.storePayloads,i=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??((p=t.http)==null?void 0:p.host)??"127.0.0.1",logRetentionDays:String(t.logRetentionDays??30),logExportTimeoutSeconds:String(t.logExportTimeoutSeconds??60),storeRequestPayloads:i(t.storeRequestPayloads),storeResponsePayloads:i(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(((r=t.http)==null?void 0:r.port)??t.port??4100),httpHost:((a=t.http)==null?void 0:a.host)??t.host??"127.0.0.1",httpsEnabled:((m=t.https)==null?void 0:m.enabled)===!0,httpsPort:String(((v=t.https)==null?void 0:v.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:i}=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:i("settings.sections.jump")}),e.jsx("div",{className:"space-y-1.5",children:oe.map((o,p)=>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-full text-[11px] font-semibold",t===o.id?"bg-primary text-primary-foreground":"bg-secondary text-muted-foreground"),children:p+1}),e.jsx("span",{children:i(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-full 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:i(o.labelKey)},o.id))})})})]})}function Lt({defaultsSummary:t,errors:s,form:i,onInputChange:o,onSetForm:p,sectionRef:l}){const{t:r}=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:r("settings.sections.basics")}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:r("settings.description")})]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-3",children:[e.jsx(ae,{label:r("settings.fields.retention"),value:i.logRetentionDays}),e.jsx(ae,{label:r("settings.fields.logExportTimeout"),value:`${i.logExportTimeoutSeconds}s`}),e.jsx(ae,{label:r("settings.fields.bodyLimit"),value:`${i.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:r("settings.fields.port")}),e.jsx(j,{type:"number",min:1,max:65535,value:i.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:r("settings.fields.host")}),e.jsx(j,{value:i.host,onChange:a=>o("host")(a.target.value),placeholder:r("settings.fields.hostPlaceholder")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:r("settings.fields.retention")}),e.jsx(j,{type:"number",min:1,max:365,value:i.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:r("settings.fields.logExportTimeout")}),e.jsx(j,{type:"number",min:5,max:600,value:i.logExportTimeoutSeconds,onChange:a=>o("logExportTimeoutSeconds")(a.target.value),"aria-invalid":!!s.logExportTimeoutSeconds}),e.jsx("p",{className:"text-xs text-muted-foreground",children:r("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:r("settings.fields.bodyLimit")}),e.jsx(j,{type:"number",min:1,max:2048,value:i.bodyLimitMb,onChange:a=>o("bodyLimitMb")(a.target.value),"aria-invalid":!!s.bodyLimitMb}),e.jsx("p",{className:"text-xs text-muted-foreground",children:r("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:r("settings.fields.logLevel")}),e.jsxs(Nt,{value:i.logLevel,onValueChange:a=>p(m=>({...m,logLevel:a})),children:[e.jsx(Ct,{children:e.jsx(wt,{})}),e.jsx(Pt,{children:Rt.map(a=>e.jsx(kt,{value:a.value,children:r(`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:r("settings.fields.storeRequestPayloads"),hint:r("settings.fields.storeRequestPayloadsHint"),checked:i.storeRequestPayloads,onCheckedChange:a=>p(m=>({...m,storeRequestPayloads:a}))}),e.jsx(ne,{label:r("settings.fields.storeResponsePayloads"),hint:r("settings.fields.storeResponsePayloadsHint"),checked:i.storeResponsePayloads,onCheckedChange:a=>p(m=>({...m,storeResponsePayloads:a}))}),e.jsx(ne,{label:r("settings.fields.enableRoutingFallback"),hint:r("settings.fields.enableRoutingFallbackHint"),checked:i.enableRoutingFallback,onCheckedChange:a=>p(m=>({...m,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:r("settings.fields.defaults")}),e.jsx("p",{className:"mt-2 text-sm",children:t??r("settings.defaults.none")})]})]})]})})}function At({errors:t,form:s,onSetForm:i,protocolChangesPending:o,sectionRef:p}){const{t:l}=P();return e.jsx(k,{id:"section-protocol",ref:p,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-amber-50 ring-1 ring-amber-200/50 p-4 shadow-sm dark:bg-amber-950/24 dark:ring-amber-500/20",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-amber-600 dark:text-amber-400"}),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 dark:bg-secondary dark:border-border",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 shadow-sm",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 dark:bg-secondary",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:r=>i(a=>({...a,httpEnabled:r}))})]}),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:r=>i(a=>({...a,httpPort:r.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:r=>i(a=>({...a,httpHost:r.target.value})),placeholder:"127.0.0.1"})]})]}):null]}),e.jsxs("div",{className:"rounded-xl bg-secondary p-5 dark:bg-secondary",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(gt,{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:r=>i(a=>({...a,httpsEnabled:r}))})]}),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:r=>i(a=>({...a,httpsPort:r.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:r=>i(a=>({...a,httpsHost:r.target.value})),placeholder:"127.0.0.1"})]})]}),e.jsx(le,{label:l("settings.protocol.https.keyPath"),value:s.httpsKeyPath,onChange:r=>i(a=>({...a,httpsKeyPath:r})),placeholder:"~/.cc-gw/certs/key.pem"}),e.jsx(le,{label:l("settings.protocol.https.certPath"),value:s.httpsCertPath,onChange:r=>i(a=>({...a,httpsCertPath:r})),placeholder:"~/.cc-gw/certs/cert.pem"}),e.jsx(le,{label:l("settings.protocol.https.caPath"),value:s.httpsCaPath,onChange:r=>i(a=>({...a,httpsCaPath:r})),placeholder:"留空则不使用"}),e.jsx("div",{className:"rounded-xl bg-amber-50 ring-1 ring-amber-200/50 p-4 shadow-sm dark:bg-amber-950/24 dark:ring-amber-500/20",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-amber-600 dark:text-amber-400"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx("p",{className:"text-sm font-medium text-amber-800 dark:text-amber-200",children:l("settings.protocol.https.warning")}),e.jsx("p",{className:"text-xs leading-relaxed text-amber-700 dark:text-amber-300",children:l("settings.protocol.https.tip")})]})]})})]}):null]})]})})}function Tt({authErrors:t,authForm:s,authLoading:i,authSettings:o,needsPassword:p,onSetAuthForm:l,sectionRef:r}){const{t:a}=P();return e.jsx(k,{id:"section-security",ref:r,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")})]}),i&&!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-full bg-secondary px-3 py-1 text-[11px] tracking-[0.08em]",children:"/ui"}),e.jsx("span",{className:"rounded-full bg-secondary px-3 py-1 text-[11px] tracking-[0.08em]",children:"/api/*"}),e.jsx("span",{className:"rounded-full 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:m=>l(v=>({...v,enabled:m}))})]})]}),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:m=>l(v=>({...v,username:m.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:m=>l(v=>({...v,password:m.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(p?"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:m=>l(v=>({...v,confirmPassword:m.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(p?"settings.auth.passwordHintRequired":"settings.auth.passwordHintOptional")})]})]})]})]})})}function Mt({configPath:t,onCopyPath:s,sectionRef:i}){const{t:o}=P();return e.jsx(k,{id:"section-config-file",ref:i,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:i,onOpenClearAll:o,sectionRef:p}){const{t:l}=P();return e.jsx(k,{id:"section-cleanup",ref:p,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-amber-200 bg-amber-50 p-5 dark:border-amber-800 dark:bg-amber-950/30",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:i,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:i,onSave:o,saving:p}){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-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:i,disabled:p,className:"w-full lg:w-auto",children:l("common.actions.reset")}),e.jsx(O,{onClick:o,disabled:p,className:"w-full lg:w-auto",children:l(p?"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:i,hintClassName:o,label:p,labelClassName:l,onCheckedChange:r}){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:p}),e.jsx("p",{className:E("text-xs text-muted-foreground",o),children:i})]}),e.jsx(B,{checked:t,onCheckedChange:r,className:"self-start sm:self-auto"})]})}function le({label:t,onChange:s,placeholder:i,value:o}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:t}),e.jsx(j,{value:o,onChange:p=>s(p.target.value),placeholder:i,className:"font-mono text-xs"})]})}const q={authStatusRequest(){return{url:"/api/auth/web",method:"GET"}},saveWebAuth:async t=>yt(vt.post("/api/auth/web",t)),cleanupLogs:async()=>De({url:"/api/logs/cleanup",method:"POST"}),clearLogs:async()=>De({url:"/api/logs/clear",method:"POST"})};function Ht(){const{t}=P(),{pushToast:s}=jt(),[i,o]=d.useState(oe[0].id),p=d.useRef(new Map),l=d.useCallback(n=>{const h=p.current.get(n);h&&h.scrollIntoView({behavior:"smooth",block:"start"})},[]),r=d.useCallback(n=>h=>{h?p.current.set(n,h):p.current.delete(n)},[]),a=Ke(Z.config.info(),qe.configInfoRequest()),m=Ke(Z.auth.web(),q.authStatusRequest()),v=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})})}),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})})}),[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,re]=d.useState(!1),[Je,ie]=d.useState(!1),[Qe,ce]=d.useState(!1),[_e,ze]=d.useState(!1),[Ge,$e]=d.useState(!1),[b,de]=d.useState(null),[x,H]=d.useState({enabled:!1,username:"",password:"",confirmPassword:""}),[Ue,D]=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(()=>x.enabled?b!=null&&b.hasPassword?x.username.trim()!==(b.username??""):!0:!1,[x.enabled,x.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(x)!==JSON.stringify(J):!1,[x,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(()=>{m.data&&(de(m.data),H(se(m.data)),D({}))},[m.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(()=>{!m.isError||!m.error||s({title:t("settings.toast.authLoadFailure",{message:m.error.message}),variant:"error"})},[m.error,m.isError,s,t]);const st=d.useCallback(n=>h=>{F(y=>({...y,[n]:h}))},[]),me=d.useCallback(()=>{const n={};if(!c.httpEnabled&&!c.httpsEnabled&&(n.protocol=t("settings.validation.protocolRequired")),c.httpEnabled){const w=Number(c.httpPort);(!Number.isFinite(w)||w<1||w>65535)&&(n.httpPort=t("settings.validation.httpPort"))}if(c.httpsEnabled){const w=Number(c.httpsPort);(!Number.isFinite(w)||w<1||w>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 y=Number(c.logRetentionDays);(!Number.isFinite(y)||y<1||y>365)&&(n.logRetentionDays=t("settings.validation.retention"));const C=Number(c.logExportTimeoutSeconds);(!Number.isFinite(C)||C<5||C>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]),pe=d.useCallback(()=>{const n={},h=x.username.trim(),y=b?h!==(b.username??""):!0,C=x.enabled&&(!(b!=null&&b.hasPassword)||y);return x.enabled&&!h&&(n.username=t("settings.auth.validation.username")),x.password&&x.password.length<6&&(n.password=t("settings.auth.validation.minLength")),C&&!x.password&&(n.password=t("settings.auth.validation.passwordRequired")),(x.password||x.confirmPassword)&&x.password!==x.confirmPassword&&(n.confirmPassword=t("settings.auth.validation.confirmMismatch")),D(n),Object.keys(n).length===0},[x,b,t]),_=d.useCallback(async()=>{var n,h,y,C,R,w,he,xe,ge,fe,be,ye,ve,je,Ne,Ce,we,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(me()){re(!0);try{const K=Number(c.port),it=Number(c.logRetentionDays),ct=Number(c.logExportTimeoutSeconds),dt=Number(c.bodyLimitMb),g={...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:K,host:c.host.trim()||void 0,logRetentionDays:it,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 g.requestLogging,delete g.responseLogging;const Oe={...g};delete Oe.webAuth,await qe.saveConfig(Oe),M({...g,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,mt=g.port??((h=g.http)==null?void 0:h.port)??4100,pt=((y=u.host)==null?void 0:y.trim())||((R=(C=u.http)==null?void 0:C.host)==null?void 0:R.trim())||"127.0.0.1",ht=((w=g.host)==null?void 0:w.trim())||((xe=(he=g.http)==null?void 0:he.host)==null?void 0:xe.trim())||"127.0.0.1",xt=ut!==mt||pt!==ht||((ge=u.http)==null?void 0:ge.enabled)!==((fe=g.http)==null?void 0:fe.enabled)||((be=u.http)==null?void 0:be.port)!==((ye=g.http)==null?void 0:ye.port)||(((ve=u.http)==null?void 0:ve.host)??u.host??"127.0.0.1")!==(((je=g.http)==null?void 0:je.host)??g.host??"127.0.0.1")||((Ne=u.https)==null?void 0:Ne.enabled)!==((Ce=g.https)==null?void 0:Ce.enabled)||((we=u.https)==null?void 0:we.port)!==((Pe=g.https)==null?void 0:Pe.port)||(((ke=u.https)==null?void 0:ke.host)??u.host??"127.0.0.1")!==(((Se=g.https)==null?void 0:Se.host)??g.host??"127.0.0.1")||((Re=u.https)==null?void 0:Re.keyPath)!==((Ee=g.https)==null?void 0:Ee.keyPath)||((Le=u.https)==null?void 0:Le.certPath)!==((Ae=g.https)==null?void 0:Ae.certPath)||Fe((Te=u.https)==null?void 0:Te.caPath)!==Fe((Me=g.https)==null?void 0:Me.caPath);s({title:t(xt?"settings.toast.protocolRestartRequired":"settings.toast.saveSuccess"),variant:"success"}),a.refetch()}catch(K){s({title:t("settings.toast.saveFailure",{message:K instanceof Error?K.message:"unknown"}),variant:"error"})}finally{re(!1)}}},[u,a,c,s,t,me]),z=d.useCallback(()=>{u&&(F(te(u)),I({}))},[u]),G=d.useCallback(async()=>{if(pe()){ue(!0);try{const n={enabled:x.enabled,username:x.username.trim()||void 0};x.password&&(n.password=x.password);const h=await v.mutateAsync(n);h.auth&&(de(h.auth),H({enabled:h.auth.enabled,username:h.auth.username??"",password:"",confirmPassword:""}),D({})),m.refetch()}catch{}finally{ue(!1)}}},[x,m,v,pe]),$=d.useCallback(()=>{b&&(H(se(b)),D({}))},[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()=>{ie(!0);try{await A.mutateAsync()}catch{}finally{ie(!1)}},[A]),rt=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(p.current.values());if(n.length===0)return;const h=new IntersectionObserver(y=>{for(const C of y)if(C.isIntersecting){o(C.target.id);break}},{rootMargin:"-80px 0px -60% 0px",threshold:0});for(const y of n)h.observe(y);return()=>h.disconnect()},[U]),{activeSection:i,authErrors:Ue,authForm:x,authQuery:m,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:rt,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:p,setAuthForm:H,setConfirmCleanupOpen:ze,setConfirmClearAllOpen:$e,setErrors:I,setForm:F,setSectionRef:r,t}}function ss(){const{t}=P(),s=Ht(),i=Number(s.isConfigDirty)+Number(s.isAuthDirty);return e.jsxs("div",{className:"flex flex-col gap-6",children:[e.jsx(bt,{info:i>0?e.jsx("span",{className:"rounded-full bg-amber-100 px-2.5 py-1 text-xs font-medium text-amber-800 dark:bg-amber-950/40 dark:text-amber-300",children:t("settings.overview.unsavedCount",{count:i})}):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:i,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,ai as Q,r as c}from"./vendor-m8O77Czp.js";import{B as h,t as z,L as ge}from"./app-CeLCVbqy.js";import{C as ve,b as ye,d as fe,e as je,a as Se}from"./card-DS9KKz-k.js";import{u as Ce,B as be,M as Ne,C as ke,T as Re,o as Ke,g as Pe,m as Me,S as Te}from"./useProviderForm-DlALMLaD.js";import{L as C,I as R}from"./label-CWq3wWgE.js";import{u as we,E as Ee}from"./shared-fOyVvn5H.js";import{u as b}from"./i18n-DWfLgqoF.js";import{S as Ae,a as Ie,b as He,c as Oe,d as Fe}from"./select-CxIEo3DN.js";import{a as $e}from"./apiKeys-Dl_vgy_U.js";import{g as G}from"./gateway-Bt6lPuXq.js";import{c as Le}from"./clipboard-BnAnBk_-.js";import{d as Ue}from"./router-C1-ppOz7.js";import"./global-zt8jbW7F.js";import"./query-CZuclkQv.js";import"./radix-OaJStcH-.js";import"./queryKeys-BlGm18Nk.js";import"./disclosure-CqU8C-ET.js";import"./switch-B2cQk2bS.js";function Be({state:d}){const{t}=b(),r=we(),{keyName:s,setKeyName:a,keyEndpoints:l,setKeyEndpoints:p,keyMaxConcurrency:x,setKeyMaxConcurrency:g,creatingKey:u,createdKey:m,createApiKey:v,copyCreatedKey:o}=d;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-full bg-emerald-500/10 text-emerald-600",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-amber-600 dark:text-amber-400",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 o(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:y=>a(y.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:y=>g(y.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 v(),disabled:u||s.trim().length===0,children:t(u?"setup.steps.apiKey.creating":"setup.steps.apiKey.create")})})]})}function De({existingProviderIds:d,saving:t,onSave:r}){const{t:s}=b(),a=Ce({mode:"create",existingProviderIds:d}),l={form:a.form,errors:a.errors,isCreate:!0,advancedOpen:a.advancedOpen,onAdvancedOpenChange:a.setAdvancedOpen,idInputRef:a.providerIdRef,onProviderIdChange:a.handleProviderIdChange,onFieldChange:a.handleFieldChange,onTypeChange:a.handleTypeChange,onAuthModeChange:a.handleAuthModeChange,onNonStreamViaStreamChange:a.handleProviderNonStreamViaStreamChange,onUseAbsoluteUrlChange:a.handleUseAbsoluteUrlChange,onAddHeader:a.handleAddHeader,onRemoveHeader:a.handleRemoveHeader,onHeaderChange:a.handleHeaderChange,onModelIdChange:a.handleModelIdChange,onModelChange:a.handleModelChange,onAddModel:a.handleAddModel,onRemoveModel:a.handleRemoveModel,onModelNonStreamViaStreamChange:a.handleModelNonStreamViaStreamChange,onSetDefaultModel:a.handleSetDefaultModel},p=()=>{a.validate()&&r(a.serialize())};return e.jsxs("div",{className:"space-y-8",children:[e.jsx(be,{...l}),e.jsx(Ne,{...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:d,onSaved:t}){const{t:r}=b(),{providers:s,setupProvider:a,setSetupProviderId:l,savingProvider:p,saveProvider:x}=d,[g,u]=c.useState(null),m=g??s.length===0,v=o=>{x(o).then(y=>{y&&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:(a==null?void 0:a.id)??"",onValueChange:l,children:[e.jsx(Ie,{children:e.jsx(He,{})}),e.jsx(Oe,{children:s.map(o=>e.jsx(Fe,{value:o.id,children:o.label||o.id},o.id))})]})]})]}):null,m?e.jsx(De,{existingProviderIds:s.map(o=>o.id),saving:p,onSave:v}):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:d}){const{t}=b(),{setupProvider:r,anthropicRoutes:s,routeSource:a,setRouteSource:l,routeTarget:p,setRouteTarget:x,savingRoute:g,saveDefaultRoute:u}=d,m=Object.entries(s),v=!!r&&a.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(([o,y])=>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:o}),e.jsxs("code",{className:"font-mono text-muted-foreground",children:["→ ",y]})]},o))})]}):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:a,onChange:o=>l(o.target.value)})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:Ve.map(o=>e.jsx(h,{type:"button",variant:"outline",size:"sm",className:"h-7 rounded-md px-2.5 text-[11px] font-normal",onClick:()=>l(o),children:o},o))}),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:o=>x(o.target.value)})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(h,{type:"button",onClick:()=>void u(),disabled:!v,children:t(g?"setup.steps.routing.saving":"setup.steps.routing.save")})})]})]})}function ze({state:d}){const{t}=b(),{setupProvider:r,testingProvider:s,testResult:a,testSetupProvider:l,anthropicBaseUrl:p,createdKey:x,copyCreatedKey:g}=d;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")}),a?e.jsx(Re,{result:a}):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 N=["provider","routing","apiKey","verify"];function Ge(){var U;const d=Ke(),{t,pushToast:r,config:s,setConfig:a,configQuery:l,customEndpoints:p,ensureConfig:x}=d,g=Ue(),[u,m]=c.useState(0),[v,o]=c.useState(null),[y,E]=c.useState(!1),[A,W]=c.useState(""),[Y,J]=c.useState(null),[X,I]=c.useState(!1),[K,Z]=c.useState(""),[P,ee]=c.useState(["anthropic"]),[M,te]=c.useState(""),[se,H]=c.useState(!1),[O,ae]=c.useState(null),[ne,F]=c.useState(!1),[re,T]=c.useState(null),S=c.useMemo(()=>(s==null?void 0:s.providers)??[],[s]),f=c.useMemo(()=>S.find(n=>n.id===v)??S[0]??null,[S,v]),w=c.useMemo(()=>s?Pe(s,p,"anthropic"):{},[s,p]),$=Object.keys(w).length,oe=c.useMemo(()=>{var i,j;if(!f)return"";const n=f.defaultModel??((j=(i=f.models)==null?void 0:i.find(k=>k.id.trim().length>0))==null?void 0:j.id);return n?`${f.id}:${n}`:`${f.id}:*`},[f]),L=Y??oe,ie=async n=>{if(!s||!x())return!1;const i={...s,providers:[...S,n]};E(!0);try{return await G.saveConfig(i),a(i),l.refetch(),o(n.id),r({title:t("providers.toast.createSuccess",{name:n.label||n.id}),variant:"success"}),!0}catch(j){return r({title:t("providers.drawer.toast.saveFailure",{message:j instanceof Error?j.message:"unknown"}),variant:"error"}),!1}finally{E(!1)}},de=async()=>{var B,D,_,V;if(!s||!x())return;const n=A.trim(),i=L.trim();if(!n||!i)return;const j={...w,[n]:i},k={...s,endpointRouting:{...s.endpointRouting??{},anthropic:{defaults:((D=(B=s.endpointRouting)==null?void 0:B.anthropic)==null?void 0:D.defaults)??s.defaults,modelRoutes:j,compatibility:(V=(_=s.endpointRouting)==null?void 0:_.anthropic)==null?void 0:V.compatibility}},modelRoutes:j};I(!0);try{await G.saveConfig(k),a(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{I(!1)}},ce=async()=>{if(!K.trim()){r({title:t("apiKeys.errors.nameRequired"),variant:"error"});return}H(!0);try{const n=await $e.create({name:K.trim(),allowedEndpoints:P.length>0?P:void 0,maxConcurrency:M?Number(M):null});ae(n)}catch(n){const i=z(n);r({title:t("setup.steps.apiKey.createFailed",{message:i.message}),variant:"error"})}finally{H(!1)}},le=async n=>{try{await Le(n),r({title:t("apiKeys.toast.keyCopied"),variant:"success"})}catch(i){r({title:t("apiKeys.toast.copyFailure"),description:i instanceof Error?i.message:t("common.unknownError"),variant:"error"})}},ue=async()=>{if(f){F(!0);try{const n=await Me.testProvider(f.id);if(n.ok){T({ok:!0,status:n.status,statusText:n.statusText,durationMs:n.durationMs,testedAt:Date.now()});return}T({ok:!1,status:n.status,statusText:n.statusText,durationMs:n.durationMs,message:`${n.status} ${n.statusText}`,testedAt:Date.now()})}catch(n){const i=z(n);T({ok:!1,status:i.status,message:i.status?`${i.status} ${i.message}`:i.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=N[u],xe={provider:S.length>0,routing:$>0,apiKey:O!==null,verify:!0};return{...d,stepIndex:u,activeStep:me,canProceed:xe,goNext:()=>{m(n=>Math.min(n+1,N.length-1))},goBack:()=>{m(n=>Math.max(n-1,0))},goToStep:n=>{const i=N.indexOf(n);i>=0&&i<=u&&m(i)},finish:()=>{g("/")},providers:S,setupProvider:f,setupProviderId:v,setSetupProviderId:o,savingProvider:y,saveProvider:ie,anthropicRoutes:w,anthropicRouteCount:$,routeSource:A,setRouteSource:W,routeTarget:L,setRouteTarget:J,savingRoute:X,saveDefaultRoute:de,keyName:K,setKeyName:Z,keyEndpoints:P,setKeyEndpoints:ee,keyMaxConcurrency:M,setKeyMaxConcurrency:te,creatingKey:se,createdKey:O,createApiKey:ce,copyCreatedKey:le,testingProvider:ne,testResult:re,testSetupProvider:ue,anthropicBaseUrl:pe}}function vt(){const{t:d}=b(),t=Ge();if(t.configQuery.isPending&&!t.config)return e.jsx(ge,{});const r=N.map((a,l)=>({id:a,label:d(`setup.steps.${a}.navLabel`),status:l<t.stepIndex?"complete":l===t.stepIndex?"current":"upcoming"})),s=t.stepIndex===N.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:d("setup.title")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:d("setup.description")})]}),e.jsx(Te,{steps:r,current:t.activeStep,onSelect:t.goToStep}),e.jsxs(ve,{children:[e.jsxs(ye,{children:[e.jsx(fe,{children:d(`setup.steps.${t.activeStep}.title`)}),e.jsx(je,{children:d(`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:d("common.actions.previous")}),s?e.jsx(h,{type:"button",onClick:t.finish,children:d("setup.actions.finish")}):e.jsx(h,{type:"button",onClick:t.goNext,disabled:!t.canProceed[t.activeStep],children:d("common.actions.next")})]})]})}export{vt as default};
@@ -0,0 +1 @@
1
+ import{r,h as s,c as t}from"./app-CeLCVbqy.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};