@chenpu17/cc-gw 0.17.0 → 0.17.1

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 (54) hide show
  1. package/package.json +5 -5
  2. package/src/web/dist/assets/{About-D2m94wu2.js → About-DmIV-sHO.js} +1 -1
  3. package/src/web/dist/assets/{ApiKeys-Bt-otGF_.js → ApiKeys-BNr4zbD6.js} +1 -1
  4. package/src/web/dist/assets/{ConfirmDialog-CRSbmgE7.js → ConfirmDialog-_CIYYtzo.js} +1 -1
  5. package/src/web/dist/assets/{Dashboard-81qp43jm.js → Dashboard-Hg4OZNAc.js} +1 -1
  6. package/src/web/dist/assets/{DialogShell-DxWKa5oR.js → DialogShell-D1T4HXtd.js} +1 -1
  7. package/src/web/dist/assets/Events-CO2wWiEK.js +1 -0
  8. package/src/web/dist/assets/{Help-XaAZ__Kz.js → Help-CafNfXfx.js} +1 -1
  9. package/src/web/dist/assets/{Login-atwWPGzz.js → Login-C04-poiG.js} +1 -1
  10. package/src/web/dist/assets/Logs-CqaIXvR0.js +1 -0
  11. package/src/web/dist/assets/{PageSection-CC5EhfMe.js → PageSection-Dd2-9G6C.js} +1 -1
  12. package/src/web/dist/assets/{PageState-XybOeENt.js → PageState-Bbhr4fy6.js} +1 -1
  13. package/src/web/dist/assets/{PageToolbar-CnLp4aWt.js → PageToolbar-GyUQBhmq.js} +1 -1
  14. package/src/web/dist/assets/{ProvidersPage-CFCY2xSG.js → ProvidersPage-CHvyCANH.js} +1 -1
  15. package/src/web/dist/assets/{RoutingPage-35o5ZSMg.js → RoutingPage-fVr25VKF.js} +1 -1
  16. package/src/web/dist/assets/{Settings-DC1TPeS9.js → Settings-DfaIYHsa.js} +1 -1
  17. package/src/web/dist/assets/{Setup-CnQPVK9X.js → Setup-DUEpie5k.js} +1 -1
  18. package/src/web/dist/assets/{TargetCombobox-DkVdA04_.js → TargetCombobox-CSnHZqDY.js} +1 -1
  19. package/src/web/dist/assets/{apiKeys-CMk2nxB_.js → apiKeys-B5Os17Qm.js} +1 -1
  20. package/src/web/dist/assets/app-DZpd2fu9.js +61 -0
  21. package/src/web/dist/assets/{badge-eRkhnmCs.js → badge-CWbm9P64.js} +1 -1
  22. package/src/web/dist/assets/{chartTheme-Cx-0Jiew.js → chartTheme-ChTod603.js} +1 -1
  23. package/src/web/dist/assets/{charts-core-BOHudNiN.js → charts-core-BuoE1ECx.js} +1 -1
  24. package/src/web/dist/assets/{charts-engine-BhFpDbO0.js → charts-engine-DHIzBJl6.js} +1 -1
  25. package/src/web/dist/assets/{charts-react-CPWg-GRD.js → charts-react-BLOapElb.js} +1 -1
  26. package/src/web/dist/assets/{currency-Bx141-XL.js → currency-DffG4uWM.js} +2 -2
  27. package/src/web/dist/assets/{disclosure-CU-KJc8C.js → disclosure-W_XtxMJz.js} +1 -1
  28. package/src/web/dist/assets/{gateway-DyhqzHSh.js → gateway-DxaHzVOF.js} +1 -1
  29. package/src/web/dist/assets/{global-BLUcvOa8.js → global-BCYo_xAt.js} +1 -1
  30. package/src/web/dist/assets/global-CP6wBbWu.css +1 -0
  31. package/src/web/dist/assets/{i18n-v60Yn7Ls.js → i18n-ClvfZhYc.js} +1 -1
  32. package/src/web/dist/assets/{label-CdbE1ezd.js → label-09axTkPo.js} +1 -1
  33. package/src/web/dist/assets/{landing-BQdbaG8s.js → landing-BsX2AKvc.js} +3 -3
  34. package/src/web/dist/assets/{modelManagement-DwdbGu0o.js → modelManagement-Dc7L1tJw.js} +1 -1
  35. package/src/web/dist/assets/package-DgoCoO-z.js +1 -0
  36. package/src/web/dist/assets/{popover-CuM9b3U7.js → popover-CX5HRHKk.js} +1 -1
  37. package/src/web/dist/assets/{query-CvboQrUT.js → query-1Ng1fzmE.js} +1 -1
  38. package/src/web/dist/assets/{radix-d0BukFWM.js → radix-DONH6gHT.js} +1 -1
  39. package/src/web/dist/assets/{router-CqUBCAsx.js → router-Bkbjq53m.js} +1 -1
  40. package/src/web/dist/assets/{segmented-control-5mZhY1KZ.js → segmented-control-Cxe6ZLHe.js} +1 -1
  41. package/src/web/dist/assets/{shared-zfHsnBTk.js → shared-DG0AgdnU.js} +1 -1
  42. package/src/web/dist/assets/{switch-CZn1nypU.js → switch-C58zWdHT.js} +1 -1
  43. package/src/web/dist/assets/{tabs-CrNMQMmG.js → tabs-BIz291zK.js} +1 -1
  44. package/src/web/dist/assets/{useAppMutation-B29oVzxS.js → useAppMutation-CsoNTPQ7.js} +1 -1
  45. package/src/web/dist/assets/{useEventStream-DN2DYBVS.js → useEventStream-CvopQT4p.js} +1 -1
  46. package/src/web/dist/assets/{useProviderForm-DIuM3Z2u.js → useProviderForm-B_wmywxX.js} +1 -1
  47. package/src/web/dist/assets/{vendor-JUtelXU0.js → vendor-C-lQMZp3.js} +94 -84
  48. package/src/web/dist/index.html +14 -11
  49. package/src/web/dist/landing.html +5 -5
  50. package/src/web/dist/assets/Events-BQ4Dkqon.js +0 -1
  51. package/src/web/dist/assets/Logs-BYFIK_hM.js +0 -1
  52. package/src/web/dist/assets/app-CRxPj2SJ.js +0 -61
  53. package/src/web/dist/assets/global-BQq8O0Tv.css +0 -1
  54. package/src/web/dist/assets/package-Dmrvm3RO.js +0 -1
@@ -1 +1 @@
1
- import{r as N,aX as vt,j as e,aY as Ue,aD as Ve,aZ as We,a_ as Je,am as q,aR as Nt,aS as wt,aT as kt,aI as Et,aJ as ze,aN as Ct,aO as St,aP as Rt,aQ as Dt,aK as Mt,aL as Pt,aM as Tt,a$ as Ot,Y as Bt}from"./vendor-JUtelXU0.js";import{g as Lt,u as Ft}from"./router-CqUBCAsx.js";import{C as Qe}from"./ConfirmDialog-CRSbmgE7.js";import{a as Ge}from"./PageState-XybOeENt.js";import{P as At}from"./PageToolbar-CnLp4aWt.js";import{t as J,q as Z,f as ae,B as F,T as $t,g as It,h as zt,i as Qt,C as ye,c as ve,b as _t}from"./app-CRxPj2SJ.js";import{d as _e,g as qe,b as He,c as qt,e as se,f as Ke,h as ne,m as ke,i as Ht,C as Xe,O as Ye,u as Kt}from"./modelManagement-DwdbGu0o.js";import{a as Ut}from"./query-CvboQrUT.js";import{g as ge}from"./gateway-DyhqzHSh.js";import{u as be}from"./useAppMutation-B29oVzxS.js";import{D as Ee,A as Ce,a as Se,b as Re,c as De,d as Me,e as Ze}from"./DialogShell-DxWKa5oR.js";import{L as K,I as G}from"./label-CdbE1ezd.js";import{S as Pe,a as Te,b as Oe,c as Be,d as Le,D as Vt}from"./disclosure-CU-KJc8C.js";import{S as Fe}from"./switch-CZn1nypU.js";import{u as I}from"./i18n-v60Yn7Ls.js";import{B as re}from"./badge-eRkhnmCs.js";import{c as je}from"./global-BLUcvOa8.js";import{T as fe}from"./TargetCombobox-DkVdA04_.js";import"./radix-d0BukFWM.js";import"./popover-CuM9b3U7.js";function Wt(a){const{t:s,pushToast:o,config:l,setConfig:r,configQuery:g,customEndpoints:f,tabs:m,ensureConfig:u}=a,c=Ut(),[b,y]=N.useState({}),[R,C]=N.useState({}),[p,w]=N.useState(null),[v,h]=N.useState({}),[x,D]=N.useState({}),[M,z]=N.useState({}),[U,V]=N.useState(null),[oe,ie]=N.useState(null),[le,de]=N.useState(null),[Ne,ce]=N.useState(!1),[ue,me]=N.useState(null),[W,X]=N.useState({}),[he,ee]=N.useState(null),_=N.useRef(null),[pe,te]=N.useState(null),H=t=>{_.current=t,te(t)},k=()=>{_.current=null,te(null)},T=N.useMemo(()=>m.filter(t=>t.key!=="providers"),[m]);N.useEffect(()=>{if(!g.data)return;const t=g.data;y(i=>{const n=_e(t,f);if(!i||Object.keys(i).length===0)return n;const d={...n};for(const[j,E]of Object.entries(i)){if(!(j in n))continue;const S=qe(t,f,j);if(He(E,S))d[j]=E;else{const L=new Map(E.map(O=>[O.source,O.id]));d[j]=n[j].map(O=>({...O,id:L.get(O.source)??O.id}))}}return d}),X(i=>{const n=qt(t,f);if(!i||Object.keys(i).length===0)return n;const d={...n};for(const[j,E]of Object.entries(i)){if(!(j in n))continue;const S=se(t,f,j);JSON.stringify(E)!==JSON.stringify(S)&&(d[j]=E)}return d}),C({}),h(Ke(t,f))},[g.data,f]);const Y=(l==null?void 0:l.providers)??[],Ae=t=>{const i=t==null?void 0:t.trim();if(!i||!i.includes(":"))return null;const n=i.split(":",1)[0].trim();return n?Y.some(d=>d.id===n)?null:n:i},et=N.useMemo(()=>{const t=[],i=new Set;for(const n of Y){const d=n.label&&n.label!==n.id?`${n.label} (${n.id})`:n.id,j=n.models??[];if(j.length>0)for(const S of j){const L=`${n.id}:${S.id}`;i.has(L)||(i.add(L),t.push({value:L,label:`${d} · ${S.label??S.id}`,providerId:n.id,providerLabel:d,modelId:S.id,modelLabel:S.label??S.id,kind:"model",isDefault:n.defaultModel===S.id}))}else if(n.defaultModel){const S=`${n.id}:${n.defaultModel}`;i.has(S)||(i.add(S),t.push({value:S,label:`${d} · ${n.defaultModel}`,providerId:n.id,providerLabel:d,modelId:n.defaultModel,modelLabel:n.defaultModel,kind:"model",isDefault:!0}))}const E=`${n.id}:*`;i.has(E)||(i.add(E),t.push({value:E,label:s("settings.routing.providerPassthroughOption",{provider:d}),providerId:n.id,providerLabel:d,modelId:"*",modelLabel:"*",kind:"passthrough"}))}for(const n of Object.values(b).flat()){const d=n.target.trim();d&&!i.has(d)&&(i.add(d),t.push({value:d,label:d,modelId:d,modelLabel:d,kind:"custom"}))}return t},[Y,b,s]),tt=t=>l?qe(l,f,t):{},st=N.useMemo(()=>{const t={};for(const i of T){const n=b[i.key]||[];t[i.key]=He(n,tt(i.key))}return t},[l,f,b,T]),nt=N.useMemo(()=>{const t={};if(!l)return t;for(const i of T){const n=W[i.key];if(!n){t[i.key]=!1;continue}const d=se(l,f,i.key);t[i.key]=JSON.stringify(n)!==JSON.stringify(d)}return t},[l,f,W,T]),at=(t,i,n)=>{X(d=>({...d,[t]:{...d[t]??{completion:null,reasoning:null,background:null,longContextThreshold:6e4},[i]:n}}))},rt=async t=>{var d,j,E,S,L,O,B,$;if(!u()||_.current)return;const i=W[t];if(!i)return;const n={completion:(d=i.completion)!=null&&d.trim()?i.completion.trim():null,reasoning:(j=i.reasoning)!=null&&j.trim()?i.reasoning.trim():null,background:(E=i.background)!=null&&E.trim()?i.background.trim():null,longContextThreshold:Number.isFinite(i.longContextThreshold)&&i.longContextThreshold>0?Math.floor(i.longContextThreshold):l.defaults.longContextThreshold};for(const A of[n.completion,n.reasoning,n.background]){const P=Ae(A);if(P){o({title:s("settings.validation.routeUnknownProvider",{provider:P}),variant:"error"});return}}ee(t),H(t);try{const A=f.find(P=>P.id===t);if(A){const P={...A.routing??{},defaults:n,modelRoutes:((S=A.routing)==null?void 0:S.modelRoutes)??{}};await ae.update(t,{routing:P}),r(Q=>{if(!Q)return Q;const xe=[...Q.customEndpoints??[]],we=xe.findIndex(yt=>yt.id===t);return we===-1?Q:(xe[we]={...xe[we],routing:P},{...Q,customEndpoints:xe})}),await c.invalidateQueries({queryKey:Z.customEndpoints.all()})}else{const P=t,Q={...l,endpointRouting:{...l.endpointRouting??{},[P]:{defaults:n,modelRoutes:((O=(L=l.endpointRouting)==null?void 0:L[P])==null?void 0:O.modelRoutes)??(P==="anthropic"?l.modelRoutes??{}:{}),compatibility:($=(B=l.endpointRouting)==null?void 0:B[P])==null?void 0:$.compatibility}}};await ge.saveConfig(Q),r(Q)}X(P=>({...P,[t]:n})),o({title:s("workbench.defaults.saveSuccess"),variant:"success"}),g.refetch()}catch(A){o({title:s("workbench.defaults.saveFailure",{message:J(A).message}),variant:"error"})}finally{ee(null),k()}},$e=(t,i)=>{h(n=>({...n,[t]:i})),r(n=>{if(!n)return n;if(t==="anthropic"||t==="openai")return{...n,routingPresets:{...n.routingPresets,[t]:i}};const d=[...n.customEndpoints??[]],j=d.findIndex(E=>E.id===t);return j===-1?n:(d[j]={...d[j],routingPresets:i},{...n,customEndpoints:d})})},ot=(t,i)=>{D(n=>({...n,[t]:i})),i.trim()&&z(n=>({...n,[t]:null}))},it=async t=>{if(!u()||_.current)return;const i=(x[t]??"").trim();if(!i){z(n=>({...n,[t]:s("modelManagement.validation.presetName")}));return}if((v[t]??[]).some(n=>n.name.toLowerCase()===i.toLowerCase())){z(n=>({...n,[t]:s("modelManagement.validation.presetDuplicate",{name:i})}));return}V(t),H(t);try{const d=(await ke.savePreset(t,i)).presets??[];$e(t,d),D(j=>({...j,[t]:""})),z(j=>({...j,[t]:null})),o({title:s("modelManagement.toast.presetSaved",{name:i}),variant:"success"})}catch(n){o({title:s("modelManagement.toast.presetSaveFailure",{message:J(n).message}),variant:"error"})}finally{V(null),k(),g.refetch()}},lt=async(t,i)=>{if(u()&&!_.current){ie({endpoint:t,name:i.name}),H(t);try{const d=(await ke.applyPreset(t,i.name)).config;r(d);const j=_e(d,f);y(E=>({...E,[t]:j[t]??[]})),Ie(t,se(l,f,t),se(d,f,t)),h(Ke(d,f)),t!=="anthropic"&&t!=="openai"&&await c.invalidateQueries({queryKey:Z.customEndpoints.all()}),o({title:s("modelManagement.toast.presetApplySuccess",{name:i.name}),variant:"success"})}catch(n){o({title:s("modelManagement.toast.presetApplyFailure",{message:J(n).message}),variant:"error"})}finally{ie(null),k(),g.refetch()}}},dt=async(t,i)=>{if(u()&&!_.current){de({endpoint:t,name:i.name}),H(t);try{const n=await ke.deletePreset(t,i.name);$e(t,n.presets??[]),o({title:s("modelManagement.toast.presetDeleteSuccess",{name:i.name}),variant:"success"})}catch(n){o({title:s("modelManagement.toast.presetDeleteFailure",{message:J(n).message}),variant:"error"})}finally{de(null),k(),g.refetch()}}},ct=async t=>{const i=f.find(n=>n.id===t);if(!(!i||i.deletable===!1))try{await ae.delete(t),await c.invalidateQueries({queryKey:Z.customEndpoints.all()}),r(n=>n&&{...n,customEndpoints:(n.customEndpoints??[]).filter(d=>d.id!==t)}),g.refetch(),o({title:s("modelManagement.deleteEndpointSuccess"),variant:"success"})}catch(n){const d=J(n);o({title:s("modelManagement.deleteEndpointError",{error:d.message}),variant:"error"})}},ut=t=>{y(i=>({...i,[t]:[...i[t]||[],{id:ne(),source:"",target:""}]})),C(i=>({...i,[t]:null}))},mt=async(t,i)=>{if(u()&&!_.current){ce(!0),H(t);try{if(t==="anthropic"||t==="openai"){const n=t,d=l.endpointRouting?{...l.endpointRouting}:{},j=d[n]??{defaults:l.defaults,modelRoutes:(n==="anthropic"?l.modelRoutes:{})??{}},E={defaults:j.defaults??l.defaults,modelRoutes:j.modelRoutes??{}},S={...l,endpointRouting:{...d,[n]:i?{...E,compatibility:{enabled:!0}}:{...E}}};await ge.saveConfig(S),r(S)}else{const n=[...l.customEndpoints??[]],d=n.findIndex(L=>L.id===t);if(d===-1)throw new Error(s("modelManagement.toast.endpointNotFound"));const j=n[d],E=j.routing??{defaults:l.defaults,modelRoutes:{}};n[d]={...j,routing:i?{...E,compatibility:{enabled:!0}}:{defaults:E.defaults,modelRoutes:E.modelRoutes}};const S={...l,customEndpoints:n};await ge.saveConfig(S),r(S)}o({title:s("modelManagement.toast.compatibilitySaved",{state:s(i?"common.status.enabled":"common.status.disabled")}),variant:"success"}),g.refetch()}catch(n){const d=J(n);o({title:s("modelManagement.toast.compatibilitySaveFailure",{message:d.message}),variant:"error"})}finally{ce(!1),k()}}},ht=(t,i)=>{y(n=>{const d=n[t]||[];return d.some(j=>j.source.trim()===i.trim())?n:{...n,[t]:[...d,{id:ne(),source:i,target:""}]}}),C(n=>({...n,[t]:null}))},pt=(t,i,n,d)=>{y(j=>({...j,[t]:(j[t]||[]).map(E=>E.id===i?{...E,[n]:d}:E)})),C(j=>({...j,[t]:null}))},xt=(t,i)=>{y(n=>({...n,[t]:(n[t]||[]).filter(d=>d.id!==i)})),C(n=>({...n,[t]:null}))},gt=(t,i,n)=>{i!==n&&(y(d=>{const j=d[t]||[],E=j.findIndex(L=>L.id===i),S=j.findIndex(L=>L.id===n);return E===-1||S===-1?d:{...d,[t]:vt(j,E,S)}}),C(d=>({...d,[t]:null})))},ft=t=>{var n;if(!l)return;const i=(l.customEndpoints??f).find(d=>d.id===t);if(i)y(d=>{var j;return{...d,[t]:Object.entries(((j=i.routing)==null?void 0:j.modelRoutes)??{}).map(([E,S])=>({id:ne(),source:E,target:S}))}});else{const d=l.endpointRouting??{},j=t,E=j==="anthropic"?l.modelRoutes??{}:{},S=((n=d[j])==null?void 0:n.modelRoutes)??E;y(L=>({...L,[t]:Object.entries(S).map(([O,B])=>({id:ne(),source:O,target:B}))}))}C(d=>({...d,[t]:null}))},bt=be({mutationFn:async t=>(await ge.saveConfig(t.nextConfig),t)}),jt=be({mutationFn:async t=>(await ae.update(t.endpoint,{routing:t.routing}),t)}),Ie=(t,i,n)=>{X(d=>{const j=d[t];return j&&JSON.stringify(j)!==JSON.stringify(i)?d:{...d,[t]:n}})};return{endpointTabs:T,routesByEndpoint:b,setRoutesByEndpoint:y,routeError:R,savingRouteFor:p,presetsByEndpoint:v,presetNameByEndpoint:x,presetErrorByEndpoint:M,savingPresetFor:U,applyingPreset:oe,deletingPreset:le,savingCompatibilityPolicy:Ne,writingEndpoint:pe,presetDiffDialog:ue,setPresetDiffDialog:me,providerModelOptions:et,isDirtyByEndpoint:st,defaultsByEndpoint:W,isDefaultsDirtyByEndpoint:nt,savingDefaultsFor:he,handleDefaultsChange:at,handleSaveDefaults:rt,handlePresetNameChange:ot,handleSavePreset:it,handleApplyPreset:lt,handleDeletePreset:dt,handleDeleteEndpoint:ct,handleAddRoute:ut,handleAddSuggestion:ht,handleRouteChange:pt,handleRemoveRoute:xt,handleReorderRules:gt,handleResetRoutes:ft,handleSaveRoutes:async t=>{var d,j,E,S,L;if(!u()||_.current)return;const i=b[t]||[],n={};for(const O of i){const B=O.source.trim(),$=O.target.trim();if(!B&&!$)continue;if(!B||!$){C(P=>({...P,[t]:s("settings.validation.routePair")}));return}if(n[B]){C(P=>({...P,[t]:s("settings.validation.routeDuplicate",{model:B})}));return}const A=Ae($);if(A){C(P=>({...P,[t]:s("settings.validation.routeUnknownProvider",{provider:A})}));return}n[B]=$}C(O=>({...O,[t]:null})),w(t),H(t);try{const O=f.find(B=>B.id===t);if(O){const B={...O.routing??{},modelRoutes:n,defaults:((d=O.routing)==null?void 0:d.defaults)||l.defaults};await jt.mutateAsync({endpoint:t,routing:B}),r($=>{if(!$)return $;const A=[...$.customEndpoints??[]],P=A.findIndex(Q=>Q.id===t);return P===-1?$:(A[P]={...A[P],routing:B},{...$,customEndpoints:A})}),await c.invalidateQueries({queryKey:Z.customEndpoints.all()}),Ie(t,se(l,f,t),B.defaults)}else{const B={...l,endpointRouting:{...l.endpointRouting??{},[t]:{defaults:((E=(j=l.endpointRouting)==null?void 0:j[t])==null?void 0:E.defaults)??l.defaults,modelRoutes:n,compatibility:(L=(S=l.endpointRouting)==null?void 0:S[t])==null?void 0:L.compatibility}},modelRoutes:t==="anthropic"?n:l.modelRoutes??{}};await bt.mutateAsync({endpoint:t,nextConfig:B}),r(B)}y(B=>{const $=B[t]??[],A=new Map($.map(P=>[P.source.trim(),P.id]));return{...B,[t]:Object.entries(n).map(([P,Q])=>({id:A.get(P.trim())??ne(),source:P,target:Q}))}}),o({title:s("modelManagement.toast.routesSaved"),variant:"success"}),g.refetch()}catch(O){o({title:s("modelManagement.toast.routesSaveFailure",{message:J(O).message}),variant:"error"})}finally{w(null),k()}},handleCompatibilityEnabledChange:mt}}const Jt=["anthropic","openai-auto","openai-chat","openai-responses"];function Gt({open:a,endpoint:s,onClose:o,onSuccess:l}){const{t:r}=I(),[g,f]=N.useState(!1),[m,u]=N.useState({id:"",label:"",paths:[{path:"",protocol:"openai-auto"}],enabled:!0});N.useEffect(()=>{if(a){if(f(!1),s){const h=s.paths&&s.paths.length>0?s.paths:s.path&&s.protocol?[{path:s.path,protocol:s.protocol}]:[{path:"",protocol:"openai-auto"}];u({id:s.id,label:s.label,paths:h,enabled:s.enabled!==!1});return}u({id:"",label:"",paths:[{path:"",protocol:"openai-auto"}],enabled:!0})}},[s,a]);const c=be({mutationFn:ae.create,invalidateKeys:[Z.customEndpoints.all()],successToast:()=>({title:r("modelManagement.createEndpointSuccess")}),errorToast:h=>({title:r("modelManagement.createEndpointError",{error:h.message})}),onSuccess:async h=>{var x;l((x=h.endpoint)==null?void 0:x.id),o()}}),b=be({mutationFn:h=>ae.update(h.id,h.updates),invalidateKeys:[Z.customEndpoints.all()],successToast:()=>({title:r("modelManagement.updateEndpointSuccess")}),errorToast:h=>({title:r("modelManagement.updateEndpointError",{error:h.message})}),onSuccess:async()=>{l(),o()}}),y=()=>{u(h=>({...h,paths:[...h.paths,{path:"",protocol:"anthropic"}]}))},R=h=>{m.paths.length!==1&&u(x=>({...x,paths:x.paths.filter((D,M)=>M!==h)}))},C=(h,x,D)=>{u(M=>{const z=[...M.paths];return z[h]={...z[h],[x]:D},{...M,paths:z}})},p=h=>{if(h==null||h.preventDefault(),f(!0),!m.id.trim()||!m.label.trim())return;for(const D of m.paths)if(!D.path.trim())return;const x=m.paths.map(D=>({path:D.path.trim(),protocol:D.protocol}));if(s){b.mutate({id:s.id,updates:{label:m.label.trim(),paths:x,enabled:m.enabled}});return}c.mutate({id:m.id.trim(),label:m.label.trim(),paths:x,enabled:m.enabled})},w=c.isPending||b.isPending,v=m.paths.length===0?r("modelManagement.atLeastOnePath"):!m.id.trim()||!m.label.trim()?r("modelManagement.endpointValidationError"):m.paths.some(h=>!h.path.trim())?r("modelManagement.pathValidationError"):null;return e.jsx(Ee,{open:a,onOpenChange:h=>!h&&o(),children:e.jsxs(Ce,{className:"max-w-lg",onInteractOutside:h=>h.preventDefault(),children:[e.jsxs(Se,{children:[e.jsx(Re,{children:r(s?"modelManagement.editEndpoint":"modelManagement.createEndpoint")}),e.jsx(De,{className:"truncate font-mono text-xs",children:s?s.id:r("modelManagement.endpointRoutingHint")})]}),e.jsx(Me,{children:e.jsxs("form",{id:"endpoint-form",onSubmit:p,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(K,{children:[r("modelManagement.endpointId")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(G,{value:m.id,onChange:h=>u(x=>({...x,id:h.target.value})),placeholder:r("modelManagement.endpointIdPlaceholder"),disabled:!!s}),e.jsx("p",{className:"text-xs text-muted-foreground",children:r("modelManagement.endpointIdHint")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(K,{children:[r("modelManagement.endpointLabel")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(G,{value:m.label,onChange:h=>u(x=>({...x,label:h.target.value})),placeholder:r("modelManagement.endpointLabelPlaceholder")})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(K,{children:[r("modelManagement.endpointPaths")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsxs(F,{type:"button",variant:"ghost",size:"sm",onClick:y,children:[e.jsx(Ue,{className:"mr-1 h-3 w-3"}),r("modelManagement.addPath")]})]}),e.jsx("div",{className:"space-y-3",children:m.paths.map((h,x)=>e.jsxs("div",{className:"space-y-2 border border-border bg-card p-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(G,{value:h.path,onChange:D=>C(x,"path",D.target.value),placeholder:r("modelManagement.endpointPathPlaceholder")}),e.jsxs(Pe,{value:h.protocol,onValueChange:D=>C(x,"protocol",D),children:[e.jsx(Te,{children:e.jsx(Oe,{})}),e.jsx(Be,{children:Jt.map(D=>e.jsx(Le,{value:D,children:r(D==="anthropic"?"modelManagement.protocolAnthropic":D==="openai-auto"?"modelManagement.protocolOpenAI":D==="openai-chat"?"modelManagement.protocolOpenAIChat":"modelManagement.protocolOpenAIResponses")},D))})]})]}),m.paths.length>1?e.jsx(F,{type:"button",variant:"ghost",size:"sm",onClick:()=>R(x),className:"text-destructive",children:e.jsx(Ve,{className:"h-4 w-4"})}):null]}),e.jsxs("div",{className:"space-y-1 text-xs text-muted-foreground",children:[x===0?e.jsx("p",{children:r("modelManagement.endpointPathHint")}):null,e.jsx("p",{children:r(`modelManagement.protocolHints.${h.protocol}`)})]})]},`${h.protocol}-${x}`))}),v&&g?e.jsx("p",{className:"text-xs text-destructive",children:v}):null]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Fe,{id:"endpoint-enabled",checked:m.enabled,onCheckedChange:h=>u(x=>({...x,enabled:h}))}),e.jsx(K,{htmlFor:"endpoint-enabled",children:r("modelManagement.endpointEnabled")})]}),s?null:e.jsx("div",{className:"rounded-xl bg-secondary p-4",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:r("modelManagement.endpointRoutingHint")})})]})}),e.jsxs(Ze,{children:[e.jsx(F,{variant:"outline",onClick:o,disabled:w,children:r("common.cancel")}),e.jsx(F,{type:"submit",form:"endpoint-form",disabled:w,children:r(w?"common.saving":s?"common.save":"common.create")})]})]})})}function Xt({tabs:a,customEndpoints:s,routeCounts:o,selectedEndpointId:l,onSelect:r,onEditEndpoint:g,onDeleteEndpoint:f}){var b;const{t:m}=I(),u=s.find(y=>y.id===l),c=u?u.label||u.id:((b=a.find(y=>y.key===l))==null?void 0:b.label)??l;return e.jsxs("div",{className:"flex items-center gap-1.5 lg:hidden",children:[e.jsxs(Pe,{value:l,onValueChange:r,children:[e.jsx(Te,{"data-testid":"routing-endpoint-switcher","aria-label":m("workbench.endpointSwitcher.label"),className:"h-8 w-[230px] text-xs",children:e.jsx(Oe,{children:c})}),e.jsx(Be,{children:a.map(y=>{const R=s.find(w=>w.id===y.key),C=R?R.label||R.id:y.label,p=o[y.key]??0;return e.jsx(Le,{value:y.key,className:"text-xs",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:C}),e.jsx("span",{className:"shrink-0 tabular-nums text-muted-foreground",children:m("workbench.endpointSwitcher.ruleCount",{count:p})})]})},y.key)})})]}),u?e.jsxs(e.Fragment,{children:[e.jsx(F,{variant:"ghost",size:"icon","data-testid":"endpoint-edit",className:"h-7 w-7",title:m("common.edit"),"aria-label":m("common.edit"),onClick:()=>g(u),children:e.jsx(We,{className:"h-3.5 w-3.5","aria-hidden":!0})}),u.deletable!==!1?e.jsx(F,{variant:"ghost",size:"icon","data-testid":"endpoint-delete",className:"h-7 w-7 text-muted-foreground hover:text-destructive",title:m("common.delete"),"aria-label":m("common.delete"),onClick:()=>f(u),children:e.jsx(Je,{className:"h-3.5 w-3.5","aria-hidden":!0})}):null]}):null]})}function Yt({dialog:a,currentRoutes:s,onConfirm:o,onClose:l}){const{t:r}=I();if(!a)return null;const{endpoint:g,preset:f}=a,m=f.modelRoutes??{},u={};for(const p of s){const w=p.source.trim(),v=p.target.trim();w&&v&&(u[w]=v)}const c=new Set([...Object.keys(u),...Object.keys(m)]),b=[],y=[],R=[];for(const p of c){const w=p in u,v=p in m;v&&!w?b.push([p,m[p]]):w&&!v?y.push([p,u[p]]):w&&v&&u[p]!==m[p]&&R.push([p,u[p],m[p]])}const C=b.length>0||y.length>0||R.length>0;return e.jsx(Ee,{open:!0,onOpenChange:p=>!p&&l(),children:e.jsxs(Ce,{className:"max-w-2xl",children:[e.jsxs(Se,{children:[e.jsx(Re,{children:r("modelManagement.presets.diffTitle")}),e.jsx(De,{children:r("modelManagement.presets.diffDescription",{name:f.name})})]}),e.jsx(Me,{children:C?e.jsxs("div",{className:"max-h-80 space-y-2 rounded-xl bg-secondary/50 p-3 text-sm",children:[b.map(([p,w])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-success-bg px-2 py-1.5 text-success",children:[e.jsx(re,{variant:"outline",className:"border-success/30 text-xs",children:r("modelManagement.presets.diffAdded")}),e.jsx("span",{className:"truncate",children:p}),e.jsx(q,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:w})]},`add-${p}`)),y.map(([p,w])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-error-bg px-2 py-1.5 text-error",children:[e.jsx(re,{variant:"outline",className:"border-error/30 text-xs",children:r("modelManagement.presets.diffRemoved")}),e.jsx("span",{className:"truncate",children:p}),e.jsx(q,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:w})]},`rm-${p}`)),R.map(([p,w,v])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-warning-bg px-2 py-1.5 text-warning",children:[e.jsx(re,{variant:"outline",className:"border-warning/30 text-xs",children:r("modelManagement.presets.diffChanged")}),e.jsx("span",{className:"truncate",children:p}),e.jsx(q,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate line-through opacity-60",children:w}),e.jsx(q,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:v})]},`chg-${p}`))]}):e.jsx("p",{className:"rounded-xl bg-secondary/50 py-8 text-center text-sm text-muted-foreground",children:r("modelManagement.presets.diffEmpty")})}),e.jsxs(Ze,{children:[e.jsx(F,{variant:"outline",onClick:l,children:r("common.cancel")}),e.jsx(F,{onClick:()=>o(g,f),disabled:!C,children:r("modelManagement.presets.diffConfirm")})]})]})})}function Zt({routing:a,endpoint:s,onRequestDeletePreset:o,embedded:l=!1}){var p,w;const{t:r}=I(),g=a.presetsByEndpoint[s]??[],f=a.presetNameByEndpoint[s]??"",m=a.presetErrorByEndpoint[s],u=a.savingPresetFor===s,c=((p=a.applyingPreset)==null?void 0:p.endpoint)===s?a.applyingPreset.name:null,b=((w=a.deletingPreset)==null?void 0:w.endpoint)===s?a.deletingPreset.name:null,y=a.writingEndpoint===s,R=!!a.isDirtyByEndpoint[s],C=e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(G,{"data-testid":"preset-name-input",value:f,onChange:v=>a.handlePresetNameChange(s,v.target.value),placeholder:r("modelManagement.presets.namePlaceholder"),disabled:u,className:"h-8 flex-1 text-xs"}),e.jsx(F,{variant:"outline",size:"sm","data-testid":"save-preset",onClick:()=>void a.handleSavePreset(s),disabled:u||y||R,children:r(u?"modelManagement.presets.saving":"modelManagement.presets.save")})]}),R?e.jsx("p",{className:"text-[11px] text-warning",children:r("modelManagement.presets.dirtyBlocked")}):null,m?e.jsx("p",{className:"text-xs text-destructive",children:m}):null,g.length===0?e.jsx("p",{className:"py-2 text-center text-[11px] text-muted-foreground",children:r("modelManagement.presets.empty")}):e.jsx($t,{children:e.jsx("div",{className:"grid grid-cols-1 gap-1.5 sm:grid-cols-2",children:g.map(v=>{const h=c===v.name,x=b===v.name,D=Object.entries(v.modelRoutes??{}),M=D.length;return e.jsxs("div",{"data-testid":"preset-row",className:"flex items-center justify-between gap-2 border border-border bg-secondary/40 px-2.5 py-2",children:[e.jsxs(It,{children:[e.jsx(zt,{asChild:!0,children:e.jsxs("div",{className:"min-w-0 flex-1 cursor-default",children:[e.jsx("span",{className:"block truncate text-[11px] font-medium",children:v.name}),e.jsx(re,{variant:"outline",className:"mt-0.5 text-[10px] font-normal",children:M>0?r("modelManagement.presets.rulesCount",{count:M}):r("modelManagement.presets.noRules")})]})}),M>0?e.jsx(Qt,{side:"bottom",className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1 text-xs",children:[D.slice(0,5).map(([z,U])=>e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"truncate",children:z}),e.jsx(q,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:U})]},z)),M>5?e.jsxs("div",{className:"text-muted-foreground",children:["…+",M-5]}):null]})}):null]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"apply-preset",className:"text-[11px] font-semibold text-foreground underline decoration-muted-foreground/40 underline-offset-2 hover:decoration-foreground disabled:opacity-50",onClick:()=>a.setPresetDiffDialog({endpoint:s,preset:v}),disabled:h||x||y,children:r(h?"modelManagement.presets.applying":"modelManagement.presets.apply")}),e.jsx("button",{type:"button","data-testid":"delete-preset",className:"text-[11px] text-muted-foreground hover:text-destructive disabled:opacity-50","aria-label":r("common.delete"),onClick:()=>o(s,v),disabled:x||h||y,children:r(x?"modelManagement.presets.deleting":"modelManagement.presets.delete")})]})]},v.name)})})})]});return l?e.jsx("div",{"data-testid":"routing-presets-card",children:C}):e.jsx(ye,{"data-testid":"routing-presets-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(ve,{className:"space-y-3 p-4",children:[e.jsx("h3",{className:"text-[13px] font-semibold",children:r("modelManagement.presets.title")}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:r("modelManagement.presets.description")}),C]})})}function es({open:a,onOpenChange:s,routing:o,endpoint:l,onRequestDeletePreset:r}){const{t:g}=I();return e.jsx(Ee,{open:a,onOpenChange:s,children:e.jsxs(Ce,{className:"max-w-lg",children:[e.jsxs(Se,{children:[e.jsx(Re,{children:g("modelManagement.presets.title")}),e.jsx(De,{className:"text-xs",children:g("modelManagement.presets.description")})]}),e.jsx(Me,{children:e.jsx(Zt,{routing:o,endpoint:l,embedded:!0,onRequestDeletePreset:r})})]})})}function ts({routing:a,endpoint:s,tabInfo:o,config:l,customEndpoints:r}){var v,h;const{t:g}=I(),f=a.routesByEndpoint[s]||[],m=a.savingRouteFor===s,u=a.savingCompatibilityPolicy,c=a.writingEndpoint===s,b=((v=o==null?void 0:o.protocols)==null?void 0:v.some(x=>x.startsWith("openai")))??s==="openai",y=Ht(s,l,r),R=b?(y==null?void 0:y.enabled)??!1:!1,p=((h=o==null?void 0:o.protocols)==null?void 0:h.includes("anthropic"))??s==="anthropic"?Xe:Ye,w=new Set(f.map(x=>x.source.trim()).filter(Boolean));return e.jsx(ye,{"data-testid":"endpoint-config-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(ve,{className:"space-y-3 p-4",children:[e.jsx("h3",{className:"text-[12.5px] font-semibold",children:g("workbench.endpointConfig.title")}),b?e.jsxs("div",{className:"flex items-center justify-between gap-2 border border-border/60 bg-secondary/30 px-2.5 py-2",children:[e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsx(K,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:g("modelManagement.openaiCompatibility.toggleLabel")}),e.jsx("p",{className:"text-[10.5px] text-muted-foreground",children:g(R?"modelManagement.openaiCompatibility.enabledHint":"modelManagement.openaiCompatibility.disabledHint")})]}),e.jsx(Fe,{"data-testid":"compatibility-toggle",checked:R,onCheckedChange:x=>void a.handleCompatibilityEnabledChange(s,x),disabled:u||c,"aria-label":g("modelManagement.openaiCompatibility.toggleLabel")})]}):null,e.jsxs("div",{children:[e.jsx("p",{className:"mb-1.5 text-[11px] text-muted-foreground",children:g("settings.routing.suggested")}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:p.map(x=>{const D=w.has(x);return e.jsx("button",{"data-testid":"suggestion-chip",type:"button",onClick:()=>a.handleAddSuggestion(s,x),disabled:m||D,className:je("h-6 border px-2 text-[10.5px] transition-colors",D?"border-border bg-secondary/40 text-muted-foreground/50":"border-border bg-card hover:border-foreground hover:text-foreground"),children:x},`${s}-${x}`)})})]})]})})}function ss({routing:a,endpoint:s}){const{t:o}=I(),l=a.defaultsByEndpoint[s]??null,r=a.isDefaultsDirtyByEndpoint[s]??!1,g=a.savingDefaultsFor===s,f=a.writingEndpoint===s,m=a.providerModelOptions;return e.jsx(ye,{"data-testid":"routing-defaults-card",className:"border-foreground bg-secondary shadow-none",children:e.jsxs(ve,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-[13px] font-semibold text-foreground",children:o("workbench.defaults.title")}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:o("workbench.defaults.cardSubtitle")})]}),e.jsxs(Vt,{summary:e.jsx("span",{className:"text-[11px] font-medium text-muted-foreground",children:o("workbench.defaults.moreLabel")}),summaryClassName:"px-2 py-1",contentClassName:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(K,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:o("workbench.defaults.reasoningLabel")}),e.jsx(fe,{value:(l==null?void 0:l.reasoning)??"",onChange:u=>a.handleDefaultsChange(s,"reasoning",u),options:m,disabled:g,ariaLabel:o("workbench.defaults.reasoningLabel"),placeholder:o("workbench.defaults.targetPlaceholder")})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(K,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:o("workbench.defaults.backgroundLabel")}),e.jsx(fe,{value:(l==null?void 0:l.background)??"",onChange:u=>a.handleDefaultsChange(s,"background",u),options:m,disabled:g,ariaLabel:o("workbench.defaults.backgroundLabel"),placeholder:o("workbench.defaults.targetPlaceholder")})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(K,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:o("workbench.defaults.thresholdLabel")}),e.jsx(G,{type:"number",min:1,value:(l==null?void 0:l.longContextThreshold)||"",onChange:u=>{const c=Number.parseInt(u.target.value,10);a.handleDefaultsChange(s,"longContextThreshold",Number.isFinite(c)?c:0)},disabled:g,className:"md:w-56"})]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"border border-border bg-card px-2.5 py-2 font-mono text-xs",children:"*"}),e.jsx(q,{className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground","aria-hidden":!0}),e.jsx("div",{"data-testid":"default-target",className:"min-w-[180px] flex-1",children:e.jsx(fe,{value:(l==null?void 0:l.completion)??"",onChange:u=>a.handleDefaultsChange(s,"completion",u),options:m,disabled:g,ariaLabel:o("workbench.defaults.completionLabel"),placeholder:o("workbench.defaults.targetPlaceholder")})}),e.jsxs(F,{variant:"outline",size:"sm","data-testid":"save-defaults",onClick:()=>void a.handleSaveDefaults(s),disabled:g||!r||f,className:"relative",children:[o(g?"common.actions.saving":"workbench.defaults.save"),r?e.jsx("span",{className:"absolute -right-1 -top-1 h-2 w-2 rounded-full bg-warning"}):null]})]})]})})}function ns({tabs:a,customEndpoints:s,routeCounts:o,selectedEndpointId:l,onSelect:r,onEditEndpoint:g,onDeleteEndpoint:f}){const{t:m}=I(),u=a.map(c=>{const b=s.find(y=>y.id===c.key);return b?{key:c.key,label:b.label||b.id,enabled:b.enabled!==!1,custom:b}:{key:c.key,label:c.label,enabled:!0}});return e.jsxs("aside",{"data-testid":"endpoint-rail","aria-label":m("workbench.endpointRail.title"),className:"hidden lg:flex lg:sticky lg:top-4 flex-col gap-1 border border-border bg-card p-1.5 shadow-[var(--surface-shadow)] lg:max-h-[calc(100vh-2rem)] lg:overflow-y-auto",children:[e.jsxs("div",{className:"px-2 pb-1 pt-2",children:[e.jsx("h2",{className:"text-[12.5px] font-semibold",children:m("workbench.endpointRail.title")}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:m("workbench.endpointRail.subtitle")})]}),u.map(c=>{const b=c.key===l,y=o[c.key]??0,R=!c.enabled;return e.jsxs("div",{"data-testid":"routing-endpoint-row",className:je("flex items-stretch border transition-colors",b?"border-foreground bg-secondary":"border-transparent hover:bg-accent",R?"opacity-60":""),children:[e.jsxs("button",{type:"button",onClick:()=>r(c.key),"aria-current":b?"true":void 0,className:"flex min-w-0 flex-1 items-center gap-2 px-2 py-2 text-left",children:[e.jsx("span",{className:je("h-1.5 w-1.5 shrink-0 rounded-full",R?"bg-muted-foreground/30":b?"bg-foreground":"bg-muted-foreground/50"),"aria-hidden":!0}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-xs font-medium",title:c.label,children:c.label}),e.jsx("span",{className:"shrink-0 text-[10.5px] tabular-nums text-muted-foreground",children:m("workbench.endpointRail.ruleCount",{count:y})})]}),c.custom?e.jsxs("div",{className:"flex items-center gap-0.5 pr-1",children:[e.jsx("button",{type:"button","data-testid":"endpoint-edit",onClick:()=>g(c.custom),className:"flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-foreground",title:m("common.edit"),"aria-label":m("common.edit"),children:e.jsx(We,{className:"h-3 w-3","aria-hidden":!0})}),c.custom.deletable!==!1?e.jsx("button",{type:"button","data-testid":"endpoint-delete",onClick:()=>f(c.custom),className:"flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-destructive",title:m("common.delete"),"aria-label":m("common.delete"),children:e.jsx(Je,{className:"h-3 w-3","aria-hidden":!0})}):null]}):null]},c.key)})]})}function as({endpointPath:a,defaultTarget:s}){const{t:o}=I();return e.jsxs("section",{"data-testid":"routing-flow-banner",className:"flex flex-wrap items-center gap-x-3 gap-y-2 border border-border bg-card px-4 py-3 shadow-[var(--surface-shadow)]",children:[e.jsx("span",{className:"text-[10.5px] font-semibold uppercase tracking-[0.06em] text-muted-foreground",children:o("workbench.flow.title")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[e.jsx("span",{className:"border border-border bg-secondary px-2.5 py-1 font-mono text-[11px]",children:o("workbench.flow.clientStep")}),e.jsx(q,{className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0}),e.jsxs("span",{className:"border border-border bg-secondary px-2.5 py-1 text-[11px]",children:[o("workbench.flow.endpointStep")," ",e.jsx("span",{className:"font-mono",children:a})]}),e.jsx(q,{className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0}),e.jsx("span",{className:"border border-foreground bg-secondary px-2.5 py-1 text-[11px] font-semibold text-foreground",children:o("workbench.flow.matchStep")}),e.jsx(q,{className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0}),e.jsx("span",{className:"border border-border bg-secondary px-2.5 py-1 font-mono text-[11px]",children:s||o("workbench.flow.fallbackNote")})]})]})}function rs({entry:a,index:s,savingRoute:o,options:l,sourceListId:r,onRouteChange:g,onRemoveRoute:f}){const{t:m}=I(),{attributes:u,listeners:c,setNodeRef:b,setActivatorNodeRef:y,transform:R,transition:C,isDragging:p}=Nt({id:a.id});return e.jsxs("div",{ref:b,"data-testid":"route-rule-row","data-id":a.id,style:{transform:kt.Transform.toString(R),transition:C},className:je("grid grid-cols-[auto_auto_minmax(0,1fr)_auto] items-center gap-x-2 gap-y-1.5 border border-border bg-card p-2 sm:flex sm:gap-2",p&&"z-10 opacity-60 shadow-[var(--surface-shadow-lg)]"),children:[e.jsx("button",{ref:y,type:"button","data-testid":"route-rule-grip","aria-label":m("workbench.routing.dragHandle"),className:"row-span-2 flex h-7 w-4 shrink-0 cursor-grab touch-none items-center justify-center text-muted-foreground hover:text-foreground active:cursor-grabbing sm:row-span-1",...u,...c,children:e.jsx(wt,{className:"h-4 w-4","aria-hidden":!0})}),e.jsx("span",{className:"w-4 shrink-0 text-center text-[10.5px] tabular-nums text-muted-foreground",children:s+1}),e.jsx(G,{"data-testid":"route-rule-source",value:a.source,onChange:w=>g(a.id,"source",w.target.value),placeholder:m("settings.routing.sourcePlaceholder"),list:r,disabled:o,className:"h-8 min-w-0 flex-1 text-xs"}),e.jsx(q,{className:"col-start-2 row-start-2 h-3.5 w-3.5 shrink-0 text-muted-foreground sm:col-auto sm:row-auto","aria-hidden":!0}),e.jsx("div",{"data-testid":"route-rule-target",className:"col-start-3 row-start-2 min-w-0 sm:col-auto sm:row-auto sm:flex-[1.15]",children:e.jsx(fe,{value:a.target,onChange:w=>g(a.id,"target",w),options:l,disabled:o,ariaLabel:m("workbench.routing.targetLabel"),placeholder:m("settings.routing.targetPlaceholder")})}),e.jsx(F,{variant:"ghost",size:"icon","data-testid":"route-rule-delete",className:"col-start-4 row-span-2 h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive sm:col-auto sm:row-span-1",onClick:()=>f(a.id),disabled:o,"aria-label":m("common.delete"),children:e.jsx(Ve,{className:"h-3.5 w-3.5","aria-hidden":!0})})]})}function os({routing:a,endpoint:s,tabInfo:o}){var w;const{t:l}=I(),r=a.routesByEndpoint[s]||[],g=a.routeError[s],f=a.savingRouteFor===s,m=a.isDirtyByEndpoint[s]??!1,u=a.writingEndpoint===s,c=a.providerModelOptions,b=`route-source-${s}`,y=Et(ze(Tt,{activationConstraint:{distance:6}}),ze(Pt,{coordinateGetter:Mt})),R=v=>{const{active:h,over:x}=v;!x||h.id===x.id||a.handleReorderRules(s,String(h.id),String(x.id))},p=((w=o==null?void 0:o.protocols)==null?void 0:w.includes("anthropic"))??s==="anthropic"?Xe:Ye;return e.jsx(ye,{"data-testid":"routing-rules-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(ve,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h3",{className:"flex items-center gap-2 text-[13px] font-semibold",children:[l("workbench.routing.rulesTitle"),e.jsx(re,{variant:"outline",className:"text-[10.5px] font-normal tabular-nums",children:r.length})]}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:l("workbench.routing.rulesSubtitle")})]}),e.jsx(F,{variant:"outline",size:"sm","data-testid":"add-route",onClick:()=>a.handleAddRoute(s),disabled:f,children:l("settings.routing.add")})]}),g?e.jsx("p",{className:"text-xs text-destructive",children:g}):null,r.length===0?e.jsx(Ge,{compact:!0,title:l("workbench.routing.emptyTitle"),description:l("workbench.routing.emptyDescription"),action:e.jsx(F,{variant:"outline",size:"sm",onClick:()=>a.handleAddRoute(s),disabled:f,children:l("workbench.routing.addFirst")})}):e.jsx(Ct,{sensors:y,collisionDetection:St,onDragEnd:R,children:e.jsx(Rt,{items:r.map(v=>v.id),strategy:Dt,children:e.jsx("div",{className:"flex flex-col gap-1.5",children:r.map((v,h)=>e.jsx(rs,{entry:v,index:h,savingRoute:f,options:c,sourceListId:b,onRouteChange:(x,D,M)=>a.handleRouteChange(s,x,D,M),onRemoveRoute:x=>a.handleRemoveRoute(s,x)},v.id))})})}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-t border-border/60 pt-3",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:l(m?"modelManagement.actions.footerDirtyHint":"modelManagement.actions.footerSavedHint")}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(F,{variant:"outline",size:"sm","data-testid":"reset-routes",onClick:()=>a.handleResetRoutes(s),disabled:f||!m,children:l("common.actions.reset")}),e.jsxs(F,{variant:"outline",size:"sm","data-testid":"save-routes",onClick:()=>void a.handleSaveRoutes(s),disabled:f||u,className:"relative",children:[l(f?"common.actions.saving":"modelManagement.actions.saveRoutes"),m?e.jsx("span",{className:"absolute -right-1 -top-1 h-2 w-2 rounded-full bg-warning"}):null]})]})]}),e.jsx("datalist",{id:b,children:p.map(v=>e.jsx("option",{value:v},`${b}-${v}`))})]})})}const is={simulateRequest(a){return{url:"/api/routing/simulate",method:"POST",data:a}}},ls=350;function ds(a,s){switch(a.kind){case"modelRoute":return{label:a.viaAlias?s("workbench.hitSim.reasonModelRouteAlias"):s("workbench.hitSim.reasonModelRoute"),tone:"hit"};case"directMatch":return{label:s("workbench.hitSim.reasonDirectMatch"),tone:"hit"};case"thinkingDefault":return{label:s("workbench.hitSim.reasonThinkingDefault"),tone:"hit"};case"completionDefault":return{label:s("workbench.hitSim.reasonCompletionDefault"),tone:"hit"};case"longContextDefault":return{label:s("workbench.hitSim.reasonLongContext"),tone:"hit",detail:s("workbench.hitSim.longContextDetail",{estimate:a.tokenEstimate.toLocaleString(),threshold:a.threshold.toLocaleString()})};case"fallback":return{label:s("workbench.hitSim.reasonFallback"),tone:"fallback"}}return{label:s("workbench.hitSim.reasonFallback"),tone:"fallback"}}function cs({tabs:a,endpoint:s,onEndpointChange:o,hasUnsavedChanges:l=!1}){var D;const{t:r}=I(),g=a.filter(M=>M.key!=="providers"),[f,m]=N.useState(((D=g[0])==null?void 0:D.key)??"anthropic"),u=s??f,c=M=>{s&&o?o(M):m(M)},[b,y]=N.useState(""),[R,C]=N.useState(!1),[p,w]=N.useState("");N.useEffect(()=>{const M=setTimeout(()=>w(b.trim()),ls);return()=>clearTimeout(M)},[b]);const{data:v,isFetching:h,error:x}=_t(["routing","simulate",u,p,R],is.simulateRequest({endpoint:u,model:p||void 0,thinking:R}),{retry:!1,refetchOnWindowFocus:!1,staleTime:1/0});return e.jsxs("section",{"data-testid":"routing-hit-simulator",className:"space-y-3 rounded-lg border border-border bg-card p-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm font-semibold text-foreground",children:r("workbench.hitSim.title")}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:r("workbench.hitSim.subtitle")})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-2",children:[s?null:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:r("workbench.hitSim.endpointLabel")}),e.jsxs(Pe,{value:u,onValueChange:c,children:[e.jsx(Te,{className:"h-8 w-[168px]",children:e.jsx(Oe,{})}),e.jsx(Be,{children:g.map(M=>e.jsx(Le,{value:M.key,children:M.label},M.key))})]})]}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Fe,{checked:R,onCheckedChange:C,"aria-label":r("workbench.hitSim.thinking")}),r("workbench.hitSim.thinking")]})]}),e.jsx(G,{value:b,onChange:M=>y(M.target.value),placeholder:r("workbench.hitSim.modelPlaceholder"),className:"h-9 text-xs",spellCheck:!1,autoComplete:"off","aria-label":r("workbench.hitSim.modelPlaceholder")}),l?e.jsx("p",{"data-testid":"simulator-unsaved-notice",className:"text-[11px] text-warning",children:r("workbench.hitSim.unsavedNotice")}):null,e.jsx(us,{result:v,loading:h,errorMessage:(x==null?void 0:x.message)??null,requestedModel:p})]})}function us({result:a,loading:s,errorMessage:o,requestedModel:l}){var u;const{t:r}=I();if(o)return e.jsxs("p",{className:"text-xs text-muted-foreground",children:[r("workbench.hitSim.errorPrefix"),": ",o]});if(!a)return s?e.jsx("div",{className:"h-[72px] animate-pulse rounded-lg border border-border bg-secondary"}):e.jsx("p",{className:"text-xs text-muted-foreground",children:r("workbench.hitSim.empty")});const g=ds(a.reason,r),f=g.tone==="fallback",m=l||r("workbench.hitSim.anyModel");return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:f?"rounded-lg border border-border bg-secondary px-3 py-2.5":"rounded-lg border border-success bg-success-bg px-3 py-2.5",children:[e.jsx("div",{className:f?"text-[11px] font-semibold text-warning":"text-[11px] font-semibold text-success",children:g.label}),e.jsx("div",{className:"mt-1 text-xs text-foreground",children:m}),e.jsxs("div",{className:"mt-1 text-xs text-muted-foreground",children:["→ ",a.providerLabel,":",a.modelId]}),g.detail?e.jsx("div",{className:"mt-1 text-[11px] text-muted-foreground",children:g.detail}):null]}),(((u=a.candidates)==null?void 0:u.length)??0)>1?e.jsxs("div",{className:"rounded-lg border border-border bg-secondary/50 px-3 py-2.5",children:[e.jsx("div",{className:"text-[11px] font-semibold text-muted-foreground",children:r("providers.aggregate.simulator.candidatesTitle")}),e.jsx("ol",{className:"mt-1.5 space-y-1",children:(a.candidates??[]).map((c,b)=>e.jsxs("li",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"w-4 shrink-0 text-center text-[10.5px] tabular-nums text-muted-foreground",children:b+1}),e.jsxs("span",{className:"min-w-0 truncate font-mono text-foreground",children:[c.providerLabel,":",c.modelId]}),b===0?e.jsx("span",{className:"shrink-0 text-[10px] font-medium text-muted-foreground",children:r("providers.aggregate.simulator.primaryBadge")}):null]},`${c.providerId}:${c.modelId}`))})]}):null,f?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:r("workbench.hitSim.fallbackHint")}):null]})}function ms({routing:a,config:s,customEndpoints:o,routeCounts:l,selectedEndpointId:r,onSelectEndpoint:g,onEditEndpoint:f,onDeleteEndpoint:m}){var C;I();const u=r??((C=a.endpointTabs[0])==null?void 0:C.key)??"anthropic",c=a.endpointTabs.find(p=>p.key===u),b=a.defaultsByEndpoint[u],y=!!a.isDirtyByEndpoint[u]||!!a.isDefaultsDirtyByEndpoint[u],R=(()=>{var w;if(u==="anthropic")return"/anthropic";if(u==="openai")return"/openai";const p=o.find(v=>v.id===u);return(w=p==null?void 0:p.paths)!=null&&w.length?p.paths[0].path:p!=null&&p.path?p.path:`/${u}`})();return e.jsxs("div",{"data-testid":"routing-workspace",className:"flex flex-col gap-3.5",children:[e.jsx(as,{endpointPath:R,defaultTarget:(b==null?void 0:b.completion)??null}),e.jsxs("div",{className:"grid items-start gap-3.5 lg:grid-cols-[210px_minmax(0,2fr)_minmax(0,1fr)]",children:[e.jsx(ns,{tabs:a.endpointTabs,customEndpoints:o,routeCounts:l,selectedEndpointId:r,onSelect:g,onEditEndpoint:f,onDeleteEndpoint:m}),e.jsxs("div",{className:"flex flex-col gap-3.5",children:[e.jsx(ss,{routing:a,endpoint:u}),e.jsx(os,{routing:a,endpoint:u,tabInfo:c})]}),e.jsxs("div",{className:"flex flex-col gap-3.5 lg:sticky lg:top-4",children:[e.jsx(cs,{tabs:a.endpointTabs,endpoint:u,onEndpointChange:g,hasUnsavedChanges:y}),e.jsx(ts,{routing:a,endpoint:u,tabInfo:c,config:s,customEndpoints:o})]})]})]})}function Bs(){var he,ee,_,pe,te,H;const{t:a}=I(),s=Kt(),o=Wt(s),[l,r]=N.useState(!1),[g,f]=N.useState(void 0),[m,u]=N.useState(!1),[c,b]=N.useState(null),[y,R]=N.useState(!1),C=Object.values(o.isDirtyByEndpoint).some(Boolean)||Object.values(o.isDefaultsDirtyByEndpoint).some(Boolean),p=Lt(({currentLocation:k,nextLocation:T})=>C&&k.pathname!==T.pathname);N.useEffect(()=>{if(!C)return;const k=T=>{T.preventDefault(),T.returnValue=""};return window.addEventListener("beforeunload",k),()=>window.removeEventListener("beforeunload",k)},[C]);const[w,v]=Ft(),h=w.get("endpoint"),[x,D]=N.useState(h),[M,z]=N.useState(null);N.useEffect(()=>{D(h)},[h]);const U=N.useRef(!1);N.useEffect(()=>{if(!U.current){if(h){U.current=!0;return}o.endpointTabs.length!==0&&(U.current=!0,v(k=>{const T=new URLSearchParams(k);return T.set("endpoint",o.endpointTabs[0].key),T},{replace:!0}))}},[h,o.endpointTabs,v]);const V=N.useCallback(k=>{v(T=>{const Y=new URLSearchParams(T);return Y.set("endpoint",k),Y},{replace:!0})},[v]),oe=N.useCallback(()=>{v(k=>{const T=new URLSearchParams(k);return T.delete("endpoint"),T},{replace:!0})},[v]);N.useEffect(()=>{M&&o.endpointTabs.some(k=>k.key===M)&&(z(null),V(M))},[M,o.endpointTabs,V]),N.useEffect(()=>{x&&(s.customEndpointsQuery.isPending||o.endpointTabs.some(k=>k.key===x)||oe())},[x,o.endpointTabs,s.customEndpointsQuery.isPending,oe]);const ie=()=>{f(void 0),r(!0)},le=k=>{f(k),r(!0)},de=async()=>{if(c){R(!0);try{c.kind==="preset"?await o.handleDeletePreset(c.endpoint,c.preset):c.kind==="endpoint"&&await o.handleDeleteEndpoint(c.endpoint.id),b(null)}finally{R(!1)}}},Ne=(c==null?void 0:c.kind)==="preset"?a("modelManagement.presets.delete"):(c==null?void 0:c.kind)==="endpoint"?a("common.delete"):"",ce=(c==null?void 0:c.kind)==="preset"?a("modelManagement.confirm.deletePreset",{name:c.preset.name}):(c==null?void 0:c.kind)==="endpoint"?[a("modelManagement.deleteEndpointConfirm",{label:c.endpoint.label}),(((he=o.routesByEndpoint[c.endpoint.id])==null?void 0:he.length)??0)>0?a("modelManagement.deleteEndpointImpactRoutes",{count:((ee=o.routesByEndpoint[c.endpoint.id])==null?void 0:ee.length)??0}):"",(((_=o.presetsByEndpoint[c.endpoint.id])==null?void 0:_.length)??0)>0?a("modelManagement.deleteEndpointImpactPresets",{count:((pe=o.presetsByEndpoint[c.endpoint.id])==null?void 0:pe.length)??0}):""].filter(Boolean).join(" "):"",ue=(c==null?void 0:c.kind)==="preset"?c.preset.name:(c==null?void 0:c.kind)==="endpoint"?c.endpoint.label:"",me=Object.fromEntries(Object.entries(o.routesByEndpoint).map(([k,T])=>[k,(T==null?void 0:T.length)??0])),W=x??((te=o.endpointTabs[0])==null?void 0:te.key)??"anthropic",X=(k,T)=>{b({kind:"preset",endpoint:k,preset:T})};return e.jsxs("div",{className:"flex flex-col gap-6",children:[e.jsx(At,{actions:e.jsxs(e.Fragment,{children:[e.jsx(Xt,{tabs:o.endpointTabs,customEndpoints:s.customEndpoints,routeCounts:me,selectedEndpointId:W,onSelect:V,onEditEndpoint:le,onDeleteEndpoint:k=>b({kind:"endpoint",endpoint:k})}),e.jsxs(F,{variant:"outline",size:"sm",onClick:()=>u(!0),children:[e.jsx(Ot,{className:"h-4 w-4","aria-hidden":!0}),a("workbench.templates")]}),e.jsxs(F,{size:"sm",onClick:ie,children:[e.jsx(Ue,{className:"h-4 w-4","aria-hidden":!0}),a("workbench.endpoints.create")]})]})}),!s.config&&s.configQuery.isError?e.jsx(Ge,{tone:"danger",icon:e.jsx(Bt,{className:"h-5 w-5","aria-hidden":"true"}),title:a("common.status.error"),description:((H=s.configQuery.error)==null?void 0:H.message)??a("common.status.error"),action:e.jsx(F,{variant:"outline",onClick:()=>void s.configQuery.refetch(),children:a("common.actions.refresh")})}):e.jsx(ms,{routing:o,config:s.config,customEndpoints:s.customEndpoints,routeCounts:me,selectedEndpointId:x,onSelectEndpoint:V,onEditEndpoint:le,onDeleteEndpoint:k=>b({kind:"endpoint",endpoint:k})}),e.jsx(es,{open:m,onOpenChange:u,routing:o,endpoint:W,onRequestDeletePreset:X}),e.jsx(Gt,{open:l,endpoint:g,onClose:()=>{r(!1),f(void 0)},onSuccess:k=>{s.configQuery.refetch(),k&&z(k)}}),e.jsx(Yt,{dialog:o.presetDiffDialog,currentRoutes:o.presetDiffDialog?o.routesByEndpoint[o.presetDiffDialog.endpoint]||[]:[],onConfirm:(k,T)=>{o.setPresetDiffDialog(null),o.handleApplyPreset(k,T)},onClose:()=>o.setPresetDiffDialog(null)}),e.jsx(Qe,{open:!!c,onOpenChange:k=>{!k&&!y&&b(null)},title:Ne,description:ce,confirmLabel:a(y?"common.actions.loading":"common.delete"),cancelLabel:a("common.actions.cancel"),loading:y,onConfirm:de,children:ue?e.jsx("div",{className:"rounded-xl border border-destructive/20 bg-destructive/5 px-3 py-2 font-mono text-xs text-foreground",children:ue}):null}),e.jsx(Qe,{open:p.state==="blocked",onOpenChange:k=>{!k&&p.state==="blocked"&&p.reset()},title:a("providers.masterDetail.unsavedTitle"),description:a("providers.masterDetail.unsavedBody"),confirmLabel:a("providers.masterDetail.unsavedConfirm"),cancelLabel:a("common.actions.cancel"),onConfirm:()=>{p.state==="blocked"&&p.proceed()}})]})}export{Bs as default};
1
+ import{r as N,a_ as vt,j as e,a$ as Ke,aG as Ve,b0 as We,b1 as Ge,aq as _,aU as Nt,aV as wt,aW as kt,aL as Et,aM as ze,aQ as Ct,aR as St,aS as Rt,aT as Dt,aN as Mt,aO as Pt,aP as Tt,b2 as Ot,Y as Bt}from"./vendor-C-lQMZp3.js";import{g as Lt,u as Ft}from"./router-Bkbjq53m.js";import{C as Qe}from"./ConfirmDialog-_CIYYtzo.js";import{a as Je}from"./PageState-Bbhr4fy6.js";import{P as At}from"./PageToolbar-GyUQBhmq.js";import{t as G,q as Z,f as ae,B as F,T as $t,g as It,h as zt,i as Qt,C as ye,c as ve,b as qt}from"./app-DZpd2fu9.js";import{d as qe,g as _e,b as He,c as _t,e as se,f as Ue,h as ne,m as ke,i as Ht,C as Xe,O as Ye,u as Ut}from"./modelManagement-Dc7L1tJw.js";import{a as Kt}from"./query-1Ng1fzmE.js";import{g as ge}from"./gateway-DxaHzVOF.js";import{u as be}from"./useAppMutation-CsoNTPQ7.js";import{D as Ee,A as Ce,a as Se,b as Re,c as De,d as Me,e as Ze}from"./DialogShell-D1T4HXtd.js";import{L as U,I as J}from"./label-09axTkPo.js";import{S as Pe,a as Te,b as Oe,c as Be,d as Le,D as Vt}from"./disclosure-W_XtxMJz.js";import{S as Fe}from"./switch-C58zWdHT.js";import{u as I}from"./i18n-ClvfZhYc.js";import{B as re}from"./badge-CWbm9P64.js";import{c as je}from"./global-BCYo_xAt.js";import{T as fe}from"./TargetCombobox-CSnHZqDY.js";import"./radix-DONH6gHT.js";import"./popover-CX5HRHKk.js";function Wt(a){const{t:s,pushToast:o,config:l,setConfig:r,configQuery:g,customEndpoints:f,tabs:m,ensureConfig:u}=a,c=Kt(),[b,y]=N.useState({}),[R,C]=N.useState({}),[p,w]=N.useState(null),[v,h]=N.useState({}),[x,D]=N.useState({}),[M,z]=N.useState({}),[K,V]=N.useState(null),[oe,ie]=N.useState(null),[le,de]=N.useState(null),[Ne,ce]=N.useState(!1),[ue,me]=N.useState(null),[W,X]=N.useState({}),[he,ee]=N.useState(null),q=N.useRef(null),[pe,te]=N.useState(null),H=t=>{q.current=t,te(t)},k=()=>{q.current=null,te(null)},T=N.useMemo(()=>m.filter(t=>t.key!=="providers"),[m]);N.useEffect(()=>{if(!g.data)return;const t=g.data;y(i=>{const n=qe(t,f);if(!i||Object.keys(i).length===0)return n;const d={...n};for(const[j,E]of Object.entries(i)){if(!(j in n))continue;const S=_e(t,f,j);if(He(E,S))d[j]=E;else{const L=new Map(E.map(O=>[O.source,O.id]));d[j]=n[j].map(O=>({...O,id:L.get(O.source)??O.id}))}}return d}),X(i=>{const n=_t(t,f);if(!i||Object.keys(i).length===0)return n;const d={...n};for(const[j,E]of Object.entries(i)){if(!(j in n))continue;const S=se(t,f,j);JSON.stringify(E)!==JSON.stringify(S)&&(d[j]=E)}return d}),C({}),h(Ue(t,f))},[g.data,f]);const Y=(l==null?void 0:l.providers)??[],Ae=t=>{const i=t==null?void 0:t.trim();if(!i||!i.includes(":"))return null;const n=i.split(":",1)[0].trim();return n?Y.some(d=>d.id===n)?null:n:i},et=N.useMemo(()=>{const t=[],i=new Set;for(const n of Y){const d=n.label&&n.label!==n.id?`${n.label} (${n.id})`:n.id,j=n.models??[];if(j.length>0)for(const S of j){const L=`${n.id}:${S.id}`;i.has(L)||(i.add(L),t.push({value:L,label:`${d} · ${S.label??S.id}`,providerId:n.id,providerLabel:d,modelId:S.id,modelLabel:S.label??S.id,kind:"model",isDefault:n.defaultModel===S.id}))}else if(n.defaultModel){const S=`${n.id}:${n.defaultModel}`;i.has(S)||(i.add(S),t.push({value:S,label:`${d} · ${n.defaultModel}`,providerId:n.id,providerLabel:d,modelId:n.defaultModel,modelLabel:n.defaultModel,kind:"model",isDefault:!0}))}const E=`${n.id}:*`;i.has(E)||(i.add(E),t.push({value:E,label:s("settings.routing.providerPassthroughOption",{provider:d}),providerId:n.id,providerLabel:d,modelId:"*",modelLabel:"*",kind:"passthrough"}))}for(const n of Object.values(b).flat()){const d=n.target.trim();d&&!i.has(d)&&(i.add(d),t.push({value:d,label:d,modelId:d,modelLabel:d,kind:"custom"}))}return t},[Y,b,s]),tt=t=>l?_e(l,f,t):{},st=N.useMemo(()=>{const t={};for(const i of T){const n=b[i.key]||[];t[i.key]=He(n,tt(i.key))}return t},[l,f,b,T]),nt=N.useMemo(()=>{const t={};if(!l)return t;for(const i of T){const n=W[i.key];if(!n){t[i.key]=!1;continue}const d=se(l,f,i.key);t[i.key]=JSON.stringify(n)!==JSON.stringify(d)}return t},[l,f,W,T]),at=(t,i,n)=>{X(d=>({...d,[t]:{...d[t]??{completion:null,reasoning:null,background:null,longContextThreshold:6e4},[i]:n}}))},rt=async t=>{var d,j,E,S,L,O,B,$;if(!u()||q.current)return;const i=W[t];if(!i)return;const n={completion:(d=i.completion)!=null&&d.trim()?i.completion.trim():null,reasoning:(j=i.reasoning)!=null&&j.trim()?i.reasoning.trim():null,background:(E=i.background)!=null&&E.trim()?i.background.trim():null,longContextThreshold:Number.isFinite(i.longContextThreshold)&&i.longContextThreshold>0?Math.floor(i.longContextThreshold):l.defaults.longContextThreshold};for(const A of[n.completion,n.reasoning,n.background]){const P=Ae(A);if(P){o({title:s("settings.validation.routeUnknownProvider",{provider:P}),variant:"error"});return}}ee(t),H(t);try{const A=f.find(P=>P.id===t);if(A){const P={...A.routing??{},defaults:n,modelRoutes:((S=A.routing)==null?void 0:S.modelRoutes)??{}};await ae.update(t,{routing:P}),r(Q=>{if(!Q)return Q;const xe=[...Q.customEndpoints??[]],we=xe.findIndex(yt=>yt.id===t);return we===-1?Q:(xe[we]={...xe[we],routing:P},{...Q,customEndpoints:xe})}),await c.invalidateQueries({queryKey:Z.customEndpoints.all()})}else{const P=t,Q={...l,endpointRouting:{...l.endpointRouting??{},[P]:{defaults:n,modelRoutes:((O=(L=l.endpointRouting)==null?void 0:L[P])==null?void 0:O.modelRoutes)??(P==="anthropic"?l.modelRoutes??{}:{}),compatibility:($=(B=l.endpointRouting)==null?void 0:B[P])==null?void 0:$.compatibility}}};await ge.saveConfig(Q),r(Q)}X(P=>({...P,[t]:n})),o({title:s("workbench.defaults.saveSuccess"),variant:"success"}),g.refetch()}catch(A){o({title:s("workbench.defaults.saveFailure",{message:G(A).message}),variant:"error"})}finally{ee(null),k()}},$e=(t,i)=>{h(n=>({...n,[t]:i})),r(n=>{if(!n)return n;if(t==="anthropic"||t==="openai")return{...n,routingPresets:{...n.routingPresets,[t]:i}};const d=[...n.customEndpoints??[]],j=d.findIndex(E=>E.id===t);return j===-1?n:(d[j]={...d[j],routingPresets:i},{...n,customEndpoints:d})})},ot=(t,i)=>{D(n=>({...n,[t]:i})),i.trim()&&z(n=>({...n,[t]:null}))},it=async t=>{if(!u()||q.current)return;const i=(x[t]??"").trim();if(!i){z(n=>({...n,[t]:s("modelManagement.validation.presetName")}));return}if((v[t]??[]).some(n=>n.name.toLowerCase()===i.toLowerCase())){z(n=>({...n,[t]:s("modelManagement.validation.presetDuplicate",{name:i})}));return}V(t),H(t);try{const d=(await ke.savePreset(t,i)).presets??[];$e(t,d),D(j=>({...j,[t]:""})),z(j=>({...j,[t]:null})),o({title:s("modelManagement.toast.presetSaved",{name:i}),variant:"success"})}catch(n){o({title:s("modelManagement.toast.presetSaveFailure",{message:G(n).message}),variant:"error"})}finally{V(null),k(),g.refetch()}},lt=async(t,i)=>{if(u()&&!q.current){ie({endpoint:t,name:i.name}),H(t);try{const d=(await ke.applyPreset(t,i.name)).config;r(d);const j=qe(d,f);y(E=>({...E,[t]:j[t]??[]})),Ie(t,se(l,f,t),se(d,f,t)),h(Ue(d,f)),t!=="anthropic"&&t!=="openai"&&await c.invalidateQueries({queryKey:Z.customEndpoints.all()}),o({title:s("modelManagement.toast.presetApplySuccess",{name:i.name}),variant:"success"})}catch(n){o({title:s("modelManagement.toast.presetApplyFailure",{message:G(n).message}),variant:"error"})}finally{ie(null),k(),g.refetch()}}},dt=async(t,i)=>{if(u()&&!q.current){de({endpoint:t,name:i.name}),H(t);try{const n=await ke.deletePreset(t,i.name);$e(t,n.presets??[]),o({title:s("modelManagement.toast.presetDeleteSuccess",{name:i.name}),variant:"success"})}catch(n){o({title:s("modelManagement.toast.presetDeleteFailure",{message:G(n).message}),variant:"error"})}finally{de(null),k(),g.refetch()}}},ct=async t=>{const i=f.find(n=>n.id===t);if(!(!i||i.deletable===!1))try{await ae.delete(t),await c.invalidateQueries({queryKey:Z.customEndpoints.all()}),r(n=>n&&{...n,customEndpoints:(n.customEndpoints??[]).filter(d=>d.id!==t)}),g.refetch(),o({title:s("modelManagement.deleteEndpointSuccess"),variant:"success"})}catch(n){const d=G(n);o({title:s("modelManagement.deleteEndpointError",{error:d.message}),variant:"error"})}},ut=t=>{y(i=>({...i,[t]:[...i[t]||[],{id:ne(),source:"",target:""}]})),C(i=>({...i,[t]:null}))},mt=async(t,i)=>{if(u()&&!q.current){ce(!0),H(t);try{if(t==="anthropic"||t==="openai"){const n=t,d=l.endpointRouting?{...l.endpointRouting}:{},j=d[n]??{defaults:l.defaults,modelRoutes:(n==="anthropic"?l.modelRoutes:{})??{}},E={defaults:j.defaults??l.defaults,modelRoutes:j.modelRoutes??{}},S={...l,endpointRouting:{...d,[n]:i?{...E,compatibility:{enabled:!0}}:{...E}}};await ge.saveConfig(S),r(S)}else{const n=[...l.customEndpoints??[]],d=n.findIndex(L=>L.id===t);if(d===-1)throw new Error(s("modelManagement.toast.endpointNotFound"));const j=n[d],E=j.routing??{defaults:l.defaults,modelRoutes:{}};n[d]={...j,routing:i?{...E,compatibility:{enabled:!0}}:{defaults:E.defaults,modelRoutes:E.modelRoutes}};const S={...l,customEndpoints:n};await ge.saveConfig(S),r(S)}o({title:s("modelManagement.toast.compatibilitySaved",{state:s(i?"common.status.enabled":"common.status.disabled")}),variant:"success"}),g.refetch()}catch(n){const d=G(n);o({title:s("modelManagement.toast.compatibilitySaveFailure",{message:d.message}),variant:"error"})}finally{ce(!1),k()}}},ht=(t,i)=>{y(n=>{const d=n[t]||[];return d.some(j=>j.source.trim()===i.trim())?n:{...n,[t]:[...d,{id:ne(),source:i,target:""}]}}),C(n=>({...n,[t]:null}))},pt=(t,i,n,d)=>{y(j=>({...j,[t]:(j[t]||[]).map(E=>E.id===i?{...E,[n]:d}:E)})),C(j=>({...j,[t]:null}))},xt=(t,i)=>{y(n=>({...n,[t]:(n[t]||[]).filter(d=>d.id!==i)})),C(n=>({...n,[t]:null}))},gt=(t,i,n)=>{i!==n&&(y(d=>{const j=d[t]||[],E=j.findIndex(L=>L.id===i),S=j.findIndex(L=>L.id===n);return E===-1||S===-1?d:{...d,[t]:vt(j,E,S)}}),C(d=>({...d,[t]:null})))},ft=t=>{var n;if(!l)return;const i=(l.customEndpoints??f).find(d=>d.id===t);if(i)y(d=>{var j;return{...d,[t]:Object.entries(((j=i.routing)==null?void 0:j.modelRoutes)??{}).map(([E,S])=>({id:ne(),source:E,target:S}))}});else{const d=l.endpointRouting??{},j=t,E=j==="anthropic"?l.modelRoutes??{}:{},S=((n=d[j])==null?void 0:n.modelRoutes)??E;y(L=>({...L,[t]:Object.entries(S).map(([O,B])=>({id:ne(),source:O,target:B}))}))}C(d=>({...d,[t]:null}))},bt=be({mutationFn:async t=>(await ge.saveConfig(t.nextConfig),t)}),jt=be({mutationFn:async t=>(await ae.update(t.endpoint,{routing:t.routing}),t)}),Ie=(t,i,n)=>{X(d=>{const j=d[t];return j&&JSON.stringify(j)!==JSON.stringify(i)?d:{...d,[t]:n}})};return{endpointTabs:T,routesByEndpoint:b,setRoutesByEndpoint:y,routeError:R,savingRouteFor:p,presetsByEndpoint:v,presetNameByEndpoint:x,presetErrorByEndpoint:M,savingPresetFor:K,applyingPreset:oe,deletingPreset:le,savingCompatibilityPolicy:Ne,writingEndpoint:pe,presetDiffDialog:ue,setPresetDiffDialog:me,providerModelOptions:et,isDirtyByEndpoint:st,defaultsByEndpoint:W,isDefaultsDirtyByEndpoint:nt,savingDefaultsFor:he,handleDefaultsChange:at,handleSaveDefaults:rt,handlePresetNameChange:ot,handleSavePreset:it,handleApplyPreset:lt,handleDeletePreset:dt,handleDeleteEndpoint:ct,handleAddRoute:ut,handleAddSuggestion:ht,handleRouteChange:pt,handleRemoveRoute:xt,handleReorderRules:gt,handleResetRoutes:ft,handleSaveRoutes:async t=>{var d,j,E,S,L;if(!u()||q.current)return;const i=b[t]||[],n={};for(const O of i){const B=O.source.trim(),$=O.target.trim();if(!B&&!$)continue;if(!B||!$){C(P=>({...P,[t]:s("settings.validation.routePair")}));return}if(n[B]){C(P=>({...P,[t]:s("settings.validation.routeDuplicate",{model:B})}));return}const A=Ae($);if(A){C(P=>({...P,[t]:s("settings.validation.routeUnknownProvider",{provider:A})}));return}n[B]=$}C(O=>({...O,[t]:null})),w(t),H(t);try{const O=f.find(B=>B.id===t);if(O){const B={...O.routing??{},modelRoutes:n,defaults:((d=O.routing)==null?void 0:d.defaults)||l.defaults};await jt.mutateAsync({endpoint:t,routing:B}),r($=>{if(!$)return $;const A=[...$.customEndpoints??[]],P=A.findIndex(Q=>Q.id===t);return P===-1?$:(A[P]={...A[P],routing:B},{...$,customEndpoints:A})}),await c.invalidateQueries({queryKey:Z.customEndpoints.all()}),Ie(t,se(l,f,t),B.defaults)}else{const B={...l,endpointRouting:{...l.endpointRouting??{},[t]:{defaults:((E=(j=l.endpointRouting)==null?void 0:j[t])==null?void 0:E.defaults)??l.defaults,modelRoutes:n,compatibility:(L=(S=l.endpointRouting)==null?void 0:S[t])==null?void 0:L.compatibility}},modelRoutes:t==="anthropic"?n:l.modelRoutes??{}};await bt.mutateAsync({endpoint:t,nextConfig:B}),r(B)}y(B=>{const $=B[t]??[],A=new Map($.map(P=>[P.source.trim(),P.id]));return{...B,[t]:Object.entries(n).map(([P,Q])=>({id:A.get(P.trim())??ne(),source:P,target:Q}))}}),o({title:s("modelManagement.toast.routesSaved"),variant:"success"}),g.refetch()}catch(O){o({title:s("modelManagement.toast.routesSaveFailure",{message:G(O).message}),variant:"error"})}finally{w(null),k()}},handleCompatibilityEnabledChange:mt}}const Gt=["anthropic","openai-auto","openai-chat","openai-responses"];function Jt({open:a,endpoint:s,onClose:o,onSuccess:l}){const{t:r}=I(),[g,f]=N.useState(!1),[m,u]=N.useState({id:"",label:"",paths:[{path:"",protocol:"openai-auto"}],enabled:!0});N.useEffect(()=>{if(a){if(f(!1),s){const h=s.paths&&s.paths.length>0?s.paths:s.path&&s.protocol?[{path:s.path,protocol:s.protocol}]:[{path:"",protocol:"openai-auto"}];u({id:s.id,label:s.label,paths:h,enabled:s.enabled!==!1});return}u({id:"",label:"",paths:[{path:"",protocol:"openai-auto"}],enabled:!0})}},[s,a]);const c=be({mutationFn:ae.create,invalidateKeys:[Z.customEndpoints.all()],successToast:()=>({title:r("modelManagement.createEndpointSuccess")}),errorToast:h=>({title:r("modelManagement.createEndpointError",{error:h.message})}),onSuccess:async h=>{var x;l((x=h.endpoint)==null?void 0:x.id),o()}}),b=be({mutationFn:h=>ae.update(h.id,h.updates),invalidateKeys:[Z.customEndpoints.all()],successToast:()=>({title:r("modelManagement.updateEndpointSuccess")}),errorToast:h=>({title:r("modelManagement.updateEndpointError",{error:h.message})}),onSuccess:async()=>{l(),o()}}),y=()=>{u(h=>({...h,paths:[...h.paths,{path:"",protocol:"anthropic"}]}))},R=h=>{m.paths.length!==1&&u(x=>({...x,paths:x.paths.filter((D,M)=>M!==h)}))},C=(h,x,D)=>{u(M=>{const z=[...M.paths];return z[h]={...z[h],[x]:D},{...M,paths:z}})},p=h=>{if(h==null||h.preventDefault(),f(!0),!m.id.trim()||!m.label.trim())return;for(const D of m.paths)if(!D.path.trim())return;const x=m.paths.map(D=>({path:D.path.trim(),protocol:D.protocol}));if(s){b.mutate({id:s.id,updates:{label:m.label.trim(),paths:x,enabled:m.enabled}});return}c.mutate({id:m.id.trim(),label:m.label.trim(),paths:x,enabled:m.enabled})},w=c.isPending||b.isPending,v=m.paths.length===0?r("modelManagement.atLeastOnePath"):!m.id.trim()||!m.label.trim()?r("modelManagement.endpointValidationError"):m.paths.some(h=>!h.path.trim())?r("modelManagement.pathValidationError"):null;return e.jsx(Ee,{open:a,onOpenChange:h=>!h&&o(),children:e.jsxs(Ce,{className:"max-w-lg",onInteractOutside:h=>h.preventDefault(),children:[e.jsxs(Se,{children:[e.jsx(Re,{children:r(s?"modelManagement.editEndpoint":"modelManagement.createEndpoint")}),e.jsx(De,{className:"truncate font-mono text-xs",children:s?s.id:r("modelManagement.endpointRoutingHint")})]}),e.jsx(Me,{children:e.jsxs("form",{id:"endpoint-form",onSubmit:p,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(U,{children:[r("modelManagement.endpointId")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(J,{value:m.id,onChange:h=>u(x=>({...x,id:h.target.value})),placeholder:r("modelManagement.endpointIdPlaceholder"),disabled:!!s}),e.jsx("p",{className:"text-xs text-muted-foreground",children:r("modelManagement.endpointIdHint")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(U,{children:[r("modelManagement.endpointLabel")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(J,{value:m.label,onChange:h=>u(x=>({...x,label:h.target.value})),placeholder:r("modelManagement.endpointLabelPlaceholder")})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(U,{children:[r("modelManagement.endpointPaths")," ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsxs(F,{type:"button",variant:"ghost",size:"sm",onClick:y,children:[e.jsx(Ke,{className:"mr-1 h-3 w-3"}),r("modelManagement.addPath")]})]}),e.jsx("div",{className:"space-y-3",children:m.paths.map((h,x)=>e.jsxs("div",{className:"space-y-2 border border-border bg-card p-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(J,{value:h.path,onChange:D=>C(x,"path",D.target.value),placeholder:r("modelManagement.endpointPathPlaceholder")}),e.jsxs(Pe,{value:h.protocol,onValueChange:D=>C(x,"protocol",D),children:[e.jsx(Te,{children:e.jsx(Oe,{})}),e.jsx(Be,{children:Gt.map(D=>e.jsx(Le,{value:D,children:r(D==="anthropic"?"modelManagement.protocolAnthropic":D==="openai-auto"?"modelManagement.protocolOpenAI":D==="openai-chat"?"modelManagement.protocolOpenAIChat":"modelManagement.protocolOpenAIResponses")},D))})]})]}),m.paths.length>1?e.jsx(F,{type:"button",variant:"ghost",size:"sm",onClick:()=>R(x),className:"text-destructive",children:e.jsx(Ve,{className:"h-4 w-4"})}):null]}),e.jsxs("div",{className:"space-y-1 text-xs text-muted-foreground",children:[x===0?e.jsx("p",{children:r("modelManagement.endpointPathHint")}):null,e.jsx("p",{children:r(`modelManagement.protocolHints.${h.protocol}`)})]})]},`${h.protocol}-${x}`))}),v&&g?e.jsx("p",{className:"text-xs text-destructive",children:v}):null]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Fe,{id:"endpoint-enabled",checked:m.enabled,onCheckedChange:h=>u(x=>({...x,enabled:h}))}),e.jsx(U,{htmlFor:"endpoint-enabled",children:r("modelManagement.endpointEnabled")})]}),s?null:e.jsx("div",{className:"rounded-xl bg-secondary p-4",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:r("modelManagement.endpointRoutingHint")})})]})}),e.jsxs(Ze,{children:[e.jsx(F,{variant:"outline",onClick:o,disabled:w,children:r("common.cancel")}),e.jsx(F,{type:"submit",form:"endpoint-form",disabled:w,children:r(w?"common.saving":s?"common.save":"common.create")})]})]})})}function Xt({tabs:a,customEndpoints:s,routeCounts:o,selectedEndpointId:l,onSelect:r,onEditEndpoint:g,onDeleteEndpoint:f}){var b;const{t:m}=I(),u=s.find(y=>y.id===l),c=u?u.label||u.id:((b=a.find(y=>y.key===l))==null?void 0:b.label)??l;return e.jsxs("div",{className:"flex items-center gap-1.5 lg:hidden",children:[e.jsxs(Pe,{value:l,onValueChange:r,children:[e.jsx(Te,{"data-testid":"routing-endpoint-switcher","aria-label":m("workbench.endpointSwitcher.label"),className:"h-8 w-[230px] text-xs",children:e.jsx(Oe,{children:c})}),e.jsx(Be,{children:a.map(y=>{const R=s.find(w=>w.id===y.key),C=R?R.label||R.id:y.label,p=o[y.key]??0;return e.jsx(Le,{value:y.key,className:"text-xs",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:C}),e.jsx("span",{className:"shrink-0 tabular-nums text-muted-foreground",children:m("workbench.endpointSwitcher.ruleCount",{count:p})})]})},y.key)})})]}),u?e.jsxs(e.Fragment,{children:[e.jsx(F,{variant:"ghost",size:"icon","data-testid":"endpoint-edit",className:"h-7 w-7",title:m("common.edit"),"aria-label":m("common.edit"),onClick:()=>g(u),children:e.jsx(We,{className:"h-3.5 w-3.5","aria-hidden":!0})}),u.deletable!==!1?e.jsx(F,{variant:"ghost",size:"icon","data-testid":"endpoint-delete",className:"h-7 w-7 text-muted-foreground hover:text-destructive",title:m("common.delete"),"aria-label":m("common.delete"),onClick:()=>f(u),children:e.jsx(Ge,{className:"h-3.5 w-3.5","aria-hidden":!0})}):null]}):null]})}function Yt({dialog:a,currentRoutes:s,onConfirm:o,onClose:l}){const{t:r}=I();if(!a)return null;const{endpoint:g,preset:f}=a,m=f.modelRoutes??{},u={};for(const p of s){const w=p.source.trim(),v=p.target.trim();w&&v&&(u[w]=v)}const c=new Set([...Object.keys(u),...Object.keys(m)]),b=[],y=[],R=[];for(const p of c){const w=p in u,v=p in m;v&&!w?b.push([p,m[p]]):w&&!v?y.push([p,u[p]]):w&&v&&u[p]!==m[p]&&R.push([p,u[p],m[p]])}const C=b.length>0||y.length>0||R.length>0;return e.jsx(Ee,{open:!0,onOpenChange:p=>!p&&l(),children:e.jsxs(Ce,{className:"max-w-2xl",children:[e.jsxs(Se,{children:[e.jsx(Re,{children:r("modelManagement.presets.diffTitle")}),e.jsx(De,{children:r("modelManagement.presets.diffDescription",{name:f.name})})]}),e.jsx(Me,{children:C?e.jsxs("div",{className:"max-h-80 space-y-2 rounded-xl bg-secondary/50 p-3 text-sm",children:[b.map(([p,w])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-success-bg px-2 py-1.5 text-success",children:[e.jsx(re,{variant:"outline",className:"border-success/30 text-xs",children:r("modelManagement.presets.diffAdded")}),e.jsx("span",{className:"truncate",children:p}),e.jsx(_,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:w})]},`add-${p}`)),y.map(([p,w])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-error-bg px-2 py-1.5 text-error",children:[e.jsx(re,{variant:"outline",className:"border-error/30 text-xs",children:r("modelManagement.presets.diffRemoved")}),e.jsx("span",{className:"truncate",children:p}),e.jsx(_,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:w})]},`rm-${p}`)),R.map(([p,w,v])=>e.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-warning-bg px-2 py-1.5 text-warning",children:[e.jsx(re,{variant:"outline",className:"border-warning/30 text-xs",children:r("modelManagement.presets.diffChanged")}),e.jsx("span",{className:"truncate",children:p}),e.jsx(_,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate line-through opacity-60",children:w}),e.jsx(_,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:v})]},`chg-${p}`))]}):e.jsx("p",{className:"rounded-xl bg-secondary/50 py-8 text-center text-sm text-muted-foreground",children:r("modelManagement.presets.diffEmpty")})}),e.jsxs(Ze,{children:[e.jsx(F,{variant:"outline",onClick:l,children:r("common.cancel")}),e.jsx(F,{onClick:()=>o(g,f),disabled:!C,children:r("modelManagement.presets.diffConfirm")})]})]})})}function Zt({routing:a,endpoint:s,onRequestDeletePreset:o,embedded:l=!1}){var p,w;const{t:r}=I(),g=a.presetsByEndpoint[s]??[],f=a.presetNameByEndpoint[s]??"",m=a.presetErrorByEndpoint[s],u=a.savingPresetFor===s,c=((p=a.applyingPreset)==null?void 0:p.endpoint)===s?a.applyingPreset.name:null,b=((w=a.deletingPreset)==null?void 0:w.endpoint)===s?a.deletingPreset.name:null,y=a.writingEndpoint===s,R=!!a.isDirtyByEndpoint[s],C=e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(J,{"data-testid":"preset-name-input",value:f,onChange:v=>a.handlePresetNameChange(s,v.target.value),placeholder:r("modelManagement.presets.namePlaceholder"),disabled:u,className:"h-8 flex-1 text-xs"}),e.jsx(F,{variant:"outline",size:"sm","data-testid":"save-preset",onClick:()=>void a.handleSavePreset(s),disabled:u||y||R,children:r(u?"modelManagement.presets.saving":"modelManagement.presets.save")})]}),R?e.jsx("p",{className:"text-[11px] text-warning",children:r("modelManagement.presets.dirtyBlocked")}):null,m?e.jsx("p",{className:"text-xs text-destructive",children:m}):null,g.length===0?e.jsx("p",{className:"py-2 text-center text-[11px] text-muted-foreground",children:r("modelManagement.presets.empty")}):e.jsx($t,{children:e.jsx("div",{className:"grid grid-cols-1 gap-1.5 sm:grid-cols-2",children:g.map(v=>{const h=c===v.name,x=b===v.name,D=Object.entries(v.modelRoutes??{}),M=D.length;return e.jsxs("div",{"data-testid":"preset-row",className:"flex items-center justify-between gap-2 border border-border bg-secondary/40 px-2.5 py-2",children:[e.jsxs(It,{children:[e.jsx(zt,{asChild:!0,children:e.jsxs("div",{className:"min-w-0 flex-1 cursor-default",children:[e.jsx("span",{className:"block truncate text-[11px] font-medium",children:v.name}),e.jsx(re,{variant:"outline",className:"mt-0.5 text-[10px] font-normal",children:M>0?r("modelManagement.presets.rulesCount",{count:M}):r("modelManagement.presets.noRules")})]})}),M>0?e.jsx(Qt,{side:"bottom",className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1 text-xs",children:[D.slice(0,5).map(([z,K])=>e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"truncate",children:z}),e.jsx(_,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:K})]},z)),M>5?e.jsxs("div",{className:"text-muted-foreground",children:["…+",M-5]}):null]})}):null]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"apply-preset",className:"text-[11px] font-semibold text-foreground underline decoration-muted-foreground/40 underline-offset-2 hover:decoration-foreground disabled:opacity-50",onClick:()=>a.setPresetDiffDialog({endpoint:s,preset:v}),disabled:h||x||y,children:r(h?"modelManagement.presets.applying":"modelManagement.presets.apply")}),e.jsx("button",{type:"button","data-testid":"delete-preset",className:"text-[11px] text-muted-foreground hover:text-destructive disabled:opacity-50","aria-label":r("common.delete"),onClick:()=>o(s,v),disabled:x||h||y,children:r(x?"modelManagement.presets.deleting":"modelManagement.presets.delete")})]})]},v.name)})})})]});return l?e.jsx("div",{"data-testid":"routing-presets-card",children:C}):e.jsx(ye,{"data-testid":"routing-presets-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(ve,{className:"space-y-3 p-4",children:[e.jsx("h3",{className:"text-[13px] font-semibold",children:r("modelManagement.presets.title")}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:r("modelManagement.presets.description")}),C]})})}function es({open:a,onOpenChange:s,routing:o,endpoint:l,onRequestDeletePreset:r}){const{t:g}=I();return e.jsx(Ee,{open:a,onOpenChange:s,children:e.jsxs(Ce,{className:"max-w-lg",children:[e.jsxs(Se,{children:[e.jsx(Re,{children:g("modelManagement.presets.title")}),e.jsx(De,{className:"text-xs",children:g("modelManagement.presets.description")})]}),e.jsx(Me,{children:e.jsx(Zt,{routing:o,endpoint:l,embedded:!0,onRequestDeletePreset:r})})]})})}function ts({routing:a,endpoint:s,tabInfo:o,config:l,customEndpoints:r}){var v,h;const{t:g}=I(),f=a.routesByEndpoint[s]||[],m=a.savingRouteFor===s,u=a.savingCompatibilityPolicy,c=a.writingEndpoint===s,b=((v=o==null?void 0:o.protocols)==null?void 0:v.some(x=>x.startsWith("openai")))??s==="openai",y=Ht(s,l,r),R=b?(y==null?void 0:y.enabled)??!1:!1,p=((h=o==null?void 0:o.protocols)==null?void 0:h.includes("anthropic"))??s==="anthropic"?Xe:Ye,w=new Set(f.map(x=>x.source.trim()).filter(Boolean));return e.jsx(ye,{"data-testid":"endpoint-config-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(ve,{className:"space-y-3 p-4",children:[e.jsx("h3",{className:"text-[12.5px] font-semibold",children:g("workbench.endpointConfig.title")}),b?e.jsxs("div",{className:"flex items-center justify-between gap-2 border border-border/60 bg-secondary/30 px-2.5 py-2",children:[e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsx(U,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:g("modelManagement.openaiCompatibility.toggleLabel")}),e.jsx("p",{className:"text-[10.5px] text-muted-foreground",children:g(R?"modelManagement.openaiCompatibility.enabledHint":"modelManagement.openaiCompatibility.disabledHint")})]}),e.jsx(Fe,{"data-testid":"compatibility-toggle",checked:R,onCheckedChange:x=>void a.handleCompatibilityEnabledChange(s,x),disabled:u||c,"aria-label":g("modelManagement.openaiCompatibility.toggleLabel")})]}):null,e.jsxs("div",{children:[e.jsx("p",{className:"mb-1.5 text-[11px] text-muted-foreground",children:g("settings.routing.suggested")}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:p.map(x=>{const D=w.has(x);return e.jsx("button",{"data-testid":"suggestion-chip",type:"button",onClick:()=>a.handleAddSuggestion(s,x),disabled:m||D,className:je("h-6 border px-2 text-[10.5px] transition-colors",D?"border-border bg-secondary/40 text-muted-foreground/50":"border-border bg-card hover:border-foreground hover:text-foreground"),children:x},`${s}-${x}`)})})]})]})})}function ss({routing:a,endpoint:s}){const{t:o}=I(),l=a.defaultsByEndpoint[s]??null,r=a.isDefaultsDirtyByEndpoint[s]??!1,g=a.savingDefaultsFor===s,f=a.writingEndpoint===s,m=a.providerModelOptions;return e.jsx(ye,{"data-testid":"routing-defaults-card",className:"border-foreground bg-secondary shadow-none",children:e.jsxs(ve,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-[13px] font-semibold text-foreground",children:o("workbench.defaults.title")}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:o("workbench.defaults.cardSubtitle")})]}),e.jsxs(Vt,{summary:e.jsx("span",{className:"text-[11px] font-medium text-muted-foreground",children:o("workbench.defaults.moreLabel")}),summaryClassName:"px-2 py-1",contentClassName:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(U,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:o("workbench.defaults.reasoningLabel")}),e.jsx(fe,{value:(l==null?void 0:l.reasoning)??"",onChange:u=>a.handleDefaultsChange(s,"reasoning",u),options:m,disabled:g,ariaLabel:o("workbench.defaults.reasoningLabel"),placeholder:o("workbench.defaults.targetPlaceholder")})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(U,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:o("workbench.defaults.backgroundLabel")}),e.jsx(fe,{value:(l==null?void 0:l.background)??"",onChange:u=>a.handleDefaultsChange(s,"background",u),options:m,disabled:g,ariaLabel:o("workbench.defaults.backgroundLabel"),placeholder:o("workbench.defaults.targetPlaceholder")})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(U,{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:o("workbench.defaults.thresholdLabel")}),e.jsx(J,{type:"number",min:1,value:(l==null?void 0:l.longContextThreshold)||"",onChange:u=>{const c=Number.parseInt(u.target.value,10);a.handleDefaultsChange(s,"longContextThreshold",Number.isFinite(c)?c:0)},disabled:g,className:"md:w-56"})]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"border border-border bg-card px-2.5 py-2 font-mono text-xs",children:"*"}),e.jsx(_,{className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground","aria-hidden":!0}),e.jsx("div",{"data-testid":"default-target",className:"min-w-[180px] flex-1",children:e.jsx(fe,{value:(l==null?void 0:l.completion)??"",onChange:u=>a.handleDefaultsChange(s,"completion",u),options:m,disabled:g,ariaLabel:o("workbench.defaults.completionLabel"),placeholder:o("workbench.defaults.targetPlaceholder")})}),e.jsxs(F,{variant:"outline",size:"sm","data-testid":"save-defaults",onClick:()=>void a.handleSaveDefaults(s),disabled:g||!r||f,className:"relative",children:[o(g?"common.actions.saving":"workbench.defaults.save"),r?e.jsx("span",{className:"absolute -right-1 -top-1 h-2 w-2 rounded-full bg-warning"}):null]})]})]})})}function ns({tabs:a,customEndpoints:s,routeCounts:o,selectedEndpointId:l,onSelect:r,onEditEndpoint:g,onDeleteEndpoint:f}){const{t:m}=I(),u=a.map(c=>{const b=s.find(y=>y.id===c.key);return b?{key:c.key,label:b.label||b.id,enabled:b.enabled!==!1,custom:b}:{key:c.key,label:c.label,enabled:!0}});return e.jsxs("aside",{"data-testid":"endpoint-rail","aria-label":m("workbench.endpointRail.title"),className:"hidden lg:flex lg:sticky lg:top-4 flex-col gap-1 border border-border bg-card p-1.5 shadow-[var(--surface-shadow)] lg:max-h-[calc(100vh-2rem)] lg:overflow-y-auto",children:[e.jsxs("div",{className:"px-2 pb-1 pt-2",children:[e.jsx("h2",{className:"text-[12.5px] font-semibold",children:m("workbench.endpointRail.title")}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:m("workbench.endpointRail.subtitle")})]}),u.map(c=>{const b=c.key===l,y=o[c.key]??0,R=!c.enabled;return e.jsxs("div",{"data-testid":"routing-endpoint-row",className:je("flex items-stretch border transition-colors",b?"border-foreground bg-secondary":"border-transparent hover:bg-accent",R?"opacity-60":""),children:[e.jsxs("button",{type:"button",onClick:()=>r(c.key),"aria-current":b?"true":void 0,className:"flex min-w-0 flex-1 items-center gap-2 px-2 py-2 text-left",children:[e.jsx("span",{className:je("h-1.5 w-1.5 shrink-0 rounded-full",R?"bg-muted-foreground/30":b?"bg-foreground":"bg-muted-foreground/50"),"aria-hidden":!0}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-xs font-medium",title:c.label,children:c.label}),e.jsx("span",{className:"shrink-0 text-[10.5px] tabular-nums text-muted-foreground",children:m("workbench.endpointRail.ruleCount",{count:y})})]}),c.custom?e.jsxs("div",{className:"flex items-center gap-0.5 pr-1",children:[e.jsx("button",{type:"button","data-testid":"endpoint-edit",onClick:()=>g(c.custom),className:"flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-foreground",title:m("common.edit"),"aria-label":m("common.edit"),children:e.jsx(We,{className:"h-3 w-3","aria-hidden":!0})}),c.custom.deletable!==!1?e.jsx("button",{type:"button","data-testid":"endpoint-delete",onClick:()=>f(c.custom),className:"flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-destructive",title:m("common.delete"),"aria-label":m("common.delete"),children:e.jsx(Ge,{className:"h-3 w-3","aria-hidden":!0})}):null]}):null]},c.key)})]})}function as({endpointPath:a,defaultTarget:s}){const{t:o}=I();return e.jsxs("section",{"data-testid":"routing-flow-banner",className:"flex flex-wrap items-center gap-x-3 gap-y-2 border border-border bg-card px-4 py-3 shadow-[var(--surface-shadow)]",children:[e.jsx("span",{className:"text-[10.5px] font-semibold uppercase tracking-[0.06em] text-muted-foreground",children:o("workbench.flow.title")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[e.jsx("span",{className:"border border-border bg-secondary px-2.5 py-1 font-mono text-[11px]",children:o("workbench.flow.clientStep")}),e.jsx(_,{className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0}),e.jsxs("span",{className:"border border-border bg-secondary px-2.5 py-1 text-[11px]",children:[o("workbench.flow.endpointStep")," ",e.jsx("span",{className:"font-mono",children:a})]}),e.jsx(_,{className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0}),e.jsx("span",{className:"border border-foreground bg-secondary px-2.5 py-1 text-[11px] font-semibold text-foreground",children:o("workbench.flow.matchStep")}),e.jsx(_,{className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":!0}),e.jsx("span",{className:"border border-border bg-secondary px-2.5 py-1 font-mono text-[11px]",children:s||o("workbench.flow.fallbackNote")})]})]})}function rs({entry:a,index:s,savingRoute:o,options:l,sourceListId:r,onRouteChange:g,onRemoveRoute:f}){const{t:m}=I(),{attributes:u,listeners:c,setNodeRef:b,setActivatorNodeRef:y,transform:R,transition:C,isDragging:p}=Nt({id:a.id});return e.jsxs("div",{ref:b,"data-testid":"route-rule-row","data-id":a.id,style:{transform:kt.Transform.toString(R),transition:C},className:je("grid grid-cols-[auto_auto_minmax(0,1fr)_auto] items-center gap-x-2 gap-y-1.5 border border-border bg-card p-2 sm:flex sm:gap-2",p&&"z-10 opacity-60 shadow-[var(--surface-shadow-lg)]"),children:[e.jsx("button",{ref:y,type:"button","data-testid":"route-rule-grip","aria-label":m("workbench.routing.dragHandle"),className:"row-span-2 flex h-7 w-4 shrink-0 cursor-grab touch-none items-center justify-center text-muted-foreground hover:text-foreground active:cursor-grabbing sm:row-span-1",...u,...c,children:e.jsx(wt,{className:"h-4 w-4","aria-hidden":!0})}),e.jsx("span",{className:"w-4 shrink-0 text-center text-[10.5px] tabular-nums text-muted-foreground",children:s+1}),e.jsx(J,{"data-testid":"route-rule-source",value:a.source,onChange:w=>g(a.id,"source",w.target.value),placeholder:m("settings.routing.sourcePlaceholder"),list:r,disabled:o,className:"h-8 min-w-0 flex-1 text-xs"}),e.jsx(_,{className:"col-start-2 row-start-2 h-3.5 w-3.5 shrink-0 text-muted-foreground sm:col-auto sm:row-auto","aria-hidden":!0}),e.jsx("div",{"data-testid":"route-rule-target",className:"col-start-3 row-start-2 min-w-0 sm:col-auto sm:row-auto sm:flex-[1.15]",children:e.jsx(fe,{value:a.target,onChange:w=>g(a.id,"target",w),options:l,disabled:o,ariaLabel:m("workbench.routing.targetLabel"),placeholder:m("settings.routing.targetPlaceholder")})}),e.jsx(F,{variant:"ghost",size:"icon","data-testid":"route-rule-delete",className:"col-start-4 row-span-2 h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive sm:col-auto sm:row-span-1",onClick:()=>f(a.id),disabled:o,"aria-label":m("common.delete"),children:e.jsx(Ve,{className:"h-3.5 w-3.5","aria-hidden":!0})})]})}function os({routing:a,endpoint:s,tabInfo:o}){var w;const{t:l}=I(),r=a.routesByEndpoint[s]||[],g=a.routeError[s],f=a.savingRouteFor===s,m=a.isDirtyByEndpoint[s]??!1,u=a.writingEndpoint===s,c=a.providerModelOptions,b=`route-source-${s}`,y=Et(ze(Tt,{activationConstraint:{distance:6}}),ze(Pt,{coordinateGetter:Mt})),R=v=>{const{active:h,over:x}=v;!x||h.id===x.id||a.handleReorderRules(s,String(h.id),String(x.id))},p=((w=o==null?void 0:o.protocols)==null?void 0:w.includes("anthropic"))??s==="anthropic"?Xe:Ye;return e.jsx(ye,{"data-testid":"routing-rules-card",className:"shadow-[var(--surface-shadow)]",children:e.jsxs(ve,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h3",{className:"flex items-center gap-2 text-[13px] font-semibold",children:[l("workbench.routing.rulesTitle"),e.jsx(re,{variant:"outline",className:"text-[10.5px] font-normal tabular-nums",children:r.length})]}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:l("workbench.routing.rulesSubtitle")})]}),e.jsx(F,{variant:"outline",size:"sm","data-testid":"add-route",onClick:()=>a.handleAddRoute(s),disabled:f,children:l("settings.routing.add")})]}),g?e.jsx("p",{className:"text-xs text-destructive",children:g}):null,r.length===0?e.jsx(Je,{compact:!0,title:l("workbench.routing.emptyTitle"),description:l("workbench.routing.emptyDescription"),action:e.jsx(F,{variant:"outline",size:"sm",onClick:()=>a.handleAddRoute(s),disabled:f,children:l("workbench.routing.addFirst")})}):e.jsx(Ct,{sensors:y,collisionDetection:St,onDragEnd:R,children:e.jsx(Rt,{items:r.map(v=>v.id),strategy:Dt,children:e.jsx("div",{className:"flex flex-col gap-1.5",children:r.map((v,h)=>e.jsx(rs,{entry:v,index:h,savingRoute:f,options:c,sourceListId:b,onRouteChange:(x,D,M)=>a.handleRouteChange(s,x,D,M),onRemoveRoute:x=>a.handleRemoveRoute(s,x)},v.id))})})}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-t border-border/60 pt-3",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:l(m?"modelManagement.actions.footerDirtyHint":"modelManagement.actions.footerSavedHint")}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(F,{variant:"outline",size:"sm","data-testid":"reset-routes",onClick:()=>a.handleResetRoutes(s),disabled:f||!m,children:l("common.actions.reset")}),e.jsxs(F,{variant:"outline",size:"sm","data-testid":"save-routes",onClick:()=>void a.handleSaveRoutes(s),disabled:f||u,className:"relative",children:[l(f?"common.actions.saving":"modelManagement.actions.saveRoutes"),m?e.jsx("span",{className:"absolute -right-1 -top-1 h-2 w-2 rounded-full bg-warning"}):null]})]})]}),e.jsx("datalist",{id:b,children:p.map(v=>e.jsx("option",{value:v},`${b}-${v}`))})]})})}const is={simulateRequest(a){return{url:"/api/routing/simulate",method:"POST",data:a}}},ls=350;function ds(a,s){switch(a.kind){case"modelRoute":return{label:a.viaAlias?s("workbench.hitSim.reasonModelRouteAlias"):s("workbench.hitSim.reasonModelRoute"),tone:"hit"};case"directMatch":return{label:s("workbench.hitSim.reasonDirectMatch"),tone:"hit"};case"thinkingDefault":return{label:s("workbench.hitSim.reasonThinkingDefault"),tone:"hit"};case"completionDefault":return{label:s("workbench.hitSim.reasonCompletionDefault"),tone:"hit"};case"longContextDefault":return{label:s("workbench.hitSim.reasonLongContext"),tone:"hit",detail:s("workbench.hitSim.longContextDetail",{estimate:a.tokenEstimate.toLocaleString(),threshold:a.threshold.toLocaleString()})};case"fallback":return{label:s("workbench.hitSim.reasonFallback"),tone:"fallback"}}return{label:s("workbench.hitSim.reasonFallback"),tone:"fallback"}}function cs({tabs:a,endpoint:s,onEndpointChange:o,hasUnsavedChanges:l=!1}){var D;const{t:r}=I(),g=a.filter(M=>M.key!=="providers"),[f,m]=N.useState(((D=g[0])==null?void 0:D.key)??"anthropic"),u=s??f,c=M=>{s&&o?o(M):m(M)},[b,y]=N.useState(""),[R,C]=N.useState(!1),[p,w]=N.useState("");N.useEffect(()=>{const M=setTimeout(()=>w(b.trim()),ls);return()=>clearTimeout(M)},[b]);const{data:v,isFetching:h,error:x}=qt(["routing","simulate",u,p,R],is.simulateRequest({endpoint:u,model:p||void 0,thinking:R}),{retry:!1,refetchOnWindowFocus:!1,staleTime:1/0});return e.jsxs("section",{"data-testid":"routing-hit-simulator",className:"space-y-3 rounded-lg border border-border bg-card p-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm font-semibold text-foreground",children:r("workbench.hitSim.title")}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:r("workbench.hitSim.subtitle")})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-2",children:[s?null:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:r("workbench.hitSim.endpointLabel")}),e.jsxs(Pe,{value:u,onValueChange:c,children:[e.jsx(Te,{className:"h-8 w-[168px]",children:e.jsx(Oe,{})}),e.jsx(Be,{children:g.map(M=>e.jsx(Le,{value:M.key,children:M.label},M.key))})]})]}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Fe,{checked:R,onCheckedChange:C,"aria-label":r("workbench.hitSim.thinking")}),r("workbench.hitSim.thinking")]})]}),e.jsx(J,{value:b,onChange:M=>y(M.target.value),placeholder:r("workbench.hitSim.modelPlaceholder"),className:"h-9 text-xs",spellCheck:!1,autoComplete:"off","aria-label":r("workbench.hitSim.modelPlaceholder")}),l?e.jsx("p",{"data-testid":"simulator-unsaved-notice",className:"text-[11px] text-warning",children:r("workbench.hitSim.unsavedNotice")}):null,e.jsx(us,{result:v,loading:h,errorMessage:(x==null?void 0:x.message)??null,requestedModel:p})]})}function us({result:a,loading:s,errorMessage:o,requestedModel:l}){var u;const{t:r}=I();if(o)return e.jsxs("p",{className:"text-xs text-muted-foreground",children:[r("workbench.hitSim.errorPrefix"),": ",o]});if(!a)return s?e.jsx("div",{className:"h-[72px] animate-pulse rounded-lg border border-border bg-secondary"}):e.jsx("p",{className:"text-xs text-muted-foreground",children:r("workbench.hitSim.empty")});const g=ds(a.reason,r),f=g.tone==="fallback",m=l||r("workbench.hitSim.anyModel");return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:f?"rounded-lg border border-border bg-secondary px-3 py-2.5":"rounded-lg border border-success bg-success-bg px-3 py-2.5",children:[e.jsx("div",{className:f?"text-[11px] font-semibold text-warning":"text-[11px] font-semibold text-success",children:g.label}),e.jsx("div",{className:"mt-1 text-xs text-foreground",children:m}),e.jsxs("div",{className:"mt-1 text-xs text-muted-foreground",children:["→ ",a.providerLabel,":",a.modelId]}),g.detail?e.jsx("div",{className:"mt-1 text-[11px] text-muted-foreground",children:g.detail}):null]}),(((u=a.candidates)==null?void 0:u.length)??0)>1?e.jsxs("div",{className:"rounded-lg border border-border bg-secondary/50 px-3 py-2.5",children:[e.jsx("div",{className:"text-[11px] font-semibold text-muted-foreground",children:r("providers.aggregate.simulator.candidatesTitle")}),e.jsx("ol",{className:"mt-1.5 space-y-1",children:(a.candidates??[]).map((c,b)=>e.jsxs("li",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"w-4 shrink-0 text-center text-[10.5px] tabular-nums text-muted-foreground",children:b+1}),e.jsxs("span",{className:"min-w-0 truncate font-mono text-foreground",children:[c.providerLabel,":",c.modelId]}),b===0?e.jsx("span",{className:"shrink-0 text-[10px] font-medium text-muted-foreground",children:r("providers.aggregate.simulator.primaryBadge")}):null]},`${c.providerId}:${c.modelId}`))})]}):null,f?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:r("workbench.hitSim.fallbackHint")}):null]})}function ms({routing:a,config:s,customEndpoints:o,routeCounts:l,selectedEndpointId:r,onSelectEndpoint:g,onEditEndpoint:f,onDeleteEndpoint:m}){var C;I();const u=r??((C=a.endpointTabs[0])==null?void 0:C.key)??"anthropic",c=a.endpointTabs.find(p=>p.key===u),b=a.defaultsByEndpoint[u],y=!!a.isDirtyByEndpoint[u]||!!a.isDefaultsDirtyByEndpoint[u],R=(()=>{var w;if(u==="anthropic")return"/anthropic";if(u==="openai")return"/openai";const p=o.find(v=>v.id===u);return(w=p==null?void 0:p.paths)!=null&&w.length?p.paths[0].path:p!=null&&p.path?p.path:`/${u}`})();return e.jsxs("div",{"data-testid":"routing-workspace",className:"flex flex-col gap-3.5",children:[e.jsx(as,{endpointPath:R,defaultTarget:(b==null?void 0:b.completion)??null}),e.jsxs("div",{className:"grid items-start gap-3.5 lg:grid-cols-[210px_minmax(0,2fr)_minmax(0,1fr)]",children:[e.jsx(ns,{tabs:a.endpointTabs,customEndpoints:o,routeCounts:l,selectedEndpointId:r,onSelect:g,onEditEndpoint:f,onDeleteEndpoint:m}),e.jsxs("div",{className:"flex flex-col gap-3.5",children:[e.jsx(ss,{routing:a,endpoint:u}),e.jsx(os,{routing:a,endpoint:u,tabInfo:c})]}),e.jsxs("div",{className:"flex flex-col gap-3.5 lg:sticky lg:top-4",children:[e.jsx(cs,{tabs:a.endpointTabs,endpoint:u,onEndpointChange:g,hasUnsavedChanges:y}),e.jsx(ts,{routing:a,endpoint:u,tabInfo:c,config:s,customEndpoints:o})]})]})]})}function Bs(){var he,ee,q,pe,te,H;const{t:a}=I(),s=Ut(),o=Wt(s),[l,r]=N.useState(!1),[g,f]=N.useState(void 0),[m,u]=N.useState(!1),[c,b]=N.useState(null),[y,R]=N.useState(!1),C=Object.values(o.isDirtyByEndpoint).some(Boolean)||Object.values(o.isDefaultsDirtyByEndpoint).some(Boolean),p=Lt(({currentLocation:k,nextLocation:T})=>C&&k.pathname!==T.pathname);N.useEffect(()=>{if(!C)return;const k=T=>{T.preventDefault(),T.returnValue=""};return window.addEventListener("beforeunload",k),()=>window.removeEventListener("beforeunload",k)},[C]);const[w,v]=Ft(),h=w.get("endpoint"),[x,D]=N.useState(h),[M,z]=N.useState(null);N.useEffect(()=>{D(h)},[h]);const K=N.useRef(!1);N.useEffect(()=>{if(!K.current){if(h){K.current=!0;return}o.endpointTabs.length!==0&&(K.current=!0,v(k=>{const T=new URLSearchParams(k);return T.set("endpoint",o.endpointTabs[0].key),T},{replace:!0}))}},[h,o.endpointTabs,v]);const V=N.useCallback(k=>{v(T=>{const Y=new URLSearchParams(T);return Y.set("endpoint",k),Y},{replace:!0})},[v]),oe=N.useCallback(()=>{v(k=>{const T=new URLSearchParams(k);return T.delete("endpoint"),T},{replace:!0})},[v]);N.useEffect(()=>{M&&o.endpointTabs.some(k=>k.key===M)&&(z(null),V(M))},[M,o.endpointTabs,V]),N.useEffect(()=>{x&&(s.customEndpointsQuery.isPending||o.endpointTabs.some(k=>k.key===x)||oe())},[x,o.endpointTabs,s.customEndpointsQuery.isPending,oe]);const ie=()=>{f(void 0),r(!0)},le=k=>{f(k),r(!0)},de=async()=>{if(c){R(!0);try{c.kind==="preset"?await o.handleDeletePreset(c.endpoint,c.preset):c.kind==="endpoint"&&await o.handleDeleteEndpoint(c.endpoint.id),b(null)}finally{R(!1)}}},Ne=(c==null?void 0:c.kind)==="preset"?a("modelManagement.presets.delete"):(c==null?void 0:c.kind)==="endpoint"?a("common.delete"):"",ce=(c==null?void 0:c.kind)==="preset"?a("modelManagement.confirm.deletePreset",{name:c.preset.name}):(c==null?void 0:c.kind)==="endpoint"?[a("modelManagement.deleteEndpointConfirm",{label:c.endpoint.label}),(((he=o.routesByEndpoint[c.endpoint.id])==null?void 0:he.length)??0)>0?a("modelManagement.deleteEndpointImpactRoutes",{count:((ee=o.routesByEndpoint[c.endpoint.id])==null?void 0:ee.length)??0}):"",(((q=o.presetsByEndpoint[c.endpoint.id])==null?void 0:q.length)??0)>0?a("modelManagement.deleteEndpointImpactPresets",{count:((pe=o.presetsByEndpoint[c.endpoint.id])==null?void 0:pe.length)??0}):""].filter(Boolean).join(" "):"",ue=(c==null?void 0:c.kind)==="preset"?c.preset.name:(c==null?void 0:c.kind)==="endpoint"?c.endpoint.label:"",me=Object.fromEntries(Object.entries(o.routesByEndpoint).map(([k,T])=>[k,(T==null?void 0:T.length)??0])),W=x??((te=o.endpointTabs[0])==null?void 0:te.key)??"anthropic",X=(k,T)=>{b({kind:"preset",endpoint:k,preset:T})};return e.jsxs("div",{className:"flex flex-col gap-6",children:[e.jsx(At,{actions:e.jsxs(e.Fragment,{children:[e.jsx(Xt,{tabs:o.endpointTabs,customEndpoints:s.customEndpoints,routeCounts:me,selectedEndpointId:W,onSelect:V,onEditEndpoint:le,onDeleteEndpoint:k=>b({kind:"endpoint",endpoint:k})}),e.jsxs(F,{variant:"outline",size:"sm",onClick:()=>u(!0),children:[e.jsx(Ot,{className:"h-4 w-4","aria-hidden":!0}),a("workbench.templates")]}),e.jsxs(F,{size:"sm",onClick:ie,children:[e.jsx(Ke,{className:"h-4 w-4","aria-hidden":!0}),a("workbench.endpoints.create")]})]})}),!s.config&&s.configQuery.isError?e.jsx(Je,{tone:"danger",icon:e.jsx(Bt,{className:"h-5 w-5","aria-hidden":"true"}),title:a("common.status.error"),description:((H=s.configQuery.error)==null?void 0:H.message)??a("common.status.error"),action:e.jsx(F,{variant:"outline",onClick:()=>void s.configQuery.refetch(),children:a("common.actions.refresh")})}):e.jsx(ms,{routing:o,config:s.config,customEndpoints:s.customEndpoints,routeCounts:me,selectedEndpointId:x,onSelectEndpoint:V,onEditEndpoint:le,onDeleteEndpoint:k=>b({kind:"endpoint",endpoint:k})}),e.jsx(es,{open:m,onOpenChange:u,routing:o,endpoint:W,onRequestDeletePreset:X}),e.jsx(Jt,{open:l,endpoint:g,onClose:()=>{r(!1),f(void 0)},onSuccess:k=>{s.configQuery.refetch(),k&&z(k)}}),e.jsx(Yt,{dialog:o.presetDiffDialog,currentRoutes:o.presetDiffDialog?o.routesByEndpoint[o.presetDiffDialog.endpoint]||[]:[],onConfirm:(k,T)=>{o.setPresetDiffDialog(null),o.handleApplyPreset(k,T)},onClose:()=>o.setPresetDiffDialog(null)}),e.jsx(Qe,{open:!!c,onOpenChange:k=>{!k&&!y&&b(null)},title:Ne,description:ce,confirmLabel:a(y?"common.actions.loading":"common.delete"),cancelLabel:a("common.actions.cancel"),loading:y,onConfirm:de,children:ue?e.jsx("div",{className:"rounded-xl border border-destructive/20 bg-destructive/5 px-3 py-2 font-mono text-xs text-foreground",children:ue}):null}),e.jsx(Qe,{open:p.state==="blocked",onOpenChange:k=>{!k&&p.state==="blocked"&&p.reset()},title:a("providers.masterDetail.unsavedTitle"),description:a("providers.masterDetail.unsavedBody"),confirmLabel:a("providers.masterDetail.unsavedConfirm"),cancelLabel:a("common.actions.cancel"),onConfirm:()=>{p.state==="blocked"&&p.proceed()}})]})}export{Bs as default};
@@ -1 +1 @@
1
- import{j as e,b5 as he,b0 as Tt,r as m,aY as Ft,a_ as Ot,av as Mt}from"./vendor-JUtelXU0.js";import{C as xe}from"./ConfirmDialog-CRSbmgE7.js";import{P as Se}from"./PageState-XybOeENt.js";import{P as Ht}from"./PageToolbar-CnLp4aWt.js";import{C as F,c as H,b as X,B as T,q as Y,r as G,e as Kt,d as qt,u as Bt,t as Ut}from"./app-CRxPj2SJ.js";import{B as I}from"./badge-eRkhnmCs.js";import{L as f,I as P}from"./label-CdbE1ezd.js";import{S as Z}from"./switch-CZn1nypU.js";import{S as je,a as Ne,b as Ce,c as we,d as z,D as Yt}from"./disclosure-CU-KJc8C.js";import{c as V}from"./global-BLUcvOa8.js";import{u as E}from"./i18n-v60Yn7Ls.js";import{a as Vt}from"./query-CvboQrUT.js";import{u as W}from"./useAppMutation-B29oVzxS.js";import{g as st}from"./gateway-DyhqzHSh.js";import{c as It}from"./clipboard-DqvcglYs.js";import{c as Qt}from"./types-BT3gK5lJ.js";import{g as _t}from"./router-CqUBCAsx.js";import"./DialogShell-DxWKa5oR.js";import"./radix-d0BukFWM.js";const zt={pricesRequest(){return{url:"/api/billing/prices",method:"GET"}}},$t=[{value:"fatal",labelKey:"fatal"},{value:"error",labelKey:"error"},{value:"warn",labelKey:"warn"},{value:"info",labelKey:"info"},{value:"debug",labelKey:"debug"},{value:"trace",labelKey:"trace"}],Pe="7.2";function Jt(){return{key:"",currency:"CNY",input:"",output:"",cacheRead:"",cacheCreation:"",label:""}}function ge(s){const t=s.billing,o=(t==null?void 0:t.displayCurrency)==="USD"?"USD":"CNY",c=(t==null?void 0:t.rates)??{};let a=Pe;o==="CNY"&&typeof c.USD=="number"&&c.USD>0?a=String(c.USD):o==="USD"&&typeof c.CNY=="number"&&c.CNY>0&&(a=String(1/c.CNY));const i=Object.entries((t==null?void 0:t.modelPrices)??{}).map(([u,n])=>{var l;return{key:u,currency:((l=n.currency)==null?void 0:l.toUpperCase())==="USD"?"USD":"CNY",input:String(n.input??0),output:String(n.output??0),cacheRead:String(n.cacheRead??0),cacheCreation:String(n.cacheCreation??0),label:n.label??""}});return{displayCurrency:o,usdCnyRate:a,overrides:i.length>0?i:[Jt()]}}function at(s){return!!(s.key.trim()||s.input.trim()||s.output.trim()||s.cacheRead.trim()||s.cacheCreation.trim()||s.label.trim())}function Gt(s){const t=Number(s.usdCnyRate),o=s.displayCurrency==="CNY"?{USD:Number.isFinite(t)&&t>0?t:Number(Pe)}:{CNY:Number.isFinite(t)&&t>0?1/t:1/Number(Pe)},c={};for(const a of s.overrides){if(!at(a))continue;const i=a.key.trim();i&&(c[i]={currency:a.currency,input:Number(a.input)||0,output:Number(a.output)||0,cacheRead:Number(a.cacheRead)||0,cacheCreation:Number(a.cacheCreation)||0,...a.label.trim()?{label:a.label.trim()}:{}})}return{displayCurrency:s.displayCurrency,rates:o,...Object.keys(c).length>0?{modelPrices:c}:{}}}const ke=[{id:"section-basics",labelKey:"settings.sections.basics"},{id:"section-protocol",labelKey:"settings.sections.protocol"},{id:"section-security",labelKey:"settings.sections.security"},{id:"section-billing",labelKey:"settings.sections.billing"},{id:"section-config-file",labelKey:"settings.sections.configFile"},{id:"section-cleanup",labelKey:"settings.sections.cleanup"}];function be(s){var c,a,i,u,n,l,g,O,L;const t=s.storePayloads,o=w=>typeof w=="boolean"?w:typeof t=="boolean"?t:!0;return{logRetentionDays:String(s.logRetentionDays??30),logExportTimeoutSeconds:String(s.logExportTimeoutSeconds??60),storeRequestPayloads:o(s.storeRequestPayloads),storeResponsePayloads:o(s.storeResponsePayloads),logLevel:s.logLevel??"info",bodyLimitMb:(()=>{const w=s.bodyLimit;return typeof w=="number"&&Number.isFinite(w)&&w>0?String(Math.max(1,Math.round(w/(1024*1024)))):"10"})(),enableRoutingFallback:s.enableRoutingFallback===!0,httpEnabled:((c=s.http)==null?void 0:c.enabled)!==!1,httpPort:String(((a=s.http)==null?void 0:a.port)??s.port??4100),httpHost:((i=s.http)==null?void 0:i.host)??s.host??"127.0.0.1",httpsEnabled:((u=s.https)==null?void 0:u.enabled)===!0,httpsPort:String(((n=s.https)==null?void 0:n.port)??4443),httpsHost:((l=s.https)==null?void 0:l.host)??s.host??"127.0.0.1",httpsKeyPath:((g=s.https)==null?void 0:g.keyPath)??"",httpsCertPath:((O=s.https)==null?void 0:O.certPath)??"",httpsCaPath:((L=s.https)==null?void 0:L.caPath)??""}}function fe(s){return{enabled:s.enabled,username:s.username??"",password:"",confirmPassword:""}}function Wt({activeSection:s,onSelectSection:t}){const{t:o}=E();return e.jsxs(e.Fragment,{children:[e.jsx("nav",{className:"hidden xl:block",children:e.jsxs(F,{className:"sticky top-20 p-3.5",children:[e.jsx("p",{className:"mb-2.5 px-2 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground",children:o("settings.sections.jump")}),e.jsx("div",{className:"space-y-1.5",children:ke.map((c,a)=>e.jsxs("button",{type:"button",onClick:()=>t(c.id),className:V("flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-left text-sm font-semibold transition-all duration-200",s===c.id?"bg-secondary text-foreground":"text-muted-foreground hover:text-foreground"),children:[e.jsx("span",{className:V("flex h-7 w-7 items-center justify-center rounded-lg text-[11px] font-semibold",s===c.id?"bg-foreground text-background":"bg-secondary text-muted-foreground"),children:a+1}),e.jsx("span",{children:o(c.labelKey)})]},c.id))})]})}),e.jsx("div",{className:"min-w-0 xl:hidden",children:e.jsx("div",{className:"overflow-x-auto pb-1",children:e.jsx("div",{className:"flex w-max gap-2 px-1",children:ke.map(c=>e.jsx("button",{type:"button",onClick:()=>t(c.id),className:V("rounded-lg px-4 py-2 text-xs font-semibold transition-all duration-150",s===c.id?"bg-secondary text-foreground font-medium":"text-muted-foreground hover:text-foreground hover:bg-secondary/50"),children:o(c.labelKey)},c.id))})})})]})}function Xt({defaultsSummary:s,errors:t,form:o,onInputChange:c,onSetForm:a,sectionRef:i}){const{t:u}=E();return e.jsx(F,{id:"section-basics",ref:i,className:"bg-card shadow-[var(--surface-shadow)]",children:e.jsxs(H,{className:"pt-6",children:[e.jsx("h3",{className:"mb-4 text-sm font-semibold",children:u("settings.sections.basics")}),e.jsxs("div",{className:"grid gap-5 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:u("settings.fields.port")}),e.jsx(P,{type:"number",min:1,max:65535,value:o.httpPort,"data-visual-volatile":"text",onChange:n=>a(l=>({...l,httpPort:n.target.value})),"aria-invalid":!!t.httpPort}),t.httpPort?e.jsx("p",{className:"text-xs text-destructive",children:t.httpPort}):null]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:u("settings.fields.host")}),e.jsx(P,{value:o.httpHost,onChange:n=>a(l=>({...l,httpHost:n.target.value})),placeholder:u("settings.fields.hostPlaceholder")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:u("settings.fields.retention")}),e.jsx(P,{type:"number",min:1,max:365,value:o.logRetentionDays,onChange:n=>c("logRetentionDays")(n.target.value),"aria-invalid":!!t.logRetentionDays}),t.logRetentionDays?e.jsx("p",{className:"text-xs text-destructive",children:t.logRetentionDays}):null]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:u("settings.fields.logExportTimeout")}),e.jsx(P,{type:"number",min:5,max:600,value:o.logExportTimeoutSeconds,onChange:n=>c("logExportTimeoutSeconds")(n.target.value),"aria-invalid":!!t.logExportTimeoutSeconds}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u("settings.fields.logExportTimeoutHint")}),t.logExportTimeoutSeconds?e.jsx("p",{className:"text-xs text-destructive",children:t.logExportTimeoutSeconds}):null]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:u("settings.fields.bodyLimit")}),e.jsx(P,{type:"number",min:1,max:2048,value:o.bodyLimitMb,onChange:n=>c("bodyLimitMb")(n.target.value),"aria-invalid":!!t.bodyLimitMb}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u("settings.fields.bodyLimitHint")}),t.bodyLimitMb?e.jsx("p",{className:"text-xs text-destructive",children:t.bodyLimitMb}):null]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:u("settings.fields.logLevel")}),e.jsxs(je,{value:o.logLevel,onValueChange:n=>a(l=>({...l,logLevel:n})),children:[e.jsx(Ne,{children:e.jsx(Ce,{})}),e.jsx(we,{children:$t.map(n=>e.jsx(z,{value:n.value,children:u(`settings.fields.logLevelOption.${n.labelKey}`)},n.value))})]})]}),e.jsxs("div",{className:"grid gap-4 md:col-span-2 sm:grid-cols-2",children:[e.jsx(ye,{label:u("settings.fields.storeRequestPayloads"),hint:u("settings.fields.storeRequestPayloadsHint"),checked:o.storeRequestPayloads,onCheckedChange:n=>a(l=>({...l,storeRequestPayloads:n}))}),e.jsx(ye,{label:u("settings.fields.storeResponsePayloads"),hint:u("settings.fields.storeResponsePayloadsHint"),checked:o.storeResponsePayloads,onCheckedChange:n=>a(l=>({...l,storeResponsePayloads:n}))}),e.jsx(ye,{label:u("settings.fields.enableRoutingFallback"),hint:u("settings.fields.enableRoutingFallbackHint"),checked:o.enableRoutingFallback,onCheckedChange:n=>a(l=>({...l,enableRoutingFallback:n}))})]}),e.jsxs("div",{className:"rounded-xl bg-secondary px-4 py-5 md:col-span-2",children:[e.jsx(f,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:u("settings.fields.defaults")}),e.jsx("p",{className:"mt-2 text-sm",children:s??u("settings.defaults.none")})]})]})]})})}function Zt({errors:s,form:t,onSetForm:o,protocolChangesPending:c,sectionRef:a}){const{t:i}=E();return e.jsx(F,{id:"section-protocol",ref:a,className:"bg-card shadow-[var(--surface-shadow)]",children:e.jsxs(H,{className:"space-y-6 pt-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:i("settings.sections.protocol")}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:i("settings.protocol.description")})]}),c?e.jsx("div",{className:"rounded-xl bg-warning-bg ring-1 ring-warning/30 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(he,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-warning"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:i("settings.protocol.restartWarning")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i("settings.protocol.restartHint")}),e.jsx("code",{className:"block rounded-lg border border-border bg-secondary px-3 py-2 text-xs font-mono text-foreground",children:"cc-gw restart --daemon"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i("settings.protocol.restartTip")})]})]})}):null,s.protocol?e.jsxs("div",{className:"rounded-xl bg-destructive/10 ring-1 ring-destructive/30 p-4 text-sm text-destructive",children:[e.jsx(he,{className:"mr-2 inline h-4 w-4"}),s.protocol]}):null,e.jsxs("div",{className:"rounded-xl bg-secondary p-5",children:[e.jsxs("div",{className:"mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(f,{className:"text-sm font-medium text-foreground",children:i("settings.protocol.http.enable")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i("settings.protocol.http.hint")})]}),e.jsx(Z,{checked:t.httpEnabled,onCheckedChange:u=>o(n=>({...n,httpEnabled:u}))})]}),t.httpEnabled?e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:i("settings.protocol.http.listener",{address:`${t.httpHost||"127.0.0.1"}:${t.httpPort||"4100"}`})})}):null]}),e.jsxs("div",{className:"rounded-xl bg-secondary p-5",children:[e.jsxs("div",{className:"mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(f,{className:"text-sm font-medium text-foreground",children:i("settings.protocol.https.enable")}),e.jsx(Tt,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i("settings.protocol.https.hint")})]}),e.jsx(Z,{checked:t.httpsEnabled,onCheckedChange:u=>o(n=>({...n,httpsEnabled:u}))})]}),t.httpsEnabled?e.jsxs("div",{className:"mt-4 space-y-4 border-t border-border pt-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:i("settings.protocol.https.port")}),e.jsx(P,{type:"number",min:1,max:65535,value:t.httpsPort,onChange:u=>o(n=>({...n,httpsPort:u.target.value})),"aria-invalid":!!s.httpsPort}),s.httpsPort?e.jsx("p",{className:"text-xs text-destructive",children:s.httpsPort}):null]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:i("settings.protocol.https.host")}),e.jsx(P,{value:t.httpsHost,onChange:u=>o(n=>({...n,httpsHost:u.target.value})),placeholder:"127.0.0.1"})]})]}),e.jsx(ve,{label:i("settings.protocol.https.keyPath"),value:t.httpsKeyPath,onChange:u=>o(n=>({...n,httpsKeyPath:u})),placeholder:"~/.cc-gw/certs/key.pem"}),e.jsx(ve,{label:i("settings.protocol.https.certPath"),value:t.httpsCertPath,onChange:u=>o(n=>({...n,httpsCertPath:u})),placeholder:"~/.cc-gw/certs/cert.pem"}),e.jsx(ve,{label:i("settings.protocol.https.caPath"),value:t.httpsCaPath,onChange:u=>o(n=>({...n,httpsCaPath:u})),placeholder:"留空则不使用"}),e.jsx("div",{className:"rounded-xl bg-warning-bg ring-1 ring-warning/30 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(he,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-warning"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx("p",{className:"text-sm font-medium text-warning",children:i("settings.protocol.https.warning")}),e.jsx("p",{className:"text-xs leading-relaxed text-warning",children:i("settings.protocol.https.tip")})]})]})})]}):null]})]})})}function es({authErrors:s,authForm:t,authLoading:o,authSettings:c,needsPassword:a,onSetAuthForm:i,sectionRef:u}){const{t:n}=E();return e.jsx(F,{id:"section-security",ref:u,className:"bg-card shadow-[var(--surface-shadow)]",children:e.jsxs(H,{className:"space-y-5 pt-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:n("settings.sections.security")}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:n("settings.auth.description")})]}),o&&!c?e.jsx(Se,{compact:!0,label:n("common.loading")}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-4 rounded-xl bg-secondary p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{className:"text-sm font-medium",children:n("settings.auth.enable")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:n("settings.auth.enableHint")}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-xs font-medium text-muted-foreground",children:[e.jsx("span",{className:"rounded-lg bg-secondary px-3 py-1 text-[11px] tracking-[0.08em]",children:"/ui"}),e.jsx("span",{className:"rounded-lg bg-secondary px-3 py-1 text-[11px] tracking-[0.08em]",children:"/api/*"}),e.jsx("span",{className:"rounded-lg bg-secondary px-3 py-1 text-[11px] tracking-[0.08em]",children:"Cookie Session"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 self-start sm:self-auto",children:[e.jsx(I,{variant:t.enabled?"success":"secondary",children:t.enabled?n("settings.auth.statusEnabled"):n("settings.auth.statusDisabled")}),e.jsx(Z,{checked:t.enabled,onCheckedChange:l=>i(g=>({...g,enabled:l}))})]})]}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,0.85fr)]",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(f,{children:n("settings.auth.username")}),e.jsx(P,{value:t.username,onChange:l=>i(g=>({...g,username:l.target.value})),placeholder:n("settings.auth.usernamePlaceholder")}),s.username?e.jsx("p",{className:"text-xs text-destructive",children:s.username}):null]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:n("settings.auth.password")}),e.jsx(P,{type:"password",value:t.password,disabled:!t.enabled,onChange:l=>i(g=>({...g,password:l.target.value})),placeholder:n("settings.auth.passwordPlaceholder")}),s.password?e.jsx("p",{className:"text-xs text-destructive",children:s.password}):e.jsx("p",{className:"text-xs text-muted-foreground",children:n(a?"settings.auth.passwordHintRequired":"settings.auth.passwordHintOptional")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:n("settings.auth.confirmPassword")}),e.jsx(P,{type:"password",value:t.confirmPassword,disabled:!t.enabled,onChange:l=>i(g=>({...g,confirmPassword:l.target.value})),placeholder:n("settings.auth.confirmPasswordPlaceholder")}),s.confirmPassword?e.jsx("p",{className:"text-xs text-destructive",children:s.confirmPassword}):null]})]}),e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"rounded-xl bg-secondary p-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.34em] text-muted-foreground",children:n("settings.auth.status")}),e.jsx("p",{className:"mt-2 text-base font-semibold",children:c!=null&&c.enabled?n("settings.auth.statusEnabled"):n("settings.auth.statusDisabled")}),c!=null&&c.username?e.jsxs("div",{className:"mt-3 rounded-lg bg-background px-3 py-2 text-xs font-medium text-foreground",children:[n("settings.auth.username"),": ",c.username]}):null]}),e.jsx("div",{className:"rounded-xl bg-secondary px-4 py-3 text-xs text-muted-foreground",children:n(a?"settings.auth.passwordHintRequired":"settings.auth.passwordHintOptional")})]})]})]})]})})}function ts({errors:s,form:t,onSetForm:o,sectionRef:c}){var K;const{t:a}=E(),[i,u]=m.useState(""),n=X(Y.billing.prices(),zt.pricesRequest()),l=(h,d)=>{o(y=>({...y,overrides:y.overrides.map((k,R)=>R===h?{...k,...d}:k)}))},g=h=>{o(d=>({...d,overrides:d.overrides.filter((y,k)=>k!==h)}))},O=()=>{o(h=>({...h,overrides:[...h.overrides,{key:"",currency:"CNY",input:"",output:"",cacheRead:"",cacheCreation:"",label:""}]}))},L=m.useMemo(()=>{var y;const h=((y=n.data)==null?void 0:y.entries)??[],d=i.trim().toLowerCase();return d?h.filter(k=>k.key.toLowerCase().includes(d)):h},[n.data,i]),w=h=>h.toLocaleString(void 0,{maximumFractionDigits:4});return e.jsx(F,{id:"section-billing",ref:c,className:"bg-card shadow-[var(--surface-shadow)]",children:e.jsxs(H,{className:"space-y-6 pt-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:a("settings.sections.billing")}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:a("billing.description")})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:a("billing.displayCurrency")}),e.jsxs(je,{value:t.displayCurrency,onValueChange:h=>o(d=>({...d,displayCurrency:h==="USD"?"USD":"CNY"})),children:[e.jsx(Ne,{"aria-label":a("billing.displayCurrency"),children:e.jsx(Ce,{})}),e.jsxs(we,{children:[e.jsx(z,{value:"CNY",children:"CNY(¥)"}),e.jsx(z,{value:"USD",children:"USD($)"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:a("billing.displayCurrencyHint")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:a("billing.rateLabel")}),e.jsx(P,{type:"number",min:"0",step:"0.0001",value:t.usdCnyRate,onChange:h=>o(d=>({...d,usdCnyRate:h.target.value})),"aria-invalid":!!s.usdCnyRate}),s.usdCnyRate?e.jsx("p",{className:"text-xs text-destructive",children:s.usdCnyRate}):e.jsx("p",{className:"text-xs text-muted-foreground",children:a("billing.rateHint",{value:(1/(Number(t.usdCnyRate)||1)).toFixed(4)})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:a("billing.overrides.title")}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:a("billing.overrides.description")})]}),e.jsxs(T,{type:"button",variant:"outline",size:"sm",onClick:O,children:[e.jsx(Ft,{className:"mr-1.5 h-3.5 w-3.5","aria-hidden":"true"}),a("billing.overrides.add")]})]}),e.jsx("div",{className:"space-y-3",children:t.overrides.map((h,d)=>{var k;const y=(k=s.overrides)==null?void 0:k[d];return e.jsxs("div",{"data-testid":`billing-override-row-${d}`,className:"grid gap-3 rounded-xl bg-secondary/60 p-3 lg:grid-cols-[minmax(0,1.4fr)_auto_repeat(4,minmax(0,0.8fr))_auto] lg:items-end",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(f,{className:"text-xs text-muted-foreground",children:a("billing.overrides.key")}),e.jsx(P,{value:h.key,onChange:R=>l(d,{key:R.target.value}),placeholder:"claude-sonnet-4-5 / acme:internal-model","aria-invalid":!!(y!=null&&y.key)}),y!=null&&y.key?e.jsx("p",{className:"text-xs text-destructive",children:y.key}):e.jsx("p",{className:"text-xs text-muted-foreground/70",children:a("billing.overrides.keyHint")})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(f,{className:"text-xs text-muted-foreground",children:a("billing.overrides.currency")}),e.jsxs(je,{value:h.currency,onValueChange:R=>l(d,{currency:R}),children:[e.jsx(Ne,{className:"w-[92px]","aria-label":a("billing.overrides.currency"),children:e.jsx(Ce,{})}),e.jsxs(we,{children:[e.jsx(z,{value:"CNY",children:"CNY"}),e.jsx(z,{value:"USD",children:"USD"})]})]})]}),[["input","priceInput"],["output","priceOutput"],["cacheRead","priceCacheRead"],["cacheCreation","priceCacheCreation"]].map(([R,p])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(f,{className:"text-xs text-muted-foreground",children:a(`billing.overrides.${p}`)}),e.jsx(P,{type:"number",min:"0",step:"0.0001",value:h[R],onChange:q=>l(d,{[R]:q.target.value})})]},R)),e.jsx(T,{type:"button",variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>g(d),disabled:t.overrides.length===1,"aria-label":a("billing.overrides.remove"),children:e.jsx(Ot,{className:"h-4 w-4","aria-hidden":"true"})}),y!=null&&y.prices?e.jsx("p",{className:"text-xs text-destructive lg:col-span-7",children:y.prices}):null]},d)})})]}),e.jsx(Yt,{summary:e.jsx("span",{className:"text-sm font-medium",children:a("billing.builtin.title")}),badge:e.jsx(I,{variant:"secondary",className:"text-[10px]",children:L.length}),contentClassName:"border-t border-border p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:a("billing.builtin.description")}),e.jsx(P,{value:i,onChange:h=>u(h.target.value),placeholder:a("billing.builtin.filterPlaceholder"),className:"max-w-xs"}),n.isPending?e.jsx(Se,{compact:!0,label:a("common.loadingShort")}):n.isError?e.jsx("p",{className:"text-xs text-destructive",children:a("billing.builtin.loadError",{message:((K=n.error)==null?void 0:K.message)??""})}):e.jsx("div",{className:"max-h-[320px] overflow-auto rounded-lg border border-border bg-card",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"sticky top-0 bg-secondary text-left uppercase tracking-wider text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2 font-semibold",children:a("billing.builtin.columns.key")}),e.jsx("th",{className:"px-3 py-2 font-semibold",children:a("billing.builtin.columns.source")}),e.jsx("th",{className:"px-3 py-2 text-right font-semibold",children:a("billing.builtin.columns.input")}),e.jsx("th",{className:"px-3 py-2 text-right font-semibold",children:a("billing.builtin.columns.output")}),e.jsx("th",{className:"px-3 py-2 text-right font-semibold",children:a("billing.builtin.columns.cacheRead")}),e.jsx("th",{className:"px-3 py-2 text-right font-semibold",children:a("billing.builtin.columns.cacheCreation")})]})}),e.jsxs("tbody",{className:"divide-y divide-border/60",children:[L.map(h=>e.jsxs("tr",{className:"tabular-nums",children:[e.jsx("td",{className:"px-3 py-1.5 font-mono",children:h.key}),e.jsx("td",{className:"px-3 py-1.5",children:e.jsx(I,{variant:h.source==="override"?"default":"secondary",className:"text-[10px]",children:h.source})}),e.jsx("td",{className:"px-3 py-1.5 text-right",children:w(h.input)}),e.jsx("td",{className:"px-3 py-1.5 text-right",children:w(h.output)}),e.jsx("td",{className:"px-3 py-1.5 text-right",children:w(h.cacheRead)}),e.jsx("td",{className:"px-3 py-1.5 text-right",children:w(h.cacheCreation)})]},`${h.source}:${h.key}`)),L.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-3 py-4 text-center text-muted-foreground",children:a("billing.builtin.empty")})}):null]})]})}),e.jsx("p",{className:"text-xs text-muted-foreground/70",children:a("billing.builtin.footnote")})]})}),e.jsx("div",{className:"rounded-xl bg-secondary px-4 py-3 text-xs text-muted-foreground",children:a("billing.estimateNote")})]})})}function ss({configPath:s,onCopyPath:t,sectionRef:o}){const{t:c}=E();return e.jsx(F,{id:"section-config-file",ref:o,className:"bg-card shadow-[var(--surface-shadow)]",children:e.jsxs(H,{className:"space-y-3 pt-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:c("settings.sections.configFile")}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:c("settings.file.description")})]}),e.jsxs(T,{variant:"outline",size:"sm",onClick:t,className:"w-full sm:w-auto",children:[e.jsx(Mt,{className:"mr-2 h-4 w-4"}),c("common.actions.copy")]})]}),e.jsx("code",{"data-visual-volatile":"true",className:"block break-all rounded-lg bg-secondary px-4 py-3 text-xs font-mono text-muted-foreground",children:s||c("settings.file.unknown")}),e.jsx("div",{className:"rounded-lg bg-secondary px-4 py-3 text-xs text-muted-foreground",children:c("help.note")})]})})}function as({cleaning:s,clearingAll:t,compacting:o,dbSizeDisplay:c,onCompact:a,onOpenCleanup:i,onOpenClearAll:u,sectionRef:n}){const{t:l}=E();return e.jsx(F,{id:"section-cleanup",ref:n,className:"bg-card shadow-[var(--surface-shadow)]",children:e.jsxs(H,{className:"space-y-4 pt-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:l("settings.sections.cleanup")}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:l("settings.cleanup.description")})]}),e.jsxs("div",{className:"rounded-lg bg-secondary px-3 py-1.5 text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:[l("settings.cleanup.dbSizeLabel"),": "]}),e.jsx("span",{className:"font-semibold tabular-nums text-foreground",children:c})]})]}),e.jsx("div",{className:"rounded-lg bg-secondary px-4 py-3 text-xs text-muted-foreground",children:l("settings.cleanup.confirmCleanup")}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsx("div",{className:"rounded-xl border border-warning/30 bg-warning-bg p-5",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{variant:"warning",children:l("settings.cleanup.softLabel")}),e.jsx("p",{className:"text-sm font-medium",children:l("settings.cleanup.softTitle")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l("settings.cleanup.softDescription")}),e.jsx(T,{variant:"outline",onClick:i,disabled:s,className:"w-full sm:w-auto",children:l(s?"common.actions.cleaning":"common.actions.cleanup")})]})}),e.jsx("div",{className:"rounded-xl border border-destructive/30 bg-destructive/10 p-5 text-destructive",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{variant:"outline",className:"border-destructive/40 bg-destructive/10 text-destructive",children:l("settings.cleanup.hardLabel")}),e.jsx("p",{className:"text-sm font-medium",children:l("settings.cleanup.hardTitle")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l("settings.cleanup.clearAllWarning")}),e.jsx(T,{variant:"destructive",onClick:u,disabled:t,className:"w-full sm:w-auto",children:l(t?"settings.cleanup.clearingAll":"settings.cleanup.clearAll")})]})})]}),e.jsx("div",{className:"rounded-xl border border-border bg-secondary/40 p-5",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium",children:l("settings.cleanup.compactTitle")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l("settings.cleanup.compactDescription")})]}),e.jsx(T,{variant:"outline",onClick:a,disabled:o,className:"w-full sm:w-auto",children:l(o?"common.actions.compacting":"common.actions.compact")})]})})]})})}function ns({dirtyCount:s,protocolChangesPending:t,onReset:o,onSave:c,saving:a}){const{t:i}=E();return s===0?null:e.jsxs("div",{className:"sticky bottom-4 z-20 flex flex-col gap-3 rounded-xl bg-card border border-border px-6 py-5 shadow-[var(--surface-shadow-lg)] md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(I,{variant:"secondary",children:i("settings.overview.unsavedCount",{count:s})}),e.jsx("p",{className:"text-sm text-muted-foreground",children:i(t?"settings.toast.protocolRestartRequired":"modelManagement.actions.footerDirtyHint")})]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2 lg:flex lg:flex-wrap lg:items-center",children:[e.jsx(T,{variant:"outline",onClick:o,disabled:a,className:"w-full lg:w-auto",children:i("common.actions.reset")}),e.jsx(T,{onClick:c,disabled:a,className:"w-full lg:w-auto",children:i(a?"common.actions.saving":"common.actions.save")})]})]})}function ye({checked:s,className:t,hint:o,hintClassName:c,label:a,labelClassName:i,onCheckedChange:u}){return e.jsxs("div",{className:V("flex flex-col gap-3 rounded-xl bg-secondary p-4 sm:flex-row sm:items-center sm:justify-between",t),children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(f,{className:V("text-sm font-semibold text-foreground",i),children:a}),e.jsx("p",{className:V("text-xs text-muted-foreground",c),children:o})]}),e.jsx(Z,{checked:s,onCheckedChange:u,className:"self-start sm:self-auto"})]})}function ve({label:s,onChange:t,placeholder:o,value:c}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:s}),e.jsx(P,{value:c,onChange:a=>t(a.target.value),placeholder:o,className:"font-mono text-xs"})]})}const _={authStatusRequest(){return{url:"/api/auth/web",method:"GET"}},saveWebAuth:async s=>Kt(qt.post("/api/auth/web",s)),cleanupLogs:async()=>G({url:"/api/logs/cleanup",method:"POST"}),clearLogs:async()=>G({url:"/api/logs/clear",method:"POST"}),dbInfo:async()=>G({url:"/api/db/info",method:"GET"}),compactDb:async()=>G({url:"/api/db/compact",method:"POST"})};function is(){const{t:s}=E(),{pushToast:t}=Bt(),o=Vt(),[c,a]=m.useState(ke[0].id),i=m.useRef(new Map),u=m.useCallback(r=>{const x=i.current.get(r);x&&x.scrollIntoView({behavior:"smooth",block:"start"})},[]),n=m.useCallback(r=>x=>{x?i.current.set(r,x):i.current.delete(r)},[]),l=X(Y.config.info(),st.configInfoRequest()),g=X(Y.auth.web(),_.authStatusRequest()),O=W({mutationFn:_.saveWebAuth,successToast:()=>({title:s("settings.auth.toast.success")}),errorToast:r=>({title:s("settings.auth.toast.failure",{message:r.message})}),invalidateKeys:[Y.auth.web()]}),L=W({mutationFn:_.cleanupLogs,successToast:r=>({title:r.deleted>0?s("settings.toast.cleanupSuccess",{count:r.deleted}):s("settings.toast.cleanupNone")}),errorToast:r=>({title:s("settings.toast.cleanupFailure",{message:r.message})}),invalidateKeys:[["logs"],["dashboard"],["db"]]}),w=W({mutationFn:_.clearLogs,successToast:r=>({title:s("settings.toast.clearAllSuccess",{logs:r.deleted,metrics:r.metricsCleared})}),errorToast:r=>({title:s("settings.toast.clearAllFailure",{message:r.message})}),invalidateKeys:[["logs"],["stats"],["dashboard"],["db"]]}),K=X(Y.db.info(),{url:"/api/db/info",method:"GET"}),h=W({mutationFn:_.compactDb,successToast:()=>({title:s("settings.toast.compactSuccess.title"),description:s("settings.toast.compactSuccess.desc")}),errorToast:r=>({title:s("settings.toast.compactFailure",{message:r.message})}),invalidateKeys:[Y.db.info(),["dashboard"]]}),[d,y]=m.useState(null),[k,R]=m.useState(""),[p,q]=m.useState({logRetentionDays:"",logExportTimeoutSeconds:"60",storeRequestPayloads:!0,storeResponsePayloads:!0,logLevel:"info",bodyLimitMb:"10",enableRoutingFallback:!1,httpEnabled:!0,httpPort:"4100",httpHost:"127.0.0.1",httpsEnabled:!1,httpsPort:"4443",httpsHost:"127.0.0.1",httpsKeyPath:"",httpsCertPath:"",httpsCaPath:""}),[nt,ee]=m.useState({}),[it,Re]=m.useState(!1),[lt,Ee]=m.useState(!1),[rt,Le]=m.useState(!1),[ot,ct]=m.useState(!1),[dt,ut]=m.useState(!1),[N,Ae]=m.useState(null),[b,$]=m.useState({enabled:!1,username:"",password:"",confirmPassword:""}),[mt,J]=m.useState({}),[pt,De]=m.useState(!1),[D,te]=m.useState({displayCurrency:"CNY",usdCnyRate:"7.2",overrides:[{key:"",currency:"CNY",input:"",output:"",cacheRead:"",cacheCreation:"",label:""}]}),[ht,se]=m.useState({}),xt=m.useMemo(()=>{if(!(d!=null&&d.defaults))return null;const r=[];return d.defaults.completion&&r.push(s("settings.defaults.completion",{model:d.defaults.completion})),d.defaults.reasoning&&r.push(s("settings.defaults.reasoning",{model:d.defaults.reasoning})),d.defaults.background&&r.push(s("settings.defaults.background",{model:d.defaults.background})),r.length>0?r.join(" | "):s("settings.defaults.none")},[d,s]),gt=m.useMemo(()=>p.httpEnabled&&p.httpsEnabled?s("settings.overview.values.httpAndHttps"):p.httpsEnabled?s("settings.overview.values.httpsOnly"):s("settings.overview.values.httpOnly"),[p.httpEnabled,p.httpsEnabled,s]),bt=m.useMemo(()=>b.enabled?N!=null&&N.hasPassword?b.username.trim()!==(N.username??""):!0:!1,[b.enabled,b.username,N]),B=m.useMemo(()=>d?be(d):null,[d]),ae=m.useMemo(()=>B?JSON.stringify(p)!==JSON.stringify(B):!1,[p,B]),ne=m.useMemo(()=>N?fe(N):null,[N]),ie=m.useMemo(()=>ne?JSON.stringify(b)!==JSON.stringify(ne):!1,[b,ne]),le=m.useMemo(()=>d?ge(d):null,[d]),U=m.useMemo(()=>le?JSON.stringify(D)!==JSON.stringify(le):!1,[D,le]),ft=m.useMemo(()=>B?["httpEnabled","httpPort","httpHost","httpsEnabled","httpsPort","httpsHost","httpsKeyPath","httpsCertPath","httpsCaPath"].some(x=>p[x]!==B[x]):!1,[p,B]);m.useEffect(()=>{l.data&&(y(l.data.config),R(l.data.path),q(be(l.data.config)),te(ge(l.data.config)),se({}))},[l.data]),m.useEffect(()=>{g.data&&(Ae(g.data),$(fe(g.data)),J({}))},[g.data]),m.useEffect(()=>{!l.isError||!l.error||t({title:s("settings.toast.loadFailure",{message:l.error.message}),variant:"error"})},[l.error,l.isError,t,s]),m.useEffect(()=>{!g.isError||!g.error||t({title:s("settings.toast.authLoadFailure",{message:g.error.message}),variant:"error"})},[g.error,g.isError,t,s]);const yt=m.useCallback(r=>x=>{q(C=>({...C,[r]:x}))},[]),Te=m.useCallback(()=>{const r={};!p.httpEnabled&&!p.httpsEnabled&&(r.protocol=s("settings.validation.protocolRequired"));const x=Number(p.httpPort);if((!Number.isFinite(x)||x<1||x>65535)&&(r.httpPort=s("settings.validation.httpPort")),p.httpsEnabled){const M=Number(p.httpsPort);(!Number.isFinite(M)||M<1||M>65535)&&(r.httpsPort=s("settings.validation.httpsPort")),(!p.httpsKeyPath||!p.httpsCertPath)&&(r.protocol=s("settings.validation.httpsCertificate"))}const C=Number(p.logRetentionDays);(!Number.isFinite(C)||C<1||C>365)&&(r.logRetentionDays=s("settings.validation.retention"));const v=Number(p.logExportTimeoutSeconds);(!Number.isFinite(v)||v<5||v>600)&&(r.logExportTimeoutSeconds=s("settings.validation.logExportTimeout"));const S=Number(p.bodyLimitMb);return(!Number.isFinite(S)||S<1||S>2048)&&(r.bodyLimitMb=s("settings.validation.bodyLimit")),ee(r),Object.keys(r).length===0},[p,s]),Fe=m.useCallback(()=>{const r={},x=b.username.trim(),C=N?x!==(N.username??""):!0,v=b.enabled&&(!(N!=null&&N.hasPassword)||C);return b.enabled&&!x&&(r.username=s("settings.auth.validation.username")),b.password&&b.password.length<6&&(r.password=s("settings.auth.validation.minLength")),v&&!b.password&&(r.password=s("settings.auth.validation.passwordRequired")),(b.password||b.confirmPassword)&&b.password!==b.confirmPassword&&(r.confirmPassword=s("settings.auth.validation.confirmMismatch")),J(r),Object.keys(r).length===0},[b,N,s]),Oe=m.useCallback(()=>{const r={},x=Number(D.usdCnyRate);(!Number.isFinite(x)||x<=0||x>1e4)&&(r.usdCnyRate=s("billing.validation.rate")),r.overrides=D.overrides.map(v=>{if(!at(v))return;const S={};if(!v.key.trim())S.key=s("billing.validation.keyRequired");else{const A=v.key.trim(),Q=A.indexOf(":");(Q===0||Q===A.length-1)&&(S.key=s("billing.validation.keyFormat"))}return[v.input,v.output,v.cacheRead,v.cacheCreation].some(A=>A.trim()!==""&&(!Number.isFinite(Number(A))||Number(A)<0))&&(S.prices=s("billing.validation.prices")),Object.keys(S).length>0?S:void 0});const C=r.overrides.some(Boolean);return se(r),!r.usdCnyRate&&!C},[D,s]),re=m.useCallback(async()=>{var r,x,C,v,S,M,A,Q,Me,He,Ke,qe,Be,Ue,Ye,Ve,Ie,Qe,_e,ze,$e,Je,Ge,We,Xe,Ze;if(!d){t({title:s("settings.toast.loadFailure",{message:s("settings.toast.missingConfig")}),variant:"error"});return}if(Te()&&Oe()){Re(!0);try{const me=Number(p.logRetentionDays),kt=Number(p.logExportTimeoutSeconds),St=Number(p.bodyLimitMb),j={...d,http:{enabled:p.httpEnabled,port:Number(p.httpPort),host:p.httpHost.trim()||"127.0.0.1"},https:{enabled:p.httpsEnabled,port:Number(p.httpsPort),host:p.httpsHost.trim()||"127.0.0.1",keyPath:p.httpsKeyPath.trim(),certPath:p.httpsCertPath.trim(),caPath:p.httpsCaPath.trim()||void 0},port:Number(p.httpPort),host:p.httpHost.trim()||void 0,logRetentionDays:me,logExportTimeoutSeconds:Math.min(Math.max(Math.round(kt),5),600),storeRequestPayloads:p.storeRequestPayloads,storeResponsePayloads:p.storeResponsePayloads,logLevel:p.logLevel,bodyLimit:Math.max(1,Math.floor(St*1024*1024)),enableRoutingFallback:p.enableRoutingFallback,...U?{billing:Gt(D)}:{}};delete j.requestLogging,delete j.responseLogging;const et={...j};delete et.webAuth,await st.saveConfig(et),y({...j,webAuth:d.webAuth});const tt=pe=>(pe==null?void 0:pe.trim())||void 0,Rt=d.port??((r=d.http)==null?void 0:r.port)??4100,Et=j.port??((x=j.http)==null?void 0:x.port)??4100,Lt=((C=d.host)==null?void 0:C.trim())||((S=(v=d.http)==null?void 0:v.host)==null?void 0:S.trim())||"127.0.0.1",At=((M=j.host)==null?void 0:M.trim())||((Q=(A=j.http)==null?void 0:A.host)==null?void 0:Q.trim())||"127.0.0.1",Dt=Rt!==Et||Lt!==At||((Me=d.http)==null?void 0:Me.enabled)!==((He=j.http)==null?void 0:He.enabled)||((Ke=d.http)==null?void 0:Ke.port)!==((qe=j.http)==null?void 0:qe.port)||(((Be=d.http)==null?void 0:Be.host)??d.host??"127.0.0.1")!==(((Ue=j.http)==null?void 0:Ue.host)??j.host??"127.0.0.1")||((Ye=d.https)==null?void 0:Ye.enabled)!==((Ve=j.https)==null?void 0:Ve.enabled)||((Ie=d.https)==null?void 0:Ie.port)!==((Qe=j.https)==null?void 0:Qe.port)||(((_e=d.https)==null?void 0:_e.host)??d.host??"127.0.0.1")!==(((ze=j.https)==null?void 0:ze.host)??j.host??"127.0.0.1")||(($e=d.https)==null?void 0:$e.keyPath)!==((Je=j.https)==null?void 0:Je.keyPath)||((Ge=d.https)==null?void 0:Ge.certPath)!==((We=j.https)==null?void 0:We.certPath)||tt((Xe=d.https)==null?void 0:Xe.caPath)!==tt((Ze=j.https)==null?void 0:Ze.caPath);t({title:s(Dt?"settings.toast.protocolRestartRequired":"settings.toast.saveSuccess"),variant:"success"}),U&&(o.invalidateQueries({queryKey:["stats"]}),o.invalidateQueries({queryKey:["dashboard"]}),o.invalidateQueries({queryKey:["logs"]}),o.invalidateQueries({queryKey:["billing"]}),o.invalidateQueries({queryKey:["api-keys"]})),l.refetch()}catch(me){t({title:s("settings.toast.saveFailure",{message:Ut(me).message}),variant:"error"})}finally{Re(!1)}}},[D,d,l,p,U,t,o,s,Te,Oe]),oe=m.useCallback(()=>{d&&(q(be(d)),te(ge(d)),ee({}),se({}))},[d]),ce=m.useCallback(async()=>{if(Fe()){De(!0);try{const r={enabled:b.enabled,username:b.username.trim()||void 0};b.password&&(r.password=b.password);const x=await O.mutateAsync(r);x.auth&&(Ae(x.auth),$({enabled:x.auth.enabled,username:x.auth.username??"",password:"",confirmPassword:""}),J({})),g.refetch()}catch{}finally{De(!1)}}},[b,g,O,Fe]),de=m.useCallback(()=>{N&&($(fe(N)),J({}))},[N]),vt=m.useCallback(async()=>{(ae||U)&&await re(),ie&&await ce()},[ce,re,ie,U,ae]),jt=m.useCallback(()=>{oe(),de()},[de,oe]),Nt=m.useCallback(async()=>{if(!k){t({title:s("settings.toast.copyFailure",{message:s("settings.file.unknown")}),variant:"error"});return}try{await It(k),t({title:s("settings.toast.copySuccess"),variant:"success"})}catch(r){t({title:s("settings.toast.copyFailure",{message:r instanceof Error?r.message:"unknown"}),variant:"error"})}},[k,t,s]),Ct=m.useCallback(async()=>{Ee(!0);try{await L.mutateAsync()}catch{}finally{Ee(!1)}},[L]),wt=m.useCallback(async()=>{Le(!0);try{await w.mutateAsync()}catch{}finally{Le(!1)}},[w]),Pt=K.data?Qt(K.data.totalBytes??K.data.sizeBytes):"-",ue=l.isPending||!d&&l.isFetching;return m.useEffect(()=>{if(ue)return;const r=Array.from(i.current.values());if(r.length===0)return;const x=new IntersectionObserver(C=>{for(const v of C)if(v.isIntersecting){a(v.target.id);break}},{rootMargin:"-80px 0px -60% 0px",threshold:0});for(const C of r)x.observe(C);return()=>x.disconnect()},[ue]),{activeSection:c,authErrors:mt,authForm:b,authQuery:g,authSettings:N,billingErrors:ht,billingForm:D,clearingAll:rt,cleaning:lt,compacting:h.isPending,config:d,configPath:k,configQuery:l,confirmCleanupOpen:ot,confirmClearAllOpen:dt,dbSizeDisplay:Pt,defaultsSummary:xt,errors:nt,form:p,handleAuthReset:de,handleAuthSave:ce,handleCleanupLogs:Ct,handleClearAllLogs:wt,handleCompact:h.mutate,handleCopyPath:Nt,handleInputChange:yt,handleReset:oe,handleResetAll:jt,handleSave:re,handleSaveAll:vt,handleSectionClick:u,isAuthDirty:ie,isBillingDirty:U,isConfigDirty:ae,isLoading:ue,needsPassword:bt,protocolSummaryLabel:gt,protocolChangesPending:ft,saving:it,savingAuth:pt,sectionRefs:i,setAuthForm:$,setConfirmCleanupOpen:ct,setConfirmClearAllOpen:ut,setErrors:ee,setForm:q,setBillingForm:te,setSectionRef:n,t:s}}function Ps(){const{t:s}=E(),t=is(),o=Number(t.isConfigDirty)+Number(t.isAuthDirty)+Number(t.isBillingDirty),c=o>0,a=_t(({currentLocation:i,nextLocation:u})=>c&&i.pathname!==u.pathname);return m.useEffect(()=>{if(!c)return;const i=u=>{u.preventDefault(),u.returnValue=""};return window.addEventListener("beforeunload",i),()=>window.removeEventListener("beforeunload",i)},[c]),e.jsxs("div",{className:"flex flex-col gap-6",children:[e.jsx(Ht,{info:o>0?e.jsx("span",{className:"rounded-lg bg-warning-bg px-2.5 py-1 text-xs font-medium text-warning",children:s("settings.overview.unsavedCount",{count:o})}):null,status:t.protocolChangesPending?e.jsx("span",{className:"text-xs text-muted-foreground",children:s("settings.protocol.restartWarning")}):null,actions:null}),t.isLoading?e.jsx(Se,{label:s("common.loading")}):t.config?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-6 xl:grid-cols-[200px_minmax(0,1fr)]",children:[e.jsx(Wt,{activeSection:t.activeSection,onSelectSection:t.handleSectionClick}),e.jsxs("div",{className:"flex min-w-0 flex-col gap-6",children:[e.jsx(Xt,{defaultsSummary:t.defaultsSummary,errors:t.errors,form:t.form,onInputChange:t.handleInputChange,onSetForm:t.setForm,sectionRef:t.setSectionRef("section-basics")}),e.jsx(Zt,{errors:t.errors,form:t.form,onSetForm:t.setForm,protocolChangesPending:t.protocolChangesPending,sectionRef:t.setSectionRef("section-protocol")}),e.jsx(es,{authErrors:t.authErrors,authForm:t.authForm,authLoading:t.authQuery.isPending||!t.authSettings&&t.authQuery.isFetching,authSettings:t.authSettings,needsPassword:t.needsPassword,onSetAuthForm:t.setAuthForm,sectionRef:t.setSectionRef("section-security")}),e.jsx(ts,{errors:t.billingErrors,form:t.billingForm,onSetForm:t.setBillingForm,sectionRef:t.setSectionRef("section-billing")}),e.jsx(ss,{configPath:t.configPath,onCopyPath:()=>void t.handleCopyPath(),sectionRef:t.setSectionRef("section-config-file")}),e.jsx(as,{cleaning:t.cleaning,clearingAll:t.clearingAll,compacting:t.compacting,dbSizeDisplay:t.dbSizeDisplay,onCompact:t.handleCompact,onOpenCleanup:()=>t.setConfirmCleanupOpen(!0),onOpenClearAll:()=>t.setConfirmClearAllOpen(!0),sectionRef:t.setSectionRef("section-cleanup")})]})]}),e.jsx(ns,{dirtyCount:o,protocolChangesPending:t.protocolChangesPending,onReset:t.handleResetAll,onSave:()=>void t.handleSaveAll(),saving:t.saving||t.savingAuth})]}):e.jsx(F,{children:e.jsx(H,{className:"pt-6",children:e.jsx("p",{className:"text-sm font-medium text-destructive",children:s("settings.toast.missingConfig")})})}),e.jsx(xe,{open:t.confirmCleanupOpen,onOpenChange:i=>{!i&&!t.cleaning&&t.setConfirmCleanupOpen(!1)},title:s("settings.cleanup.confirmTitle"),description:s("settings.cleanup.confirmDescription"),confirmLabel:t.cleaning?s("common.actions.cleaning"):s("common.actions.cleanup"),cancelLabel:s("common.actions.cancel"),loading:t.cleaning,onConfirm:async()=>{await t.handleCleanupLogs(),t.setConfirmCleanupOpen(!1)}}),e.jsx(xe,{open:t.confirmClearAllOpen,onOpenChange:i=>{!i&&!t.clearingAll&&t.setConfirmClearAllOpen(!1)},title:s("settings.cleanup.clearAllTitle"),description:s("settings.cleanup.clearAllWarning"),confirmLabel:t.clearingAll?s("settings.cleanup.clearingAll"):s("settings.cleanup.clearAll"),cancelLabel:s("common.actions.cancel"),loading:t.clearingAll,onConfirm:async()=>{await t.handleClearAllLogs(),t.setConfirmClearAllOpen(!1)}}),e.jsx(xe,{open:a.state==="blocked",onOpenChange:i=>{!i&&a.state==="blocked"&&a.reset()},title:s("settings.unsaved.title"),description:s("settings.unsaved.body"),confirmLabel:s("settings.unsaved.confirm"),cancelLabel:s("common.actions.cancel"),onConfirm:()=>{a.state==="blocked"&&a.proceed()}})]})}export{Ps as default};
1
+ import{j as e,b8 as he,b3 as Tt,r as m,a$ as Ft,b1 as Ot,ay as Mt}from"./vendor-C-lQMZp3.js";import{C as xe}from"./ConfirmDialog-_CIYYtzo.js";import{P as Se}from"./PageState-Bbhr4fy6.js";import{P as Ht}from"./PageToolbar-GyUQBhmq.js";import{C as F,c as H,b as X,B as T,q as Y,r as G,e as Kt,d as qt,u as Bt,t as Ut}from"./app-DZpd2fu9.js";import{B as I}from"./badge-CWbm9P64.js";import{L as f,I as P}from"./label-09axTkPo.js";import{S as Z}from"./switch-C58zWdHT.js";import{S as je,a as Ne,b as Ce,c as we,d as z,D as Yt}from"./disclosure-W_XtxMJz.js";import{c as V}from"./global-BCYo_xAt.js";import{u as E}from"./i18n-ClvfZhYc.js";import{a as Vt}from"./query-1Ng1fzmE.js";import{u as W}from"./useAppMutation-CsoNTPQ7.js";import{g as st}from"./gateway-DxaHzVOF.js";import{c as It}from"./clipboard-DqvcglYs.js";import{c as Qt}from"./types-BT3gK5lJ.js";import{g as _t}from"./router-Bkbjq53m.js";import"./DialogShell-D1T4HXtd.js";import"./radix-DONH6gHT.js";const zt={pricesRequest(){return{url:"/api/billing/prices",method:"GET"}}},$t=[{value:"fatal",labelKey:"fatal"},{value:"error",labelKey:"error"},{value:"warn",labelKey:"warn"},{value:"info",labelKey:"info"},{value:"debug",labelKey:"debug"},{value:"trace",labelKey:"trace"}],Pe="7.2";function Jt(){return{key:"",currency:"CNY",input:"",output:"",cacheRead:"",cacheCreation:"",label:""}}function ge(s){const t=s.billing,o=(t==null?void 0:t.displayCurrency)==="USD"?"USD":"CNY",c=(t==null?void 0:t.rates)??{};let a=Pe;o==="CNY"&&typeof c.USD=="number"&&c.USD>0?a=String(c.USD):o==="USD"&&typeof c.CNY=="number"&&c.CNY>0&&(a=String(1/c.CNY));const i=Object.entries((t==null?void 0:t.modelPrices)??{}).map(([u,n])=>{var l;return{key:u,currency:((l=n.currency)==null?void 0:l.toUpperCase())==="USD"?"USD":"CNY",input:String(n.input??0),output:String(n.output??0),cacheRead:String(n.cacheRead??0),cacheCreation:String(n.cacheCreation??0),label:n.label??""}});return{displayCurrency:o,usdCnyRate:a,overrides:i.length>0?i:[Jt()]}}function at(s){return!!(s.key.trim()||s.input.trim()||s.output.trim()||s.cacheRead.trim()||s.cacheCreation.trim()||s.label.trim())}function Gt(s){const t=Number(s.usdCnyRate),o=s.displayCurrency==="CNY"?{USD:Number.isFinite(t)&&t>0?t:Number(Pe)}:{CNY:Number.isFinite(t)&&t>0?1/t:1/Number(Pe)},c={};for(const a of s.overrides){if(!at(a))continue;const i=a.key.trim();i&&(c[i]={currency:a.currency,input:Number(a.input)||0,output:Number(a.output)||0,cacheRead:Number(a.cacheRead)||0,cacheCreation:Number(a.cacheCreation)||0,...a.label.trim()?{label:a.label.trim()}:{}})}return{displayCurrency:s.displayCurrency,rates:o,...Object.keys(c).length>0?{modelPrices:c}:{}}}const ke=[{id:"section-basics",labelKey:"settings.sections.basics"},{id:"section-protocol",labelKey:"settings.sections.protocol"},{id:"section-security",labelKey:"settings.sections.security"},{id:"section-billing",labelKey:"settings.sections.billing"},{id:"section-config-file",labelKey:"settings.sections.configFile"},{id:"section-cleanup",labelKey:"settings.sections.cleanup"}];function be(s){var c,a,i,u,n,l,g,O,L;const t=s.storePayloads,o=w=>typeof w=="boolean"?w:typeof t=="boolean"?t:!0;return{logRetentionDays:String(s.logRetentionDays??30),logExportTimeoutSeconds:String(s.logExportTimeoutSeconds??60),storeRequestPayloads:o(s.storeRequestPayloads),storeResponsePayloads:o(s.storeResponsePayloads),logLevel:s.logLevel??"info",bodyLimitMb:(()=>{const w=s.bodyLimit;return typeof w=="number"&&Number.isFinite(w)&&w>0?String(Math.max(1,Math.round(w/(1024*1024)))):"10"})(),enableRoutingFallback:s.enableRoutingFallback===!0,httpEnabled:((c=s.http)==null?void 0:c.enabled)!==!1,httpPort:String(((a=s.http)==null?void 0:a.port)??s.port??4100),httpHost:((i=s.http)==null?void 0:i.host)??s.host??"127.0.0.1",httpsEnabled:((u=s.https)==null?void 0:u.enabled)===!0,httpsPort:String(((n=s.https)==null?void 0:n.port)??4443),httpsHost:((l=s.https)==null?void 0:l.host)??s.host??"127.0.0.1",httpsKeyPath:((g=s.https)==null?void 0:g.keyPath)??"",httpsCertPath:((O=s.https)==null?void 0:O.certPath)??"",httpsCaPath:((L=s.https)==null?void 0:L.caPath)??""}}function fe(s){return{enabled:s.enabled,username:s.username??"",password:"",confirmPassword:""}}function Wt({activeSection:s,onSelectSection:t}){const{t:o}=E();return e.jsxs(e.Fragment,{children:[e.jsx("nav",{className:"hidden xl:block",children:e.jsxs(F,{className:"sticky top-20 p-3.5",children:[e.jsx("p",{className:"mb-2.5 px-2 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground",children:o("settings.sections.jump")}),e.jsx("div",{className:"space-y-1.5",children:ke.map((c,a)=>e.jsxs("button",{type:"button",onClick:()=>t(c.id),className:V("flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-left text-sm font-semibold transition-all duration-200",s===c.id?"bg-secondary text-foreground":"text-muted-foreground hover:text-foreground"),children:[e.jsx("span",{className:V("flex h-7 w-7 items-center justify-center rounded-lg text-[11px] font-semibold",s===c.id?"bg-foreground text-background":"bg-secondary text-muted-foreground"),children:a+1}),e.jsx("span",{children:o(c.labelKey)})]},c.id))})]})}),e.jsx("div",{className:"min-w-0 xl:hidden",children:e.jsx("div",{className:"overflow-x-auto pb-1",children:e.jsx("div",{className:"flex w-max gap-2 px-1",children:ke.map(c=>e.jsx("button",{type:"button",onClick:()=>t(c.id),className:V("rounded-lg px-4 py-2 text-xs font-semibold transition-all duration-150",s===c.id?"bg-secondary text-foreground font-medium":"text-muted-foreground hover:text-foreground hover:bg-secondary/50"),children:o(c.labelKey)},c.id))})})})]})}function Xt({defaultsSummary:s,errors:t,form:o,onInputChange:c,onSetForm:a,sectionRef:i}){const{t:u}=E();return e.jsx(F,{id:"section-basics",ref:i,className:"bg-card shadow-[var(--surface-shadow)]",children:e.jsxs(H,{className:"pt-6",children:[e.jsx("h3",{className:"mb-4 text-sm font-semibold",children:u("settings.sections.basics")}),e.jsxs("div",{className:"grid gap-5 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:u("settings.fields.port")}),e.jsx(P,{type:"number",min:1,max:65535,value:o.httpPort,"data-visual-volatile":"text",onChange:n=>a(l=>({...l,httpPort:n.target.value})),"aria-invalid":!!t.httpPort}),t.httpPort?e.jsx("p",{className:"text-xs text-destructive",children:t.httpPort}):null]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:u("settings.fields.host")}),e.jsx(P,{value:o.httpHost,onChange:n=>a(l=>({...l,httpHost:n.target.value})),placeholder:u("settings.fields.hostPlaceholder")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:u("settings.fields.retention")}),e.jsx(P,{type:"number",min:1,max:365,value:o.logRetentionDays,onChange:n=>c("logRetentionDays")(n.target.value),"aria-invalid":!!t.logRetentionDays}),t.logRetentionDays?e.jsx("p",{className:"text-xs text-destructive",children:t.logRetentionDays}):null]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:u("settings.fields.logExportTimeout")}),e.jsx(P,{type:"number",min:5,max:600,value:o.logExportTimeoutSeconds,onChange:n=>c("logExportTimeoutSeconds")(n.target.value),"aria-invalid":!!t.logExportTimeoutSeconds}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u("settings.fields.logExportTimeoutHint")}),t.logExportTimeoutSeconds?e.jsx("p",{className:"text-xs text-destructive",children:t.logExportTimeoutSeconds}):null]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:u("settings.fields.bodyLimit")}),e.jsx(P,{type:"number",min:1,max:2048,value:o.bodyLimitMb,onChange:n=>c("bodyLimitMb")(n.target.value),"aria-invalid":!!t.bodyLimitMb}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u("settings.fields.bodyLimitHint")}),t.bodyLimitMb?e.jsx("p",{className:"text-xs text-destructive",children:t.bodyLimitMb}):null]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:u("settings.fields.logLevel")}),e.jsxs(je,{value:o.logLevel,onValueChange:n=>a(l=>({...l,logLevel:n})),children:[e.jsx(Ne,{children:e.jsx(Ce,{})}),e.jsx(we,{children:$t.map(n=>e.jsx(z,{value:n.value,children:u(`settings.fields.logLevelOption.${n.labelKey}`)},n.value))})]})]}),e.jsxs("div",{className:"grid gap-4 md:col-span-2 sm:grid-cols-2",children:[e.jsx(ye,{label:u("settings.fields.storeRequestPayloads"),hint:u("settings.fields.storeRequestPayloadsHint"),checked:o.storeRequestPayloads,onCheckedChange:n=>a(l=>({...l,storeRequestPayloads:n}))}),e.jsx(ye,{label:u("settings.fields.storeResponsePayloads"),hint:u("settings.fields.storeResponsePayloadsHint"),checked:o.storeResponsePayloads,onCheckedChange:n=>a(l=>({...l,storeResponsePayloads:n}))}),e.jsx(ye,{label:u("settings.fields.enableRoutingFallback"),hint:u("settings.fields.enableRoutingFallbackHint"),checked:o.enableRoutingFallback,onCheckedChange:n=>a(l=>({...l,enableRoutingFallback:n}))})]}),e.jsxs("div",{className:"rounded-xl bg-secondary px-4 py-5 md:col-span-2",children:[e.jsx(f,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:u("settings.fields.defaults")}),e.jsx("p",{className:"mt-2 text-sm",children:s??u("settings.defaults.none")})]})]})]})})}function Zt({errors:s,form:t,onSetForm:o,protocolChangesPending:c,sectionRef:a}){const{t:i}=E();return e.jsx(F,{id:"section-protocol",ref:a,className:"bg-card shadow-[var(--surface-shadow)]",children:e.jsxs(H,{className:"space-y-6 pt-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:i("settings.sections.protocol")}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:i("settings.protocol.description")})]}),c?e.jsx("div",{className:"rounded-xl bg-warning-bg ring-1 ring-warning/30 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(he,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-warning"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:i("settings.protocol.restartWarning")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i("settings.protocol.restartHint")}),e.jsx("code",{className:"block rounded-lg border border-border bg-secondary px-3 py-2 text-xs font-mono text-foreground",children:"cc-gw restart --daemon"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i("settings.protocol.restartTip")})]})]})}):null,s.protocol?e.jsxs("div",{className:"rounded-xl bg-destructive/10 ring-1 ring-destructive/30 p-4 text-sm text-destructive",children:[e.jsx(he,{className:"mr-2 inline h-4 w-4"}),s.protocol]}):null,e.jsxs("div",{className:"rounded-xl bg-secondary p-5",children:[e.jsxs("div",{className:"mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(f,{className:"text-sm font-medium text-foreground",children:i("settings.protocol.http.enable")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i("settings.protocol.http.hint")})]}),e.jsx(Z,{checked:t.httpEnabled,onCheckedChange:u=>o(n=>({...n,httpEnabled:u}))})]}),t.httpEnabled?e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:i("settings.protocol.http.listener",{address:`${t.httpHost||"127.0.0.1"}:${t.httpPort||"4100"}`})})}):null]}),e.jsxs("div",{className:"rounded-xl bg-secondary p-5",children:[e.jsxs("div",{className:"mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(f,{className:"text-sm font-medium text-foreground",children:i("settings.protocol.https.enable")}),e.jsx(Tt,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i("settings.protocol.https.hint")})]}),e.jsx(Z,{checked:t.httpsEnabled,onCheckedChange:u=>o(n=>({...n,httpsEnabled:u}))})]}),t.httpsEnabled?e.jsxs("div",{className:"mt-4 space-y-4 border-t border-border pt-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:i("settings.protocol.https.port")}),e.jsx(P,{type:"number",min:1,max:65535,value:t.httpsPort,onChange:u=>o(n=>({...n,httpsPort:u.target.value})),"aria-invalid":!!s.httpsPort}),s.httpsPort?e.jsx("p",{className:"text-xs text-destructive",children:s.httpsPort}):null]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:i("settings.protocol.https.host")}),e.jsx(P,{value:t.httpsHost,onChange:u=>o(n=>({...n,httpsHost:u.target.value})),placeholder:"127.0.0.1"})]})]}),e.jsx(ve,{label:i("settings.protocol.https.keyPath"),value:t.httpsKeyPath,onChange:u=>o(n=>({...n,httpsKeyPath:u})),placeholder:"~/.cc-gw/certs/key.pem"}),e.jsx(ve,{label:i("settings.protocol.https.certPath"),value:t.httpsCertPath,onChange:u=>o(n=>({...n,httpsCertPath:u})),placeholder:"~/.cc-gw/certs/cert.pem"}),e.jsx(ve,{label:i("settings.protocol.https.caPath"),value:t.httpsCaPath,onChange:u=>o(n=>({...n,httpsCaPath:u})),placeholder:"留空则不使用"}),e.jsx("div",{className:"rounded-xl bg-warning-bg ring-1 ring-warning/30 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(he,{className:"mt-0.5 h-5 w-5 flex-shrink-0 text-warning"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx("p",{className:"text-sm font-medium text-warning",children:i("settings.protocol.https.warning")}),e.jsx("p",{className:"text-xs leading-relaxed text-warning",children:i("settings.protocol.https.tip")})]})]})})]}):null]})]})})}function es({authErrors:s,authForm:t,authLoading:o,authSettings:c,needsPassword:a,onSetAuthForm:i,sectionRef:u}){const{t:n}=E();return e.jsx(F,{id:"section-security",ref:u,className:"bg-card shadow-[var(--surface-shadow)]",children:e.jsxs(H,{className:"space-y-5 pt-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:n("settings.sections.security")}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:n("settings.auth.description")})]}),o&&!c?e.jsx(Se,{compact:!0,label:n("common.loading")}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-4 rounded-xl bg-secondary p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{className:"text-sm font-medium",children:n("settings.auth.enable")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:n("settings.auth.enableHint")}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-xs font-medium text-muted-foreground",children:[e.jsx("span",{className:"rounded-lg bg-secondary px-3 py-1 text-[11px] tracking-[0.08em]",children:"/ui"}),e.jsx("span",{className:"rounded-lg bg-secondary px-3 py-1 text-[11px] tracking-[0.08em]",children:"/api/*"}),e.jsx("span",{className:"rounded-lg bg-secondary px-3 py-1 text-[11px] tracking-[0.08em]",children:"Cookie Session"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 self-start sm:self-auto",children:[e.jsx(I,{variant:t.enabled?"success":"secondary",children:t.enabled?n("settings.auth.statusEnabled"):n("settings.auth.statusDisabled")}),e.jsx(Z,{checked:t.enabled,onCheckedChange:l=>i(g=>({...g,enabled:l}))})]})]}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,0.85fr)]",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(f,{children:n("settings.auth.username")}),e.jsx(P,{value:t.username,onChange:l=>i(g=>({...g,username:l.target.value})),placeholder:n("settings.auth.usernamePlaceholder")}),s.username?e.jsx("p",{className:"text-xs text-destructive",children:s.username}):null]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:n("settings.auth.password")}),e.jsx(P,{type:"password",value:t.password,disabled:!t.enabled,onChange:l=>i(g=>({...g,password:l.target.value})),placeholder:n("settings.auth.passwordPlaceholder")}),s.password?e.jsx("p",{className:"text-xs text-destructive",children:s.password}):e.jsx("p",{className:"text-xs text-muted-foreground",children:n(a?"settings.auth.passwordHintRequired":"settings.auth.passwordHintOptional")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:n("settings.auth.confirmPassword")}),e.jsx(P,{type:"password",value:t.confirmPassword,disabled:!t.enabled,onChange:l=>i(g=>({...g,confirmPassword:l.target.value})),placeholder:n("settings.auth.confirmPasswordPlaceholder")}),s.confirmPassword?e.jsx("p",{className:"text-xs text-destructive",children:s.confirmPassword}):null]})]}),e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"rounded-xl bg-secondary p-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.34em] text-muted-foreground",children:n("settings.auth.status")}),e.jsx("p",{className:"mt-2 text-base font-semibold",children:c!=null&&c.enabled?n("settings.auth.statusEnabled"):n("settings.auth.statusDisabled")}),c!=null&&c.username?e.jsxs("div",{className:"mt-3 rounded-lg bg-background px-3 py-2 text-xs font-medium text-foreground",children:[n("settings.auth.username"),": ",c.username]}):null]}),e.jsx("div",{className:"rounded-xl bg-secondary px-4 py-3 text-xs text-muted-foreground",children:n(a?"settings.auth.passwordHintRequired":"settings.auth.passwordHintOptional")})]})]})]})]})})}function ts({errors:s,form:t,onSetForm:o,sectionRef:c}){var K;const{t:a}=E(),[i,u]=m.useState(""),n=X(Y.billing.prices(),zt.pricesRequest()),l=(h,d)=>{o(y=>({...y,overrides:y.overrides.map((k,R)=>R===h?{...k,...d}:k)}))},g=h=>{o(d=>({...d,overrides:d.overrides.filter((y,k)=>k!==h)}))},O=()=>{o(h=>({...h,overrides:[...h.overrides,{key:"",currency:"CNY",input:"",output:"",cacheRead:"",cacheCreation:"",label:""}]}))},L=m.useMemo(()=>{var y;const h=((y=n.data)==null?void 0:y.entries)??[],d=i.trim().toLowerCase();return d?h.filter(k=>k.key.toLowerCase().includes(d)):h},[n.data,i]),w=h=>h.toLocaleString(void 0,{maximumFractionDigits:4});return e.jsx(F,{id:"section-billing",ref:c,className:"bg-card shadow-[var(--surface-shadow)]",children:e.jsxs(H,{className:"space-y-6 pt-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:a("settings.sections.billing")}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:a("billing.description")})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:a("billing.displayCurrency")}),e.jsxs(je,{value:t.displayCurrency,onValueChange:h=>o(d=>({...d,displayCurrency:h==="USD"?"USD":"CNY"})),children:[e.jsx(Ne,{"aria-label":a("billing.displayCurrency"),children:e.jsx(Ce,{})}),e.jsxs(we,{children:[e.jsx(z,{value:"CNY",children:"CNY(¥)"}),e.jsx(z,{value:"USD",children:"USD($)"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:a("billing.displayCurrencyHint")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:a("billing.rateLabel")}),e.jsx(P,{type:"number",min:"0",step:"0.0001",value:t.usdCnyRate,onChange:h=>o(d=>({...d,usdCnyRate:h.target.value})),"aria-invalid":!!s.usdCnyRate}),s.usdCnyRate?e.jsx("p",{className:"text-xs text-destructive",children:s.usdCnyRate}):e.jsx("p",{className:"text-xs text-muted-foreground",children:a("billing.rateHint",{value:(1/(Number(t.usdCnyRate)||1)).toFixed(4)})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:a("billing.overrides.title")}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:a("billing.overrides.description")})]}),e.jsxs(T,{type:"button",variant:"outline",size:"sm",onClick:O,children:[e.jsx(Ft,{className:"mr-1.5 h-3.5 w-3.5","aria-hidden":"true"}),a("billing.overrides.add")]})]}),e.jsx("div",{className:"space-y-3",children:t.overrides.map((h,d)=>{var k;const y=(k=s.overrides)==null?void 0:k[d];return e.jsxs("div",{"data-testid":`billing-override-row-${d}`,className:"grid gap-3 rounded-xl bg-secondary/60 p-3 lg:grid-cols-[minmax(0,1.4fr)_auto_repeat(4,minmax(0,0.8fr))_auto] lg:items-end",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(f,{className:"text-xs text-muted-foreground",children:a("billing.overrides.key")}),e.jsx(P,{value:h.key,onChange:R=>l(d,{key:R.target.value}),placeholder:"claude-sonnet-4-5 / acme:internal-model","aria-invalid":!!(y!=null&&y.key)}),y!=null&&y.key?e.jsx("p",{className:"text-xs text-destructive",children:y.key}):e.jsx("p",{className:"text-xs text-muted-foreground/70",children:a("billing.overrides.keyHint")})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(f,{className:"text-xs text-muted-foreground",children:a("billing.overrides.currency")}),e.jsxs(je,{value:h.currency,onValueChange:R=>l(d,{currency:R}),children:[e.jsx(Ne,{className:"w-[92px]","aria-label":a("billing.overrides.currency"),children:e.jsx(Ce,{})}),e.jsxs(we,{children:[e.jsx(z,{value:"CNY",children:"CNY"}),e.jsx(z,{value:"USD",children:"USD"})]})]})]}),[["input","priceInput"],["output","priceOutput"],["cacheRead","priceCacheRead"],["cacheCreation","priceCacheCreation"]].map(([R,p])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(f,{className:"text-xs text-muted-foreground",children:a(`billing.overrides.${p}`)}),e.jsx(P,{type:"number",min:"0",step:"0.0001",value:h[R],onChange:q=>l(d,{[R]:q.target.value})})]},R)),e.jsx(T,{type:"button",variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>g(d),disabled:t.overrides.length===1,"aria-label":a("billing.overrides.remove"),children:e.jsx(Ot,{className:"h-4 w-4","aria-hidden":"true"})}),y!=null&&y.prices?e.jsx("p",{className:"text-xs text-destructive lg:col-span-7",children:y.prices}):null]},d)})})]}),e.jsx(Yt,{summary:e.jsx("span",{className:"text-sm font-medium",children:a("billing.builtin.title")}),badge:e.jsx(I,{variant:"secondary",className:"text-[10px]",children:L.length}),contentClassName:"border-t border-border p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:a("billing.builtin.description")}),e.jsx(P,{value:i,onChange:h=>u(h.target.value),placeholder:a("billing.builtin.filterPlaceholder"),className:"max-w-xs"}),n.isPending?e.jsx(Se,{compact:!0,label:a("common.loadingShort")}):n.isError?e.jsx("p",{className:"text-xs text-destructive",children:a("billing.builtin.loadError",{message:((K=n.error)==null?void 0:K.message)??""})}):e.jsx("div",{className:"max-h-[320px] overflow-auto rounded-lg border border-border bg-card",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"sticky top-0 bg-secondary text-left uppercase tracking-wider text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2 font-semibold",children:a("billing.builtin.columns.key")}),e.jsx("th",{className:"px-3 py-2 font-semibold",children:a("billing.builtin.columns.source")}),e.jsx("th",{className:"px-3 py-2 text-right font-semibold",children:a("billing.builtin.columns.input")}),e.jsx("th",{className:"px-3 py-2 text-right font-semibold",children:a("billing.builtin.columns.output")}),e.jsx("th",{className:"px-3 py-2 text-right font-semibold",children:a("billing.builtin.columns.cacheRead")}),e.jsx("th",{className:"px-3 py-2 text-right font-semibold",children:a("billing.builtin.columns.cacheCreation")})]})}),e.jsxs("tbody",{className:"divide-y divide-border/60",children:[L.map(h=>e.jsxs("tr",{className:"tabular-nums",children:[e.jsx("td",{className:"px-3 py-1.5 font-mono",children:h.key}),e.jsx("td",{className:"px-3 py-1.5",children:e.jsx(I,{variant:h.source==="override"?"default":"secondary",className:"text-[10px]",children:h.source})}),e.jsx("td",{className:"px-3 py-1.5 text-right",children:w(h.input)}),e.jsx("td",{className:"px-3 py-1.5 text-right",children:w(h.output)}),e.jsx("td",{className:"px-3 py-1.5 text-right",children:w(h.cacheRead)}),e.jsx("td",{className:"px-3 py-1.5 text-right",children:w(h.cacheCreation)})]},`${h.source}:${h.key}`)),L.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-3 py-4 text-center text-muted-foreground",children:a("billing.builtin.empty")})}):null]})]})}),e.jsx("p",{className:"text-xs text-muted-foreground/70",children:a("billing.builtin.footnote")})]})}),e.jsx("div",{className:"rounded-xl bg-secondary px-4 py-3 text-xs text-muted-foreground",children:a("billing.estimateNote")})]})})}function ss({configPath:s,onCopyPath:t,sectionRef:o}){const{t:c}=E();return e.jsx(F,{id:"section-config-file",ref:o,className:"bg-card shadow-[var(--surface-shadow)]",children:e.jsxs(H,{className:"space-y-3 pt-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:c("settings.sections.configFile")}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:c("settings.file.description")})]}),e.jsxs(T,{variant:"outline",size:"sm",onClick:t,className:"w-full sm:w-auto",children:[e.jsx(Mt,{className:"mr-2 h-4 w-4"}),c("common.actions.copy")]})]}),e.jsx("code",{"data-visual-volatile":"true",className:"block break-all rounded-lg bg-secondary px-4 py-3 text-xs font-mono text-muted-foreground",children:s||c("settings.file.unknown")}),e.jsx("div",{className:"rounded-lg bg-secondary px-4 py-3 text-xs text-muted-foreground",children:c("help.note")})]})})}function as({cleaning:s,clearingAll:t,compacting:o,dbSizeDisplay:c,onCompact:a,onOpenCleanup:i,onOpenClearAll:u,sectionRef:n}){const{t:l}=E();return e.jsx(F,{id:"section-cleanup",ref:n,className:"bg-card shadow-[var(--surface-shadow)]",children:e.jsxs(H,{className:"space-y-4 pt-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:l("settings.sections.cleanup")}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:l("settings.cleanup.description")})]}),e.jsxs("div",{className:"rounded-lg bg-secondary px-3 py-1.5 text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:[l("settings.cleanup.dbSizeLabel"),": "]}),e.jsx("span",{className:"font-semibold tabular-nums text-foreground",children:c})]})]}),e.jsx("div",{className:"rounded-lg bg-secondary px-4 py-3 text-xs text-muted-foreground",children:l("settings.cleanup.confirmCleanup")}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsx("div",{className:"rounded-xl border border-warning/30 bg-warning-bg p-5",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{variant:"warning",children:l("settings.cleanup.softLabel")}),e.jsx("p",{className:"text-sm font-medium",children:l("settings.cleanup.softTitle")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l("settings.cleanup.softDescription")}),e.jsx(T,{variant:"outline",onClick:i,disabled:s,className:"w-full sm:w-auto",children:l(s?"common.actions.cleaning":"common.actions.cleanup")})]})}),e.jsx("div",{className:"rounded-xl border border-destructive/30 bg-destructive/10 p-5 text-destructive",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(I,{variant:"outline",className:"border-destructive/40 bg-destructive/10 text-destructive",children:l("settings.cleanup.hardLabel")}),e.jsx("p",{className:"text-sm font-medium",children:l("settings.cleanup.hardTitle")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l("settings.cleanup.clearAllWarning")}),e.jsx(T,{variant:"destructive",onClick:u,disabled:t,className:"w-full sm:w-auto",children:l(t?"settings.cleanup.clearingAll":"settings.cleanup.clearAll")})]})})]}),e.jsx("div",{className:"rounded-xl border border-border bg-secondary/40 p-5",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium",children:l("settings.cleanup.compactTitle")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l("settings.cleanup.compactDescription")})]}),e.jsx(T,{variant:"outline",onClick:a,disabled:o,className:"w-full sm:w-auto",children:l(o?"common.actions.compacting":"common.actions.compact")})]})})]})})}function ns({dirtyCount:s,protocolChangesPending:t,onReset:o,onSave:c,saving:a}){const{t:i}=E();return s===0?null:e.jsxs("div",{className:"sticky bottom-4 z-20 flex flex-col gap-3 rounded-xl bg-card border border-border px-6 py-5 shadow-[var(--surface-shadow-lg)] md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(I,{variant:"secondary",children:i("settings.overview.unsavedCount",{count:s})}),e.jsx("p",{className:"text-sm text-muted-foreground",children:i(t?"settings.toast.protocolRestartRequired":"modelManagement.actions.footerDirtyHint")})]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2 lg:flex lg:flex-wrap lg:items-center",children:[e.jsx(T,{variant:"outline",onClick:o,disabled:a,className:"w-full lg:w-auto",children:i("common.actions.reset")}),e.jsx(T,{onClick:c,disabled:a,className:"w-full lg:w-auto",children:i(a?"common.actions.saving":"common.actions.save")})]})]})}function ye({checked:s,className:t,hint:o,hintClassName:c,label:a,labelClassName:i,onCheckedChange:u}){return e.jsxs("div",{className:V("flex flex-col gap-3 rounded-xl bg-secondary p-4 sm:flex-row sm:items-center sm:justify-between",t),children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(f,{className:V("text-sm font-semibold text-foreground",i),children:a}),e.jsx("p",{className:V("text-xs text-muted-foreground",c),children:o})]}),e.jsx(Z,{checked:s,onCheckedChange:u,className:"self-start sm:self-auto"})]})}function ve({label:s,onChange:t,placeholder:o,value:c}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(f,{children:s}),e.jsx(P,{value:c,onChange:a=>t(a.target.value),placeholder:o,className:"font-mono text-xs"})]})}const _={authStatusRequest(){return{url:"/api/auth/web",method:"GET"}},saveWebAuth:async s=>Kt(qt.post("/api/auth/web",s)),cleanupLogs:async()=>G({url:"/api/logs/cleanup",method:"POST"}),clearLogs:async()=>G({url:"/api/logs/clear",method:"POST"}),dbInfo:async()=>G({url:"/api/db/info",method:"GET"}),compactDb:async()=>G({url:"/api/db/compact",method:"POST"})};function is(){const{t:s}=E(),{pushToast:t}=Bt(),o=Vt(),[c,a]=m.useState(ke[0].id),i=m.useRef(new Map),u=m.useCallback(r=>{const x=i.current.get(r);x&&x.scrollIntoView({behavior:"smooth",block:"start"})},[]),n=m.useCallback(r=>x=>{x?i.current.set(r,x):i.current.delete(r)},[]),l=X(Y.config.info(),st.configInfoRequest()),g=X(Y.auth.web(),_.authStatusRequest()),O=W({mutationFn:_.saveWebAuth,successToast:()=>({title:s("settings.auth.toast.success")}),errorToast:r=>({title:s("settings.auth.toast.failure",{message:r.message})}),invalidateKeys:[Y.auth.web()]}),L=W({mutationFn:_.cleanupLogs,successToast:r=>({title:r.deleted>0?s("settings.toast.cleanupSuccess",{count:r.deleted}):s("settings.toast.cleanupNone")}),errorToast:r=>({title:s("settings.toast.cleanupFailure",{message:r.message})}),invalidateKeys:[["logs"],["dashboard"],["db"]]}),w=W({mutationFn:_.clearLogs,successToast:r=>({title:s("settings.toast.clearAllSuccess",{logs:r.deleted,metrics:r.metricsCleared})}),errorToast:r=>({title:s("settings.toast.clearAllFailure",{message:r.message})}),invalidateKeys:[["logs"],["stats"],["dashboard"],["db"]]}),K=X(Y.db.info(),{url:"/api/db/info",method:"GET"}),h=W({mutationFn:_.compactDb,successToast:()=>({title:s("settings.toast.compactSuccess.title"),description:s("settings.toast.compactSuccess.desc")}),errorToast:r=>({title:s("settings.toast.compactFailure",{message:r.message})}),invalidateKeys:[Y.db.info(),["dashboard"]]}),[d,y]=m.useState(null),[k,R]=m.useState(""),[p,q]=m.useState({logRetentionDays:"",logExportTimeoutSeconds:"60",storeRequestPayloads:!0,storeResponsePayloads:!0,logLevel:"info",bodyLimitMb:"10",enableRoutingFallback:!1,httpEnabled:!0,httpPort:"4100",httpHost:"127.0.0.1",httpsEnabled:!1,httpsPort:"4443",httpsHost:"127.0.0.1",httpsKeyPath:"",httpsCertPath:"",httpsCaPath:""}),[nt,ee]=m.useState({}),[it,Re]=m.useState(!1),[lt,Ee]=m.useState(!1),[rt,Le]=m.useState(!1),[ot,ct]=m.useState(!1),[dt,ut]=m.useState(!1),[N,Ae]=m.useState(null),[b,$]=m.useState({enabled:!1,username:"",password:"",confirmPassword:""}),[mt,J]=m.useState({}),[pt,De]=m.useState(!1),[D,te]=m.useState({displayCurrency:"CNY",usdCnyRate:"7.2",overrides:[{key:"",currency:"CNY",input:"",output:"",cacheRead:"",cacheCreation:"",label:""}]}),[ht,se]=m.useState({}),xt=m.useMemo(()=>{if(!(d!=null&&d.defaults))return null;const r=[];return d.defaults.completion&&r.push(s("settings.defaults.completion",{model:d.defaults.completion})),d.defaults.reasoning&&r.push(s("settings.defaults.reasoning",{model:d.defaults.reasoning})),d.defaults.background&&r.push(s("settings.defaults.background",{model:d.defaults.background})),r.length>0?r.join(" | "):s("settings.defaults.none")},[d,s]),gt=m.useMemo(()=>p.httpEnabled&&p.httpsEnabled?s("settings.overview.values.httpAndHttps"):p.httpsEnabled?s("settings.overview.values.httpsOnly"):s("settings.overview.values.httpOnly"),[p.httpEnabled,p.httpsEnabled,s]),bt=m.useMemo(()=>b.enabled?N!=null&&N.hasPassword?b.username.trim()!==(N.username??""):!0:!1,[b.enabled,b.username,N]),B=m.useMemo(()=>d?be(d):null,[d]),ae=m.useMemo(()=>B?JSON.stringify(p)!==JSON.stringify(B):!1,[p,B]),ne=m.useMemo(()=>N?fe(N):null,[N]),ie=m.useMemo(()=>ne?JSON.stringify(b)!==JSON.stringify(ne):!1,[b,ne]),le=m.useMemo(()=>d?ge(d):null,[d]),U=m.useMemo(()=>le?JSON.stringify(D)!==JSON.stringify(le):!1,[D,le]),ft=m.useMemo(()=>B?["httpEnabled","httpPort","httpHost","httpsEnabled","httpsPort","httpsHost","httpsKeyPath","httpsCertPath","httpsCaPath"].some(x=>p[x]!==B[x]):!1,[p,B]);m.useEffect(()=>{l.data&&(y(l.data.config),R(l.data.path),q(be(l.data.config)),te(ge(l.data.config)),se({}))},[l.data]),m.useEffect(()=>{g.data&&(Ae(g.data),$(fe(g.data)),J({}))},[g.data]),m.useEffect(()=>{!l.isError||!l.error||t({title:s("settings.toast.loadFailure",{message:l.error.message}),variant:"error"})},[l.error,l.isError,t,s]),m.useEffect(()=>{!g.isError||!g.error||t({title:s("settings.toast.authLoadFailure",{message:g.error.message}),variant:"error"})},[g.error,g.isError,t,s]);const yt=m.useCallback(r=>x=>{q(C=>({...C,[r]:x}))},[]),Te=m.useCallback(()=>{const r={};!p.httpEnabled&&!p.httpsEnabled&&(r.protocol=s("settings.validation.protocolRequired"));const x=Number(p.httpPort);if((!Number.isFinite(x)||x<1||x>65535)&&(r.httpPort=s("settings.validation.httpPort")),p.httpsEnabled){const M=Number(p.httpsPort);(!Number.isFinite(M)||M<1||M>65535)&&(r.httpsPort=s("settings.validation.httpsPort")),(!p.httpsKeyPath||!p.httpsCertPath)&&(r.protocol=s("settings.validation.httpsCertificate"))}const C=Number(p.logRetentionDays);(!Number.isFinite(C)||C<1||C>365)&&(r.logRetentionDays=s("settings.validation.retention"));const v=Number(p.logExportTimeoutSeconds);(!Number.isFinite(v)||v<5||v>600)&&(r.logExportTimeoutSeconds=s("settings.validation.logExportTimeout"));const S=Number(p.bodyLimitMb);return(!Number.isFinite(S)||S<1||S>2048)&&(r.bodyLimitMb=s("settings.validation.bodyLimit")),ee(r),Object.keys(r).length===0},[p,s]),Fe=m.useCallback(()=>{const r={},x=b.username.trim(),C=N?x!==(N.username??""):!0,v=b.enabled&&(!(N!=null&&N.hasPassword)||C);return b.enabled&&!x&&(r.username=s("settings.auth.validation.username")),b.password&&b.password.length<6&&(r.password=s("settings.auth.validation.minLength")),v&&!b.password&&(r.password=s("settings.auth.validation.passwordRequired")),(b.password||b.confirmPassword)&&b.password!==b.confirmPassword&&(r.confirmPassword=s("settings.auth.validation.confirmMismatch")),J(r),Object.keys(r).length===0},[b,N,s]),Oe=m.useCallback(()=>{const r={},x=Number(D.usdCnyRate);(!Number.isFinite(x)||x<=0||x>1e4)&&(r.usdCnyRate=s("billing.validation.rate")),r.overrides=D.overrides.map(v=>{if(!at(v))return;const S={};if(!v.key.trim())S.key=s("billing.validation.keyRequired");else{const A=v.key.trim(),Q=A.indexOf(":");(Q===0||Q===A.length-1)&&(S.key=s("billing.validation.keyFormat"))}return[v.input,v.output,v.cacheRead,v.cacheCreation].some(A=>A.trim()!==""&&(!Number.isFinite(Number(A))||Number(A)<0))&&(S.prices=s("billing.validation.prices")),Object.keys(S).length>0?S:void 0});const C=r.overrides.some(Boolean);return se(r),!r.usdCnyRate&&!C},[D,s]),re=m.useCallback(async()=>{var r,x,C,v,S,M,A,Q,Me,He,Ke,qe,Be,Ue,Ye,Ve,Ie,Qe,_e,ze,$e,Je,Ge,We,Xe,Ze;if(!d){t({title:s("settings.toast.loadFailure",{message:s("settings.toast.missingConfig")}),variant:"error"});return}if(Te()&&Oe()){Re(!0);try{const me=Number(p.logRetentionDays),kt=Number(p.logExportTimeoutSeconds),St=Number(p.bodyLimitMb),j={...d,http:{enabled:p.httpEnabled,port:Number(p.httpPort),host:p.httpHost.trim()||"127.0.0.1"},https:{enabled:p.httpsEnabled,port:Number(p.httpsPort),host:p.httpsHost.trim()||"127.0.0.1",keyPath:p.httpsKeyPath.trim(),certPath:p.httpsCertPath.trim(),caPath:p.httpsCaPath.trim()||void 0},port:Number(p.httpPort),host:p.httpHost.trim()||void 0,logRetentionDays:me,logExportTimeoutSeconds:Math.min(Math.max(Math.round(kt),5),600),storeRequestPayloads:p.storeRequestPayloads,storeResponsePayloads:p.storeResponsePayloads,logLevel:p.logLevel,bodyLimit:Math.max(1,Math.floor(St*1024*1024)),enableRoutingFallback:p.enableRoutingFallback,...U?{billing:Gt(D)}:{}};delete j.requestLogging,delete j.responseLogging;const et={...j};delete et.webAuth,await st.saveConfig(et),y({...j,webAuth:d.webAuth});const tt=pe=>(pe==null?void 0:pe.trim())||void 0,Rt=d.port??((r=d.http)==null?void 0:r.port)??4100,Et=j.port??((x=j.http)==null?void 0:x.port)??4100,Lt=((C=d.host)==null?void 0:C.trim())||((S=(v=d.http)==null?void 0:v.host)==null?void 0:S.trim())||"127.0.0.1",At=((M=j.host)==null?void 0:M.trim())||((Q=(A=j.http)==null?void 0:A.host)==null?void 0:Q.trim())||"127.0.0.1",Dt=Rt!==Et||Lt!==At||((Me=d.http)==null?void 0:Me.enabled)!==((He=j.http)==null?void 0:He.enabled)||((Ke=d.http)==null?void 0:Ke.port)!==((qe=j.http)==null?void 0:qe.port)||(((Be=d.http)==null?void 0:Be.host)??d.host??"127.0.0.1")!==(((Ue=j.http)==null?void 0:Ue.host)??j.host??"127.0.0.1")||((Ye=d.https)==null?void 0:Ye.enabled)!==((Ve=j.https)==null?void 0:Ve.enabled)||((Ie=d.https)==null?void 0:Ie.port)!==((Qe=j.https)==null?void 0:Qe.port)||(((_e=d.https)==null?void 0:_e.host)??d.host??"127.0.0.1")!==(((ze=j.https)==null?void 0:ze.host)??j.host??"127.0.0.1")||(($e=d.https)==null?void 0:$e.keyPath)!==((Je=j.https)==null?void 0:Je.keyPath)||((Ge=d.https)==null?void 0:Ge.certPath)!==((We=j.https)==null?void 0:We.certPath)||tt((Xe=d.https)==null?void 0:Xe.caPath)!==tt((Ze=j.https)==null?void 0:Ze.caPath);t({title:s(Dt?"settings.toast.protocolRestartRequired":"settings.toast.saveSuccess"),variant:"success"}),U&&(o.invalidateQueries({queryKey:["stats"]}),o.invalidateQueries({queryKey:["dashboard"]}),o.invalidateQueries({queryKey:["logs"]}),o.invalidateQueries({queryKey:["billing"]}),o.invalidateQueries({queryKey:["api-keys"]})),l.refetch()}catch(me){t({title:s("settings.toast.saveFailure",{message:Ut(me).message}),variant:"error"})}finally{Re(!1)}}},[D,d,l,p,U,t,o,s,Te,Oe]),oe=m.useCallback(()=>{d&&(q(be(d)),te(ge(d)),ee({}),se({}))},[d]),ce=m.useCallback(async()=>{if(Fe()){De(!0);try{const r={enabled:b.enabled,username:b.username.trim()||void 0};b.password&&(r.password=b.password);const x=await O.mutateAsync(r);x.auth&&(Ae(x.auth),$({enabled:x.auth.enabled,username:x.auth.username??"",password:"",confirmPassword:""}),J({})),g.refetch()}catch{}finally{De(!1)}}},[b,g,O,Fe]),de=m.useCallback(()=>{N&&($(fe(N)),J({}))},[N]),vt=m.useCallback(async()=>{(ae||U)&&await re(),ie&&await ce()},[ce,re,ie,U,ae]),jt=m.useCallback(()=>{oe(),de()},[de,oe]),Nt=m.useCallback(async()=>{if(!k){t({title:s("settings.toast.copyFailure",{message:s("settings.file.unknown")}),variant:"error"});return}try{await It(k),t({title:s("settings.toast.copySuccess"),variant:"success"})}catch(r){t({title:s("settings.toast.copyFailure",{message:r instanceof Error?r.message:"unknown"}),variant:"error"})}},[k,t,s]),Ct=m.useCallback(async()=>{Ee(!0);try{await L.mutateAsync()}catch{}finally{Ee(!1)}},[L]),wt=m.useCallback(async()=>{Le(!0);try{await w.mutateAsync()}catch{}finally{Le(!1)}},[w]),Pt=K.data?Qt(K.data.totalBytes??K.data.sizeBytes):"-",ue=l.isPending||!d&&l.isFetching;return m.useEffect(()=>{if(ue)return;const r=Array.from(i.current.values());if(r.length===0)return;const x=new IntersectionObserver(C=>{for(const v of C)if(v.isIntersecting){a(v.target.id);break}},{rootMargin:"-80px 0px -60% 0px",threshold:0});for(const C of r)x.observe(C);return()=>x.disconnect()},[ue]),{activeSection:c,authErrors:mt,authForm:b,authQuery:g,authSettings:N,billingErrors:ht,billingForm:D,clearingAll:rt,cleaning:lt,compacting:h.isPending,config:d,configPath:k,configQuery:l,confirmCleanupOpen:ot,confirmClearAllOpen:dt,dbSizeDisplay:Pt,defaultsSummary:xt,errors:nt,form:p,handleAuthReset:de,handleAuthSave:ce,handleCleanupLogs:Ct,handleClearAllLogs:wt,handleCompact:h.mutate,handleCopyPath:Nt,handleInputChange:yt,handleReset:oe,handleResetAll:jt,handleSave:re,handleSaveAll:vt,handleSectionClick:u,isAuthDirty:ie,isBillingDirty:U,isConfigDirty:ae,isLoading:ue,needsPassword:bt,protocolSummaryLabel:gt,protocolChangesPending:ft,saving:it,savingAuth:pt,sectionRefs:i,setAuthForm:$,setConfirmCleanupOpen:ct,setConfirmClearAllOpen:ut,setErrors:ee,setForm:q,setBillingForm:te,setSectionRef:n,t:s}}function Ps(){const{t:s}=E(),t=is(),o=Number(t.isConfigDirty)+Number(t.isAuthDirty)+Number(t.isBillingDirty),c=o>0,a=_t(({currentLocation:i,nextLocation:u})=>c&&i.pathname!==u.pathname);return m.useEffect(()=>{if(!c)return;const i=u=>{u.preventDefault(),u.returnValue=""};return window.addEventListener("beforeunload",i),()=>window.removeEventListener("beforeunload",i)},[c]),e.jsxs("div",{className:"flex flex-col gap-6",children:[e.jsx(Ht,{info:o>0?e.jsx("span",{className:"rounded-lg bg-warning-bg px-2.5 py-1 text-xs font-medium text-warning",children:s("settings.overview.unsavedCount",{count:o})}):null,status:t.protocolChangesPending?e.jsx("span",{className:"text-xs text-muted-foreground",children:s("settings.protocol.restartWarning")}):null,actions:null}),t.isLoading?e.jsx(Se,{label:s("common.loading")}):t.config?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-6 xl:grid-cols-[200px_minmax(0,1fr)]",children:[e.jsx(Wt,{activeSection:t.activeSection,onSelectSection:t.handleSectionClick}),e.jsxs("div",{className:"flex min-w-0 flex-col gap-6",children:[e.jsx(Xt,{defaultsSummary:t.defaultsSummary,errors:t.errors,form:t.form,onInputChange:t.handleInputChange,onSetForm:t.setForm,sectionRef:t.setSectionRef("section-basics")}),e.jsx(Zt,{errors:t.errors,form:t.form,onSetForm:t.setForm,protocolChangesPending:t.protocolChangesPending,sectionRef:t.setSectionRef("section-protocol")}),e.jsx(es,{authErrors:t.authErrors,authForm:t.authForm,authLoading:t.authQuery.isPending||!t.authSettings&&t.authQuery.isFetching,authSettings:t.authSettings,needsPassword:t.needsPassword,onSetAuthForm:t.setAuthForm,sectionRef:t.setSectionRef("section-security")}),e.jsx(ts,{errors:t.billingErrors,form:t.billingForm,onSetForm:t.setBillingForm,sectionRef:t.setSectionRef("section-billing")}),e.jsx(ss,{configPath:t.configPath,onCopyPath:()=>void t.handleCopyPath(),sectionRef:t.setSectionRef("section-config-file")}),e.jsx(as,{cleaning:t.cleaning,clearingAll:t.clearingAll,compacting:t.compacting,dbSizeDisplay:t.dbSizeDisplay,onCompact:t.handleCompact,onOpenCleanup:()=>t.setConfirmCleanupOpen(!0),onOpenClearAll:()=>t.setConfirmClearAllOpen(!0),sectionRef:t.setSectionRef("section-cleanup")})]})]}),e.jsx(ns,{dirtyCount:o,protocolChangesPending:t.protocolChangesPending,onReset:t.handleResetAll,onSave:()=>void t.handleSaveAll(),saving:t.saving||t.savingAuth})]}):e.jsx(F,{children:e.jsx(H,{className:"pt-6",children:e.jsx("p",{className:"text-sm font-medium text-destructive",children:s("settings.toast.missingConfig")})})}),e.jsx(xe,{open:t.confirmCleanupOpen,onOpenChange:i=>{!i&&!t.cleaning&&t.setConfirmCleanupOpen(!1)},title:s("settings.cleanup.confirmTitle"),description:s("settings.cleanup.confirmDescription"),confirmLabel:t.cleaning?s("common.actions.cleaning"):s("common.actions.cleanup"),cancelLabel:s("common.actions.cancel"),loading:t.cleaning,onConfirm:async()=>{await t.handleCleanupLogs(),t.setConfirmCleanupOpen(!1)}}),e.jsx(xe,{open:t.confirmClearAllOpen,onOpenChange:i=>{!i&&!t.clearingAll&&t.setConfirmClearAllOpen(!1)},title:s("settings.cleanup.clearAllTitle"),description:s("settings.cleanup.clearAllWarning"),confirmLabel:t.clearingAll?s("settings.cleanup.clearingAll"):s("settings.cleanup.clearAll"),cancelLabel:s("common.actions.cancel"),loading:t.clearingAll,onConfirm:async()=>{await t.handleClearAllLogs(),t.setConfirmClearAllOpen(!1)}}),e.jsx(xe,{open:a.state==="blocked",onOpenChange:i=>{!i&&a.state==="blocked"&&a.reset()},title:s("settings.unsaved.title"),description:s("settings.unsaved.body"),confirmLabel:s("settings.unsaved.confirm"),cancelLabel:s("common.actions.cancel"),onConfirm:()=>{a.state==="blocked"&&a.proceed()}})]})}export{Ps as default};