@bigduu/lotus 2026.5.12 → 2026.5.13

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 (97) hide show
  1. package/dist/assets/{App-D9R-_Pem.css → App-DNZiQHSs.css} +1 -1
  2. package/dist/assets/App-bVqmFSlk.js +224 -0
  3. package/dist/assets/{FeatureGuide-BNBq_PLn.js → FeatureGuide-BlFyQEho.js} +1 -1
  4. package/dist/assets/MetricsService-PUxHq4VE.js +1 -0
  5. package/dist/assets/SubAgentsPanel-B1pN_aEg.js +1 -0
  6. package/dist/assets/{_baseUniq-DVrw3Tro.js → _baseUniq-Rkm-pzcz.js} +1 -1
  7. package/dist/assets/{architectureDiagram-Q4EWVU46-BZE_2gaA.js → architectureDiagram-Q4EWVU46-Dr89vzdU.js} +1 -1
  8. package/dist/assets/{blockDiagram-DXYQGD6D-CI8uSrzU.js → blockDiagram-DXYQGD6D-TGOxvREa.js} +1 -1
  9. package/dist/assets/{c4Diagram-AHTNJAMY-DYfj69gY.js → c4Diagram-AHTNJAMY-CBv5o-M1.js} +1 -1
  10. package/dist/assets/{chunk-4BX2VUAB-Cw-2rap4.js → chunk-4BX2VUAB-CxLevY_l.js} +1 -1
  11. package/dist/assets/{chunk-4TB4RGXK-jxTPHq0D.js → chunk-4TB4RGXK-CZ85N7UX.js} +1 -1
  12. package/dist/assets/{chunk-55IACEB6-DmAIxchJ.js → chunk-55IACEB6-CyMcswjM.js} +1 -1
  13. package/dist/assets/{chunk-EDXVE4YY-FvClTRCF.js → chunk-EDXVE4YY-KspsFgAM.js} +1 -1
  14. package/dist/assets/{chunk-FMBD7UC4-Dv-f6b4O.js → chunk-FMBD7UC4-BH440Lco.js} +1 -1
  15. package/dist/assets/{chunk-OYMX7WX6-CUAa_Yz6.js → chunk-OYMX7WX6-D5KuKqj-.js} +1 -1
  16. package/dist/assets/{chunk-QZHKN3VN-D1FDs1aQ.js → chunk-QZHKN3VN-CYjk1VsY.js} +1 -1
  17. package/dist/assets/{chunk-YZCP3GAM-C2iPLYG9.js → chunk-YZCP3GAM-D1Ua-1JA.js} +1 -1
  18. package/dist/assets/classDiagram-6PBFFD2Q-D76pdmuK.js +1 -0
  19. package/dist/assets/classDiagram-v2-HSJHXN6E-D76pdmuK.js +1 -0
  20. package/dist/assets/clone-L6_2PEie.js +1 -0
  21. package/dist/assets/{cose-bilkent-S5V4N54A-CidaofdU.js → cose-bilkent-S5V4N54A-DBcT_Wx0.js} +1 -1
  22. package/dist/assets/{dagre-KV5264BT-B5okAMLc.js → dagre-KV5264BT-DXZkFF5A.js} +1 -1
  23. package/dist/assets/{diagram-5BDNPKRD-DqlBY-17.js → diagram-5BDNPKRD-BsQPI1ko.js} +1 -1
  24. package/dist/assets/{diagram-G4DWMVQ6-BuAFDD-X.js → diagram-G4DWMVQ6-BO9UfQRh.js} +1 -1
  25. package/dist/assets/{diagram-MMDJMWI5-CFv_32_w.js → diagram-MMDJMWI5-DkWy2py4.js} +1 -1
  26. package/dist/assets/{diagram-TYMM5635-CEU-9NCq.js → diagram-TYMM5635-DkuaI_3A.js} +1 -1
  27. package/dist/assets/en-US-CnZu52UQ.js +3 -0
  28. package/dist/assets/{erDiagram-SMLLAGMA-BGcZ-Hfc.js → erDiagram-SMLLAGMA-5BQBJx-k.js} +1 -1
  29. package/dist/assets/{flowDiagram-DWJPFMVM-CCSeCjR1.js → flowDiagram-DWJPFMVM-CBv8eO1S.js} +1 -1
  30. package/dist/assets/{ganttDiagram-T4ZO3ILL-BqAoxnNO.js → ganttDiagram-T4ZO3ILL-CkWwjmoY.js} +1 -1
  31. package/dist/assets/{gitGraphDiagram-UUTBAWPF-DJ0V7_Rv.js → gitGraphDiagram-UUTBAWPF-Cq7iSNVm.js} +1 -1
  32. package/dist/assets/{graph-BxbYGKIB.js → graph-DP71R45G.js} +1 -1
  33. package/dist/assets/index-BBEDlZ5R.js +1 -0
  34. package/dist/assets/index-Bcpx4-c6.js +1 -0
  35. package/dist/assets/{index-DvyQfHOQ.js → index-BfCdANOc.js} +1 -1
  36. package/dist/assets/index-C1smAwgR.js +1 -0
  37. package/dist/assets/index-CIgS9N5-.js +1 -0
  38. package/dist/assets/index-CWTKRCxw.js +21 -0
  39. package/dist/assets/index-D9ODTr93.css +1 -0
  40. package/dist/assets/index-Dyeykeg3.js +8 -0
  41. package/dist/assets/index-GggL5P0b.js +1 -0
  42. package/dist/assets/index-Y7yrhp6h.js +1 -0
  43. package/dist/assets/{index-B-HCj2Sv.js → index-YqZv5PIH.js} +1 -1
  44. package/dist/assets/index-ZWAEbTDI.js +1 -0
  45. package/dist/assets/index-oQX-HGAT.js +1 -0
  46. package/dist/assets/index-rcVNW1p_.js +1 -0
  47. package/dist/assets/{index.es-BhiHSeCT.js → index.es-usLOUMSp.js} +1 -1
  48. package/dist/assets/{infoDiagram-42DDH7IO-Cemw9omR.js → infoDiagram-42DDH7IO-Cs719lD3.js} +1 -1
  49. package/dist/assets/{ishikawaDiagram-UXIWVN3A-BYRE-suN.js → ishikawaDiagram-UXIWVN3A-zTI5fHSR.js} +1 -1
  50. package/dist/assets/{journeyDiagram-VCZTEJTY-BRkAfzxG.js → journeyDiagram-VCZTEJTY-DINdIE0t.js} +1 -1
  51. package/dist/assets/{kanban-definition-6JOO6SKY-DrTcKNPa.js → kanban-definition-6JOO6SKY-BWZUu9_H.js} +1 -1
  52. package/dist/assets/{layout-B2E_GeCC.js → layout-QZEMSKRD.js} +1 -1
  53. package/dist/assets/main-BEVjNwcv.js +8 -0
  54. package/dist/assets/{min-5KBdYKFY.js → min-BB314uX0.js} +1 -1
  55. package/dist/assets/{mindmap-definition-QFDTVHPH-sq4qw8uy.js → mindmap-definition-QFDTVHPH-GgqTvonx.js} +1 -1
  56. package/dist/assets/{pieDiagram-DEJITSTG-C8vOtX53.js → pieDiagram-DEJITSTG-wmUFaxVG.js} +1 -1
  57. package/dist/assets/{quadrantDiagram-34T5L4WZ-LV5yQE3M.js → quadrantDiagram-34T5L4WZ-Bt7Nxjyo.js} +1 -1
  58. package/dist/assets/{requirementDiagram-MS252O5E-Bq6y8VCF.js → requirementDiagram-MS252O5E-4eb0TnXV.js} +1 -1
  59. package/dist/assets/{sankeyDiagram-XADWPNL6-DvABiNaK.js → sankeyDiagram-XADWPNL6-H6jXqw4X.js} +1 -1
  60. package/dist/assets/{sequenceDiagram-FGHM5R23-Bv9Ckauz.js → sequenceDiagram-FGHM5R23-DgqfEZPw.js} +1 -1
  61. package/dist/assets/{stateDiagram-FHFEXIEX-CwYUsnc5.js → stateDiagram-FHFEXIEX-CZrwRbTi.js} +1 -1
  62. package/dist/assets/stateDiagram-v2-QKLJ7IA2-CwhUMrAy.js +1 -0
  63. package/dist/assets/{timeline-definition-GMOUNBTQ-BgidC49j.js → timeline-definition-GMOUNBTQ-CMjl6c48.js} +1 -1
  64. package/dist/assets/vendor-antd-C8lKwvI6.js +502 -0
  65. package/dist/assets/{vendor-charts-BYce7JXy.js → vendor-charts-bhMup2Pu.js} +1 -1
  66. package/dist/assets/{vendor-markdown-DzaXAW9Q.js → vendor-markdown-DZuK0SxV.js} +1 -1
  67. package/dist/assets/{vendor-mermaid-De-Yacw-.js → vendor-mermaid-C1Gk9PtT.js} +4 -4
  68. package/dist/assets/{vendor-pdf-DHgAFQ2M.js → vendor-pdf-DB-djSmA.js} +4 -4
  69. package/dist/assets/{vennDiagram-DHZGUBPP-Bzkbjibi.js → vennDiagram-DHZGUBPP-CJuHv1C-.js} +1 -1
  70. package/dist/assets/{wardley-RL74JXVD-CBRp4POe.js → wardley-RL74JXVD-3f0MBifK.js} +1 -1
  71. package/dist/assets/{wardleyDiagram-NUSXRM2D-DAhT4-uz.js → wardleyDiagram-NUSXRM2D-DsfJX8FP.js} +1 -1
  72. package/dist/assets/{xychartDiagram-5P7HB3ND-CXfA4uSx.js → xychartDiagram-5P7HB3ND-DnywOWSH.js} +1 -1
  73. package/dist/assets/zh-CN-NcKxgANL.js +3 -0
  74. package/dist/index.html +4 -4
  75. package/package.json +2 -2
  76. package/dist/assets/App-D0lPE9xB.js +0 -223
  77. package/dist/assets/SubAgentsPanel-Cd3hI6oA.js +0 -1
  78. package/dist/assets/classDiagram-6PBFFD2Q-DVvX4wPS.js +0 -1
  79. package/dist/assets/classDiagram-v2-HSJHXN6E-DVvX4wPS.js +0 -1
  80. package/dist/assets/clone-DRAA6Q7k.js +0 -1
  81. package/dist/assets/en-US-DLwJLted.js +0 -3
  82. package/dist/assets/index-BEkwZ-K8.js +0 -1
  83. package/dist/assets/index-BJ91JKHM.js +0 -1
  84. package/dist/assets/index-BU7SwU12.js +0 -1
  85. package/dist/assets/index-CZebUuvC.js +0 -1
  86. package/dist/assets/index-CjawVLpi.js +0 -1
  87. package/dist/assets/index-CucuFwVZ.css +0 -1
  88. package/dist/assets/index-D6i0E0ol.js +0 -8
  89. package/dist/assets/index-DMuHtlMb.js +0 -1
  90. package/dist/assets/index-DYN0Kom_.js +0 -1
  91. package/dist/assets/index-DaK9qR94.js +0 -1
  92. package/dist/assets/index-sP4t2bcu.js +0 -1
  93. package/dist/assets/index-t4uyozr6.js +0 -21
  94. package/dist/assets/main-C9Xbnb0p.js +0 -6
  95. package/dist/assets/stateDiagram-v2-QKLJ7IA2-aegiqwuH.js +0 -1
  96. package/dist/assets/vendor-antd-DODjfilb.js +0 -502
  97. package/dist/assets/zh-CN-B74Ip0pW.js +0 -3
@@ -1,21 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-B-HCj2Sv.js","./vendor-markdown-DzaXAW9Q.js","./vendor-i18n-BNURlJ23.js","./vendor-antd-DODjfilb.js","./App-D0lPE9xB.js","./vendor-mermaid-De-Yacw-.js","./main-C9Xbnb0p.js","./main-B6snAd4S.css","./App-D9R-_Pem.css"])))=>i.map(i=>d[i]);
2
- var On=Object.defineProperty;var Nn=(e,s,n)=>s in e?On(e,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[s]=n;var Ls=(e,s,n)=>Nn(e,typeof s!="symbol"?s+"":s,n);import{j as t}from"./vendor-markdown-DzaXAW9Q.js";import{a as i,u as Z,R as zs,i as $n}from"./vendor-i18n-BNURlJ23.js";import{w as Vn,u as Ae,f as Bn,z as qn,s as Un,B as Es,i as Vt,n as rt,D as Hn,F as at,G as Te,H as Kn,I as Wn,J as Gn,K as Jn,L as En,S as Bt,M as Be,v as Os,k as pe,N as Dn,t as In,b as Xn,a as _s,o as Yn,O as Ns,P as Zn,Q as Qn,R as Dt,T as ea,U as ta,V as sa,W as $s,X as Vs,Y as Bs,Z as qs,d as na,_ as aa,A as ra,$ as oa,a0 as ia,a1 as la,a2 as ca,a3 as da}from"./App-D0lPE9xB.js";import{C as I,S as F,A as ke,j as ie,W as q,E as z,t as fe,M as _,J as qt,av as rs,aw as re,ax as ge,L as We,ay as Ve,az as ae,k as ve,aA as Re,aB as he,aC as ua,at as Ie,a7 as V,aD as Ds,aE as ga,Q as os,U as cs,ac as ma,aF as pa,K as Kt,aG as ds,O as Is,N as Ut,aH as Us,l as ue,aI as et,V as ot,aj as Tt,I as St,ae as vt,aJ as ha,a9 as fa,aK as Hs,aL as we,G as Le,ai as Pn,aM as ya,aN as tt,aO as ye,B as xa,aP as Ks,aQ as ba,aR as va,o as ws,z as ja,aS as Ws,aT as Zt,aU as Ta,aV as Sa,a3 as _a,ao as wa,aW as ka}from"./vendor-antd-DODjfilb.js";import{_ as ks}from"./vendor-mermaid-De-Yacw-.js";import{r as Ma}from"./onboardingStorage-BVcEpmTy.js";import"./main-C9Xbnb0p.js";import{R as _t,B as Ps,C as Wt,X as Gt,Y as Jt,T as wt,L as Fs,a as is,b as Fn,c as jt,P as Ca,d as Ea,e as Da}from"./vendor-charts-BYce7JXy.js";function Ia(e){return e instanceof Vn}function Pa(){const{chats:e,currentSessionId:s,currentChat:n,addMessage:a,selectSession:o,deleteSession:r,deleteSessions:l,deleteMessage:m,updateSession:c,persistSessionTitle:p,pinSession:d,unpinSession:b,loadChats:f}=Ae(Bn(x=>({chats:x.chats,currentSessionId:x.currentSessionId,currentChat:qn(x),addMessage:x.addMessage,selectSession:x.selectSession,deleteSession:x.deleteSession,deleteSessions:x.deleteSessions,deleteMessage:x.deleteMessage,updateSession:x.updateSession,persistSessionTitle:x.persistSessionTitle,pinSession:x.pinSession,unpinSession:x.unpinSession,loadChats:x.loadChats}))),w=Ae(Un(s)),v=i.useMemo(()=>(n==null?void 0:n.messages)||[],[n]),u=i.useMemo(()=>e.filter(x=>x.pinned),[e]),C=i.useMemo(()=>e.filter(x=>!x.pinned),[e]),j=e.length;return{chats:e,currentSessionId:s,currentChat:n,isProcessing:w,baseMessages:v,pinnedChats:u,unpinnedChats:C,chatCount:j,addMessage:a,deleteMessage:m,selectSession:o,deleteSession:r,deleteSessions:l,pinSession:d,unpinSession:b,updateSession:c,persistSessionTitle:p,loadChats:f}}function Fa(e){const s=Ae(f=>f.addChat),n=Ae(f=>f.lastSelectedPromptId),a=Ae(f=>f.systemPrompts),o=Es.getInstance(),r=i.useCallback(async(f,w)=>{var j,x;const v=a.find(E=>E.id===n),u=(v==null?void 0:v.id)||(a.length>0?((j=a.find(E=>E.id==="general_assistant"))==null?void 0:j.id)||a[0].id:""),C={title:f||"New Session",createdAt:Date.now(),messages:[],config:{systemPromptId:u,baseSystemPrompt:(v==null?void 0:v.content)||(a.length>0?((x=a.find(E=>E.id==="general_assistant"))==null?void 0:x.content)||a[0].content:""),lastUsedEnhancedPrompt:null,...Vt.getState().isProviderModelRefEnabled()?{model_ref:Vt.getState().selectedModelRef}:{}},...w};await s(C)},[s,n,a]),l=i.useCallback(async f=>{rt("[ChatOps]","[useChatOperations] createChatWithSystemPrompt started with prompt:",f);const w={title:`New Session - ${f.name}`,createdAt:Date.now(),messages:[],config:{systemPromptId:f.id,baseSystemPrompt:f.content,lastUsedEnhancedPrompt:null}};rt("[ChatOps]","[useChatOperations] Calling addChat with newChatData.config:",w.config),await s(w)},[s]),m=i.useCallback(f=>{const w=e.chats.find(v=>v.id===f);w&&(w.pinned?e.unpinSession(f):e.pinSession(f))},[e]),c=i.useCallback((f,w)=>{e.updateSession(f,{title:w})},[e]),p=i.useCallback(async()=>{await o.cleanupSessions("empty",!0),await Ae.getState().loadChats()},[o]),d=i.useCallback(async()=>{await o.cleanupSessions("all",!0),await Ae.getState().loadChats()},[o]),b=i.useCallback(async()=>{await o.cleanupSessions("all",!1),await Ae.getState().loadChats()},[o]);return{createNewChat:r,createChatWithSystemPrompt:l,toggleChatPin:m,updateChatTitle:c,deleteEmptyChats:p,deleteAllUnpinnedChats:d,deleteAllChats:b}}function Ra(e,s){const n=i.useMemo(()=>e.baseMessages,[e.baseMessages]),a=i.useCallback(async()=>{var p;if(!e.currentSessionId||!e.currentChat)return;const o=[...e.baseMessages];if(o.length===0)return;const r=o[o.length-1];let l=o;if((r==null?void 0:r.role)==="assistant"){if(!(await e.deleteMessage(e.currentSessionId,r.id)).success)return;l=o.slice(0,-1)}const m=[...l].reverse().find(d=>d.role==="user");if(!m)return;const c="content"in m?m.content:m.displayText;typeof c=="string"&&await((p=s==null?void 0:s.onRetry)==null?void 0:p.call(s,c))},[e,s]);return{currentMessages:n,retryLastMessage:a}}const Aa=()=>{const e=Pa(),s=Fa(e),n=Hn({sessionId:e.currentSessionId,addMessage:e.addMessage,updateSession:e.updateSession}),a=Ra(e,{onRetry:n.sendMessage});return{chats:e.chats,currentSessionId:e.currentSessionId,currentChat:e.currentChat,pinnedChats:e.pinnedChats,unpinnedChats:e.unpinnedChats,chatCount:e.chatCount,currentMessages:a.currentMessages,agentAvailable:n.agentAvailable,addMessage:e.addMessage,deleteMessage:e.deleteMessage,selectSession:e.selectSession,deleteSession:e.deleteSession,deleteSessions:e.deleteSessions,pinSession:e.pinSession,unpinSession:e.unpinSession,updateSession:e.updateSession,loadChats:e.loadChats,createNewChat:s.createNewChat,createChatWithSystemPrompt:s.createChatWithSystemPrompt,toggleChatPin:s.toggleChatPin,updateChatTitle:s.updateChatTitle,deleteEmptyChats:s.deleteEmptyChats,deleteAllUnpinnedChats:s.deleteAllUnpinnedChats,deleteAllChats:s.deleteAllChats,retryLastMessage:a.retryLastMessage,sendMessage:n.sendMessage,cancelMessage:n.cancel}},{Text:Qt}=ie,{useToken:La}=fe,za=({httpProxy:e,httpsProxy:s,onHttpProxyChange:n,onHttpsProxyChange:a,onReload:o,onSave:r,isLoading:l})=>{const{t:m}=Z(),{token:c}=La(),p=at(T=>T.proxyAuthStatus),d=at(T=>T.isLoadingProxyAuthStatus),b=at(T=>T.loadProxyAuthStatus),f=at(T=>T.applyProxyAuth),w=at(T=>T.clearProxyAuth),[v,u]=i.useState({username:"",password:""}),[C,j]=i.useState(!1);i.useEffect(()=>{b()},[b]);const x=async()=>{const T=v.username.trim();if(T){j(!0);try{await f({username:T,password:v.password}),u({username:"",password:""})}catch(P){console.error("Failed to apply proxy auth:",P)}finally{j(!1)}}},E=async()=>{j(!0);try{await w()}catch(T){console.error("Failed to clear proxy auth:",T)}finally{j(!1)}};return t.jsx(I,{size:"small",title:t.jsx(Qt,{strong:!0,children:m("settings.networkCard.title")}),className:"lotus-settings-card",children:t.jsxs(F,{direction:"vertical",size:c.marginSM,style:{width:"100%"},children:[t.jsx(ke,{message:m("settings.networkCard.guideTip"),type:"info",showIcon:!0}),t.jsxs(F,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[t.jsx(Qt,{type:"secondary",children:m("settings.networkCard.httpProxy")}),t.jsx(q,{"data-testid":"proxy-url",style:{width:"100%"},value:e,onChange:T=>n(T.target.value),placeholder:m("settings.networkCard.proxyPlaceholder"),disabled:l})]}),t.jsxs(F,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[t.jsx(Qt,{type:"secondary",children:m("settings.networkCard.httpsProxy")}),t.jsx(q,{style:{width:"100%"},value:s,onChange:T=>a(T.target.value),placeholder:m("settings.networkCard.proxyPlaceholder"),disabled:l})]}),t.jsx(I,{size:"small",title:m("settings.networkCard.proxyAuthTitle"),className:"lotus-settings-card",style:{marginTop:c.marginSM},children:p!=null&&p.configured?t.jsxs(F,{direction:"vertical",style:{width:"100%"},children:[t.jsx(ke,{type:"success",message:m("settings.networkCard.proxyConfiguredForUser",{username:p.username??""}),showIcon:!0}),t.jsx(z,{onClick:E,loading:C||d,danger:!0,children:m("settings.networkCard.clearCredentials")})]}):t.jsxs(F,{direction:"vertical",size:c.marginXS,style:{width:"100%"},children:[t.jsx(q,{placeholder:m("settings.networkCard.username"),value:v.username,onChange:T=>u(P=>({...P,username:T.target.value}))}),t.jsx(q.Password,{placeholder:m("settings.networkCard.password"),value:v.password,onChange:T=>u(P=>({...P,password:T.target.value}))}),t.jsx(z,{type:"primary",onClick:x,loading:C||d,disabled:!v.username.trim(),children:m("settings.networkCard.apply")})]})}),t.jsx(Qt,{type:"secondary",style:{fontSize:c.fontSizeSM},children:m("settings.networkCard.credentialsStorageNote")}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:c.marginSM},children:[t.jsx(z,{onClick:()=>Promise.resolve(o()).finally(()=>b({force:!0})),disabled:l,children:m("settings.networkCard.reload")}),t.jsx(z,{"data-testid":"save-proxy-settings",type:"primary",onClick:()=>Promise.resolve(r()).finally(()=>b({force:!0})),disabled:l,children:m("settings.networkCard.save")})]})]})})},{Text:Oa}=ie,{useToken:Na}=fe,$a=({msgApi:e})=>{const{t:s}=Z(),{token:n}=Na(),[a]=_.useForm(),[o,r]=i.useState(!1),[l,m]=i.useState(!1),[c,p]=i.useState(!1),[d,b]=i.useState(!1),[f,w]=i.useState(null),v=c&&!d,u=i.useMemo(()=>c?d?s("settings.configTab.accessPassword.helperLocalBypass","当前是本地访问,可直接修改访问密码,无需输入当前密码。"):s("settings.configTab.accessPassword.helperRemote","当前是远程访问。修改访问密码前,必须先输入当前密码。"):s("settings.configTab.accessPassword.helperNotEnabled","未设置访问密码。设置后,远程访问需要先输入密码,本地 loopback 访问可直接绕过。"),[d,c,s]),C=i.useCallback(async()=>{r(!0),w(null);try{const x=await Te.getAccessStatus();p(x.password_enabled),b(x.local_bypass)}catch(x){const E=x instanceof Error?x.message:s("settings.configTab.accessPassword.loadStatusFailed","Failed to load access status");w(E)}finally{r(!1)}},[s]);i.useEffect(()=>{C()},[C]);const j=async()=>{var x;try{const E=await a.validateFields();m(!0),await Te.updateAccessPassword({current_password:((x=E.currentPassword)==null?void 0:x.trim())||void 0,new_password:E.newPassword.trim()}),e.success(c?s("settings.configTab.accessPassword.updated","访问密码已更新"):s("settings.configTab.accessPassword.enabled","访问密码已设置")),a.resetFields(),await C()}catch(E){if(E.errorFields)return;const T=E instanceof Error?E.message:s("settings.configTab.accessPassword.updateFailed","Failed to update access password");e.error(T)}finally{m(!1)}};return t.jsx(I,{size:"small",className:"lotus-settings-card",title:t.jsx(Oa,{strong:!0,children:s("settings.configTab.accessPasswordTitle","访问密码")}),children:t.jsxs(F,{direction:"vertical",size:n.marginMD,style:{width:"100%"},children:[t.jsx(ke,{type:c?"info":"warning",showIcon:!0,message:c?s("settings.configTab.accessPassword.statusEnabled","访问密码已启用"):s("settings.configTab.accessPassword.statusDisabled","访问密码未启用"),description:u}),f?t.jsx(ke,{type:"error",showIcon:!0,message:f}):null,t.jsxs(_,{form:a,layout:"vertical",disabled:o||l,children:[v?t.jsx(_.Item,{label:s("settings.configTab.accessPassword.currentPasswordLabel","当前密码"),name:"currentPassword",rules:[{required:!0,message:s("settings.configTab.accessPassword.validation.currentPasswordRequired","请输入当前密码")}],children:t.jsx(q.Password,{autoComplete:"current-password"})}):null,t.jsx(_.Item,{label:c?s("settings.configTab.accessPassword.newPasswordLabel","新密码"):s("settings.configTab.accessPassword.setPasswordLabel","设置密码"),name:"newPassword",rules:[{required:!0,message:s("settings.configTab.accessPassword.validation.newPasswordRequired","请输入新密码")},{min:4,message:s("settings.configTab.accessPassword.validation.minLength","密码长度至少 4 位")}],children:t.jsx(q.Password,{autoComplete:"new-password"})}),t.jsx(_.Item,{label:s("settings.configTab.accessPassword.confirmPasswordLabel","确认密码"),name:"confirmPassword",dependencies:["newPassword"],rules:[{required:!0,message:s("settings.configTab.accessPassword.validation.confirmPasswordRequired","请再次输入新密码")},({getFieldValue:x})=>({validator(E,T){return!T||x("newPassword")===T?Promise.resolve():Promise.reject(new Error(s("settings.configTab.accessPassword.validation.passwordMismatch","两次输入的密码不一致")))}})],children:t.jsx(q.Password,{autoComplete:"new-password"})}),t.jsx(z,{type:"primary",loading:l,onClick:()=>void j(),children:c?s("settings.configTab.accessPassword.updateAction","更新访问密码"):s("settings.configTab.accessPassword.enableAction","启用访问密码")})]})]})})},{Text:Oe}=ie,{useToken:Va}=fe,Gs="http://127.0.0.1:9562/v1",Ot=e=>[...new Set(e.map(s=>s.trim()).filter(s=>s.length>0))].sort(),Ba=e=>{var n;const s=(n=e.tools)==null?void 0:n.disabled;return Array.isArray(s)?Ot(s.filter(a=>typeof a=="string")):[]},qa=({msgApi:e,locale:s,onLocaleChange:n})=>{const{t:a}=Z(),{token:o}=Va(),[r,l]=i.useState({http_proxy:"",https_proxy:"",memory:{auto_dream_enabled:!1,background_model:""}}),[m,c]=i.useState(Gs),[p,d]=i.useState([]),[b,f]=i.useState([]),[w,v]=i.useState([]),[u,C]=i.useState(!1),[j,x]=i.useState(!1),E=i.useCallback(async()=>{var A,U;C(!0);try{const[$,oe]=await Promise.all([Te.getBambooConfig(),Te.getBambooTools()]);l({http_proxy:$.http_proxy||"",https_proxy:$.https_proxy||"",memory:{auto_dream_enabled:((A=$.memory)==null?void 0:A.auto_dream_enabled)??!1,background_model:((U=$.memory)==null?void 0:U.background_model)||""}});const de=Ba($);f(de),v(de),d(Ot(oe.tools||[]))}catch($){console.error("Failed to load config:",$),e.error(a("settings.configTab.loadConfigFailed"))}finally{C(!1)}},[e,a]);i.useEffect(()=>{E()},[E]);const T=A=>{l(U=>({...U,http_proxy:A}))},P=A=>{l(U=>({...U,https_proxy:A}))},ee=A=>{l(U=>({...U,memory:{...U.memory,auto_dream_enabled:A}}))},R=A=>{l(U=>({...U,memory:{...U.memory,background_model:A}}))},B=async()=>{var A,U;C(!0);try{const $=await Te.validateBambooConfigPatch(r);if(!$.valid){const de=((U=(A=$.errors)==null?void 0:A.proxy)==null?void 0:U[0])??Object.values($.errors||{}).flat().filter(Boolean)[0];e.error((de==null?void 0:de.message)||a("settings.configTab.invalidConfig"));return}await Te.setBambooConfig(r),e.success(a("settings.configTab.saveConfigSuccess"))}catch($){console.error("Failed to save config:",$);const oe=$ instanceof Error&&$.message.trim()?$.message:a("settings.configTab.saveConfigFailed");e.error(oe)}finally{C(!1)}},G=async()=>{e.success(a("settings.configTab.backendSaved"))},h=()=>{c(Gs),e.success(a("settings.configTab.backendResetDefault"))},y=(A,U)=>{f($=>{const oe=new Set($);return U?oe.delete(A):oe.add(A),Ot([...oe])})},D=async()=>{x(!0);try{const A=await Te.getBambooTools();d(Ot(A.tools||[])),e.success(a("settings.configTab.toolsReloadSuccess"))}catch(A){console.error("Failed to reload tools:",A),e.error(a("settings.configTab.toolsLoadFailed"))}finally{x(!1)}},S=async()=>{x(!0);try{const A=Ot(b);await Te.setBambooConfig({tools:{disabled:A}}),f(A),v(A),e.success(a("settings.configTab.toolsSaveSuccess"))}catch(A){console.error("Failed to save tool settings:",A),e.error(a("settings.configTab.toolsSaveFailed"))}finally{x(!1)}},O=JSON.stringify(b)!==JSON.stringify(w),X=new Set(b);return t.jsx(qt,{spinning:u,tip:a("settings.common.loading"),children:t.jsx(rs,{items:[{key:"general",label:a("settings.configTab.tabs.general"),children:t.jsxs(F,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[t.jsx(ke,{message:a("settings.configTab.providerMovedTitle"),description:a("settings.configTab.providerMovedDescription"),type:"info",showIcon:!0,closable:!0}),t.jsx(za,{httpProxy:r.http_proxy,httpsProxy:r.https_proxy,onHttpProxyChange:T,onHttpsProxyChange:P,onReload:E,onSave:B,isLoading:u}),t.jsx(I,{size:"small",className:"lotus-settings-card",title:t.jsx(Oe,{strong:!0,children:a("settings.configTab.language")}),children:t.jsx(re,{value:s,style:{width:260},options:[{label:a("settings.configTab.languageEnglish"),value:"en-US"},{label:a("settings.configTab.languageChinese"),value:"zh-CN"},{label:a("settings.configTab.languageTraditionalChinese"),value:"zh-TW"},{label:a("settings.configTab.languageFrench"),value:"fr-FR"},{label:a("settings.configTab.languageJapanese"),value:"ja-JP"},{label:a("settings.configTab.languageHindi"),value:"hi-IN"}],onChange:A=>n(A)})}),t.jsx(I,{size:"small",className:"lotus-settings-card",title:t.jsx(Oe,{strong:!0,children:a("settings.configTab.memoryTitle")}),children:t.jsxs(F,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[t.jsx(Oe,{type:"secondary",children:a("settings.configTab.memoryDescription")}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:o.marginMD,flexWrap:"wrap"},children:[t.jsxs("div",{children:[t.jsx(Oe,{strong:!0,children:a("settings.configTab.autoDreamEnabled")}),t.jsx("div",{children:t.jsx(Oe,{type:"secondary",style:{fontSize:o.fontSizeSM},children:a("settings.configTab.autoDreamEnabledHint")})})]}),t.jsx(ge,{"data-testid":"auto-dream-toggle",checked:r.memory.auto_dream_enabled,onChange:ee})]}),t.jsxs(F,{direction:"vertical",size:o.marginXXS,style:{width:"100%"},children:[t.jsx(Oe,{strong:!0,children:a("settings.configTab.backgroundModel")}),t.jsx(q,{"data-testid":"auto-dream-background-model-input",value:r.memory.background_model,onChange:A=>R(A.target.value),placeholder:a("settings.configTab.backgroundModelPlaceholder")}),t.jsx(Oe,{type:"secondary",style:{fontSize:o.fontSizeSM},children:a("settings.configTab.backgroundModelHint")})]}),t.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:t.jsx(z,{"data-testid":"save-memory-settings",type:"primary",onClick:B,loading:u,children:a("settings.configTab.save")})})]})}),t.jsx(I,{size:"small",title:t.jsx(Oe,{strong:!0,children:a("settings.configTab.backendApiBaseUrlTitle")}),children:t.jsxs(F,{direction:"vertical",size:o.marginSM,style:{width:"100%"},children:[t.jsx(F,{direction:"vertical",size:o.marginXXS,style:{width:"100%"},children:t.jsx(q,{style:{width:"100%"},value:m,onChange:A=>c(A.target.value),placeholder:a("settings.configTab.backendApiPlaceholder")})}),t.jsx(Oe,{type:"secondary",style:{fontSize:o.fontSizeSM},children:a("settings.configTab.backendApiHint")}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:o.marginSM},children:[t.jsx(z,{"data-testid":"reset-to-defaults",onClick:h,children:a("settings.configTab.resetToDefault")}),t.jsx(z,{"data-testid":"save-api-settings",type:"primary",onClick:G,children:a("settings.configTab.save")})]})]})}),t.jsx($a,{msgApi:e})]})},{key:"tools",label:a("settings.configTab.tabs.tools"),children:t.jsx(I,{size:"small",title:t.jsx(Oe,{strong:!0,children:a("settings.configTab.toolsTitle")}),children:t.jsxs(F,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[t.jsx(Oe,{type:"secondary",children:a("settings.configTab.toolsDescription")}),p.length===0?t.jsx(ke,{type:"info",showIcon:!0,message:a("settings.configTab.toolsEmpty")}):t.jsx(We,{bordered:!0,dataSource:p,renderItem:A=>t.jsx(We.Item,{actions:[t.jsx(ge,{checked:!X.has(A),onChange:U=>y(A,U)},`${A}-switch`)],children:t.jsx(Oe,{code:!0,children:A})})}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:o.marginSM},children:[t.jsx(z,{onClick:D,loading:j,children:a("settings.configTab.reloadTools")}),t.jsx(z,{type:"primary",onClick:S,loading:j,disabled:!O,children:a("settings.configTab.save")})]})]})})}]})})},{Title:Ua,Text:hs}=ie,{useToken:Ha}=fe,Ka=()=>{const{t:e}=Z(),{token:s}=Ha(),n=Kn(),a=Wn(),o=Gn(),[r]=_.useForm(),l=zs.useRef(n);zs.useEffect(()=>{l.current!==n&&(r.setFieldsValue(n),l.current=n)},[n,r]);const m=p=>{l.current={...l.current,...p},a(p)},c=()=>{o(),r.resetFields()};return t.jsxs("div",{style:{padding:"24px",maxWidth:"1200px",margin:"0 auto"},children:[t.jsx(Ua,{level:3,style:{marginBottom:"8px"},children:e("settings.mermaidTab.title")}),t.jsx(hs,{type:"secondary",style:{display:"block",marginBottom:"24px"},children:e("settings.mermaidTab.description")}),t.jsxs(_,{form:r,layout:"vertical",initialValues:n,onValuesChange:m,children:[t.jsxs(I,{title:e("settings.mermaidTab.themeCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:[t.jsx(Ve,{gutter:16,children:t.jsx(ae,{span:24,children:t.jsx(_.Item,{name:"theme",label:t.jsxs(F,{children:[e("settings.mermaidTab.themeLabel"),t.jsx(ve,{title:e("settings.mermaidTab.themeTooltip"),children:t.jsx(Re,{style:{color:s.colorTextSecondary}})})]}),children:t.jsxs(re,{children:[t.jsx(re.Option,{value:"default",children:e("settings.mermaidTab.themeOptions.default")}),t.jsx(re.Option,{value:"neutral",children:e("settings.mermaidTab.themeOptions.neutral")}),t.jsx(re.Option,{value:"dark",children:e("settings.mermaidTab.themeOptions.dark")}),t.jsx(re.Option,{value:"forest",children:e("settings.mermaidTab.themeOptions.forest")}),t.jsx(re.Option,{value:"base",children:e("settings.mermaidTab.themeOptions.base")})]})})})}),t.jsxs(hs,{type:"secondary",style:{display:"block",marginTop:"8px"},children:[t.jsx("strong",{children:e("settings.mermaidTab.themeDescriptionsTitle")}),t.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.default"),t.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.neutral"),t.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.dark"),t.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.forest"),t.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.base")]})]}),t.jsxs(I,{title:e("settings.mermaidTab.globalCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:[t.jsxs(Ve,{gutter:16,children:[t.jsx(ae,{span:12,children:t.jsx(_.Item,{name:"fontSize",label:t.jsxs(F,{children:[e("settings.mermaidTab.fontSizeLabel"),t.jsx(ve,{title:e("settings.mermaidTab.fontSizeTooltip"),children:t.jsx(Re,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:10,max:32,step:1,style:{width:"100%"},addonAfter:"px"})})}),t.jsx(ae,{span:12,children:t.jsx(_.Item,{name:"defaultScale",label:t.jsxs(F,{children:[e("settings.mermaidTab.defaultZoomLabel"),t.jsx(ve,{title:e("settings.mermaidTab.defaultZoomTooltip"),children:t.jsx(Re,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:.1,max:3,step:.1,style:{width:"100%"}})})})]}),t.jsx(_.Item,{name:"useMaxWidth",label:t.jsxs(F,{children:[e("settings.mermaidTab.responsiveWidthLabel"),t.jsx(ve,{title:e("settings.mermaidTab.responsiveWidthTooltip"),children:t.jsx(Re,{style:{color:s.colorTextSecondary}})})]}),valuePropName:"checked",children:t.jsx(ge,{})})]}),t.jsx(I,{title:e("settings.mermaidTab.flowchartCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsxs(Ve,{gutter:16,children:[t.jsx(ae,{span:8,children:t.jsx(_.Item,{name:"flowchartNodeSpacing",label:t.jsxs(F,{children:[e("settings.mermaidTab.flowchartNodeSpacingLabel"),t.jsx(ve,{title:e("settings.mermaidTab.flowchartNodeSpacingTooltip"),children:t.jsx(Re,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:20,max:200,step:10,style:{width:"100%"}})})}),t.jsx(ae,{span:8,children:t.jsx(_.Item,{name:"flowchartRankSpacing",label:t.jsxs(F,{children:[e("settings.mermaidTab.flowchartRankSpacingLabel"),t.jsx(ve,{title:e("settings.mermaidTab.flowchartRankSpacingTooltip"),children:t.jsx(Re,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:20,max:200,step:10,style:{width:"100%"}})})}),t.jsx(ae,{span:8,children:t.jsx(_.Item,{name:"flowchartCurve",label:t.jsxs(F,{children:[e("settings.mermaidTab.flowchartCurveTypeLabel"),t.jsx(ve,{title:e("settings.mermaidTab.flowchartCurveTypeTooltip"),children:t.jsx(Re,{style:{color:s.colorTextSecondary}})})]}),children:t.jsxs(re,{children:[t.jsx(re.Option,{value:"basis",children:e("settings.mermaidTab.flowchartCurveOptions.basis")}),t.jsx(re.Option,{value:"linear",children:e("settings.mermaidTab.flowchartCurveOptions.linear")}),t.jsx(re.Option,{value:"cardinal",children:e("settings.mermaidTab.flowchartCurveOptions.cardinal")})]})})})]})}),t.jsx(I,{title:e("settings.mermaidTab.sequenceCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsxs(Ve,{gutter:16,children:[t.jsx(ae,{span:6,children:t.jsx(_.Item,{name:"sequenceActorMargin",label:t.jsxs(F,{children:[e("settings.mermaidTab.sequenceActorMarginLabel"),t.jsx(ve,{title:e("settings.mermaidTab.sequenceActorMarginTooltip"),children:t.jsx(Re,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:20,max:200,step:10,style:{width:"100%"}})})}),t.jsx(ae,{span:6,children:t.jsx(_.Item,{name:"sequenceMessageMargin",label:t.jsxs(F,{children:[e("settings.mermaidTab.sequenceMessageMarginLabel"),t.jsx(ve,{title:e("settings.mermaidTab.sequenceMessageMarginTooltip"),children:t.jsx(Re,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:10,max:100,step:5,style:{width:"100%"}})})}),t.jsx(ae,{span:6,children:t.jsx(_.Item,{name:"sequenceWidth",label:t.jsxs(F,{children:[e("settings.mermaidTab.sequenceActorWidthLabel"),t.jsx(ve,{title:e("settings.mermaidTab.sequenceActorWidthTooltip"),children:t.jsx(Re,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:100,max:300,step:10,style:{width:"100%"}})})}),t.jsx(ae,{span:6,children:t.jsx(_.Item,{name:"sequenceHeight",label:t.jsxs(F,{children:[e("settings.mermaidTab.sequenceActorHeightLabel"),t.jsx(ve,{title:e("settings.mermaidTab.sequenceActorHeightTooltip"),children:t.jsx(Re,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:40,max:150,step:5,style:{width:"100%"}})})})]})}),t.jsx(I,{title:e("settings.mermaidTab.ganttCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsxs(Ve,{gutter:16,children:[t.jsx(ae,{span:12,children:t.jsx(_.Item,{name:"ganttBarHeight",label:t.jsxs(F,{children:[e("settings.mermaidTab.ganttBarHeightLabel"),t.jsx(ve,{title:e("settings.mermaidTab.ganttBarHeightTooltip"),children:t.jsx(Re,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:10,max:50,step:5,style:{width:"100%"},addonAfter:"px"})})}),t.jsx(ae,{span:12,children:t.jsx(_.Item,{name:"ganttTopPadding",label:t.jsxs(F,{children:[e("settings.mermaidTab.ganttTopPaddingLabel"),t.jsx(ve,{title:e("settings.mermaidTab.ganttTopPaddingTooltip"),children:t.jsx(Re,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:20,max:100,step:10,style:{width:"100%"}})})})]})}),t.jsx(F,{children:t.jsx(z,{icon:t.jsx(ua,{}),onClick:c,children:e("settings.mermaidTab.resetToDefaults")})}),t.jsx(Ie,{}),t.jsx(I,{title:e("settings.mermaidTab.previewTitle"),styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsx(hs,{type:"secondary",children:e("settings.mermaidTab.previewDescription")})})]})]})},Wa=i.lazy(()=>ks(()=>import("./index-B-HCj2Sv.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8]),import.meta.url)),{Text:dt}=ie,{useToken:Ga}=fe,Ja=({promptEnhancement:e,onPromptEnhancementChange:s,mermaidEnhancementEnabled:n,taskEnhancementEnabled:a,showCopilotConclusionWithOptionsEnhancement:o,copilotConclusionWithOptionsEnhancementEnabled:r,onMermaidToggle:l,onTaskToggle:m,onCopilotConclusionWithOptionsToggle:c,onSaveEnhancement:p})=>{const{t:d}=Z(),{token:b}=Ga(),f=b.marginLG;return t.jsxs(V,{vertical:!0,gap:f,children:[t.jsx(I,{size:"small",className:"lotus-settings-card",children:t.jsx(i.Suspense,{fallback:t.jsx(qt,{size:"small"}),children:t.jsx(Wa,{})})}),t.jsx(I,{size:"small",className:"lotus-settings-card",children:t.jsxs(F,{direction:"vertical",size:b.marginXS,style:{width:"100%"},children:[t.jsx(dt,{strong:!0,children:d("settings.promptsTab.title")}),t.jsxs(V,{align:"center",gap:b.marginSM,children:[t.jsx(dt,{strong:!0,children:d("settings.promptsTab.mermaidEnhancement")}),t.jsx(ge,{checked:n,onChange:l})]}),t.jsxs(V,{align:"center",gap:b.marginSM,children:[t.jsx(dt,{strong:!0,children:d("settings.promptsTab.taskListRules")}),t.jsx(ge,{checked:a,onChange:m})]}),o&&t.jsxs(F,{direction:"vertical",size:b.marginXXS,style:{width:"100%"},children:[t.jsxs(V,{align:"center",gap:b.marginSM,children:[t.jsx(dt,{strong:!0,children:d("settings.promptsTab.copilotConclusionWithOptionsBeforeFinish")}),t.jsx(ge,{checked:r,onChange:c})]}),t.jsx(dt,{type:"secondary",style:{fontSize:b.fontSizeSM},children:d("settings.promptsTab.copilotConclusionWithOptionsBeforeFinishDescription",{defaultValue:Jn()})})]}),t.jsx(q.TextArea,{rows:6,placeholder:d("settings.promptsTab.enhancementPlaceholder"),value:e,onChange:w=>s(w.target.value)}),t.jsx(V,{justify:"flex-end",children:t.jsx(z,{type:"primary",onClick:p,children:d("settings.promptsTab.saveEnhancement")})}),t.jsx(dt,{type:"secondary",style:{fontSize:b.fontSizeSM},children:d("settings.promptsTab.description")})]})}),n&&t.jsx(Ds,{size:"small",items:[{key:"mermaid",label:t.jsx(dt,{strong:!0,children:d("settings.mermaidTab.title")}),children:t.jsx(Ka,{})}]})]})},{Text:nt}=ie,{useToken:Xa}=fe,Ya=({themeMode:e,onThemeModeChange:s,vdiSafeMode:n,onVdiSafeModeToggle:a,onClearLocalStorage:o,onResetApp:r,isResetting:l,darkModeKey:m})=>{const{t:c}=Z(),{token:p}=Xa();return t.jsx(I,{size:"small",className:"lotus-settings-card",children:t.jsxs(F,{direction:"vertical",size:p.marginSM,style:{width:"100%"},children:[t.jsxs(V,{align:"center",justify:"space-between",gap:p.marginSM,children:[t.jsx(nt,{strong:!0,children:c("settings.appTab.runningVersion","Running version")}),t.jsxs(nt,{code:!0,"data-testid":"settings-app-version",children:["v",En]})]}),t.jsx(nt,{type:"secondary",style:{fontSize:p.fontSizeSM},children:c("settings.appTab.runningVersionDesc","This is the currently running Lotus frontend version.")}),t.jsxs(V,{align:"center",gap:p.marginSM,children:[t.jsx(nt,{strong:!0,children:c("settings.appTab.darkMode")}),t.jsx(ge,{"data-testid":"dark-mode-toggle",checked:e==="dark",onChange:d=>{const b=d?"dark":"light";s(b),localStorage.setItem(m,b)}})]}),t.jsxs(V,{align:"center",gap:p.marginSM,children:[t.jsx(nt,{strong:!0,children:c("settings.appTab.vdiSafeMode","Graphics compatibility mode")}),t.jsx(ge,{"data-testid":"vdi-safe-mode-toggle",checked:n,onChange:a})]}),t.jsx(nt,{type:"secondary",style:{fontSize:p.fontSizeSM},children:c("settings.appTab.vdiSafeModeDesc","Disables blur and glass effects that can break dropdowns and hover overlays in some virtual desktop, remote, or graphics-constrained environments.")}),t.jsx(z,{block:!0,icon:t.jsx(ga,{}),onClick:()=>{Ma(),window.location.reload()},children:c("settings.appTab.resetStepReplayGuide")}),t.jsx(os,{title:c("settings.appTab.clearLocalStorageTitle"),description:c("settings.appTab.clearLocalStorageDescription"),onConfirm:o,okText:c("settings.appTab.confirmClear"),cancelText:c("settings.appTab.cancel"),placement:"top",children:t.jsx(z,{danger:!0,block:!0,icon:t.jsx(cs,{}),children:c("settings.appTab.clearLocalStorageButton")})}),t.jsx(Ie,{style:{margin:`${p.marginSM}px 0`}}),t.jsxs(V,{align:"center",gap:p.marginSM,children:[t.jsx(ma,{style:{color:p.colorError}}),t.jsx(nt,{strong:!0,style:{color:p.colorError},children:c("settings.appTab.dangerZone")})]}),t.jsx(nt,{type:"secondary",style:{fontSize:p.fontSizeSM},children:c("settings.appTab.dangerDescription")}),t.jsx(os,{title:c("settings.appTab.resetApplicationTitle"),description:t.jsxs("div",{children:[t.jsx("p",{children:c("settings.appTab.resetApplicationIntro")}),t.jsxs("ul",{style:{margin:0,paddingLeft:16},children:[t.jsx("li",{children:c("settings.appTab.resetStepDeleteAllSessions")}),t.jsx("li",{children:c("settings.appTab.resetStepClearStorage")}),t.jsx("li",{children:c("settings.appTab.resetStepResetConfig")}),t.jsx("li",{children:c("settings.appTab.resetStepSetupFlow")}),t.jsx("li",{children:c("settings.appTab.resetStepReload")})]})]}),onConfirm:r,okText:c("settings.appTab.resetConfirm"),cancelText:c("settings.appTab.cancel"),placement:"top",okButtonProps:{danger:!0},children:t.jsx(z,{"data-testid":"reset-to-defaults",danger:!0,block:!0,type:"primary",icon:t.jsx(pa,{}),loading:l,children:c("settings.appTab.resetButton")})})]})})},{Text:ut}=ie,{useToken:Za}=fe,Js=[{value:"literal-token",labelKey:"settings.keywordMaskingTab.example.literalToken",match_type:"exact",pattern:"sk-"},{value:"github",labelKey:"settings.keywordMaskingTab.example.githubTokens",match_type:"regex",pattern:"ghp_[A-Za-z0-9]+"},{value:"aws",labelKey:"settings.keywordMaskingTab.example.awsKeys",match_type:"regex",pattern:"AKIA[0-9A-Z]{16}"},{value:"email",labelKey:"settings.keywordMaskingTab.example.emails",match_type:"regex",pattern:"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"}],Qa=(e,s,n)=>{if(!s)return{masked:e};if(n==="exact")return{masked:e.split(s).join("[MASKED]")};try{const a=new RegExp(s,"g");return{masked:e.replace(a,"[MASKED]")}}catch(a){return{masked:e,error:a instanceof Error?a.message:$n.t("settings.keywordMaskingTab.invalidRegexPattern")}}},er=()=>{const{t:e}=Z(),{message:s}=Kt.useApp(),{token:n}=Za(),[a,o]=i.useState([]),[r,l]=i.useState(!1),[m,c]=i.useState(null),[p,d]=i.useState(""),[b,f]=i.useState("exact"),[w,v]=i.useState(!0),[u,C]=i.useState(),[j,x]=i.useState("My token is sk-123"),E=i.useCallback(async()=>{try{l(!0);const S=await Bt.getInstance().getKeywordMaskingConfig();o(S.entries)}catch(D){s.error(e("settings.keywordMaskingTab.loadFailed")),console.error(D)}finally{l(!1)}},[e]);i.useEffect(()=>{E()},[E]);const T=async D=>{try{const S=Bt.getInstance(),O=await S.validateKeywordEntries(D);if(!O.valid&&O.errors){const A=O.errors.map(U=>`Entry ${U.index+1}: ${U.message}`).join("; ");return s.error(`${e("settings.keywordMaskingTab.validationFailedPrefix")}: ${A}`),!1}const X=await S.updateKeywordMaskingConfig(D);return o(X.entries),s.success(e("settings.keywordMaskingTab.saveSuccess")),!0}catch(S){return s.error(S instanceof Error?S.message:e("settings.keywordMaskingTab.saveFailed")),!1}},P=async()=>{const D={pattern:"",match_type:"exact",enabled:!0},S=[...a,D];o(S),c(S.length-1),d(""),f("exact"),v(!0),C(void 0)},ee=D=>{const S=a[D];c(D),d(S.pattern),f(S.match_type),v(S.enabled),C(void 0)},R=async()=>{if(m===null)return;if(!p.trim()){s.error(e("settings.keywordMaskingTab.patternRequired"));return}const D=[...a];D[m]={pattern:p.trim(),match_type:b,enabled:w},await T(D)&&c(null)},B=()=>{var D;m!==null&&!((D=a[m])!=null&&D.pattern)&&o(a.filter((S,O)=>O!==m)),c(null)},G=async D=>{const S=a.filter((O,X)=>X!==D);await T(S)},h=async(D,S)=>{const O=[...a];O[D]={...O[D],enabled:S},await T(O)},y=Qa(j,p,b);return t.jsx(I,{className:"lotus-settings-card",title:e("settings.keywordMaskingTab.title"),extra:t.jsx(z,{"data-testid":"add-keyword",type:"primary",icon:t.jsx(Ut,{}),onClick:P,loading:r,children:e("settings.keywordMaskingTab.addKeyword")}),children:t.jsxs(F,{direction:"vertical",style:{width:"100%"},size:"large",children:[t.jsx(ut,{type:"secondary",children:e("settings.keywordMaskingTab.description")}),t.jsx(We,{loading:r,dataSource:a,locale:{emptyText:e("settings.keywordMaskingTab.empty")},renderItem:(D,S)=>t.jsx(We.Item,{style:{backgroundColor:n.colorFillAlter,marginBottom:8,borderRadius:n.borderRadius,padding:12},actions:m===S?[t.jsx(z,{"data-testid":"save-keyword",type:"primary",icon:t.jsx(ds,{}),onClick:R,"aria-label":e("settings.keywordMaskingTab.save")},"save"),t.jsx(z,{onClick:B,children:e("settings.keywordMaskingTab.cancel")},"cancel")]:[t.jsx(z,{icon:t.jsx(Is,{}),onClick:()=>ee(S),"aria-label":e("settings.keywordMaskingTab.edit")},"edit"),t.jsx(z,{"data-testid":`delete-keyword-${S}`,danger:!0,icon:t.jsx(cs,{}),onClick:()=>G(S),"aria-label":e("settings.keywordMaskingTab.delete")},"delete")],children:t.jsx(V,{vertical:!0,style:{width:"100%"},gap:8,children:m===S?t.jsxs(t.Fragment,{children:[t.jsx(q,{"data-testid":"keyword-pattern-input",placeholder:e("settings.keywordMaskingTab.patternPlaceholder"),value:p,onChange:O=>d(O.target.value),autoFocus:!0}),t.jsxs(V,{gap:8,align:"center",wrap:"wrap",children:[t.jsx(re,{"data-testid":"keyword-examples-select","aria-label":e("settings.keywordMaskingTab.examples"),placeholder:e("settings.keywordMaskingTab.examples"),value:u,onChange:O=>{C(O);const X=Js.find(A=>A.value===O);X&&(d(X.pattern),f(X.match_type))},options:Js.map(O=>({value:O.value,label:e(O.labelKey)})),style:{minWidth:220}}),t.jsx(re,{value:b,onChange:f,options:[{value:"exact",label:e("settings.keywordMaskingTab.exactMatch")},{value:"regex",label:e("settings.keywordMaskingTab.regexPattern")}],style:{width:150}}),t.jsx(ge,{checked:w,onChange:v})]}),t.jsxs(V,{vertical:!0,gap:6,children:[t.jsx(ut,{type:"secondary",children:e("settings.keywordMaskingTab.sampleText")}),t.jsx(q,{placeholder:e("settings.keywordMaskingTab.sampleTextPlaceholder"),value:j,onChange:O=>x(O.target.value)}),t.jsx(ut,{type:"secondary",children:e("settings.keywordMaskingTab.maskedPreview")}),t.jsx(q,{readOnly:!0,value:y.masked,status:y.error?"error":void 0}),y.error&&t.jsx(ut,{type:"danger",children:y.error})]})]}):t.jsxs(V,{justify:"space-between",align:"center",children:[t.jsxs(V,{vertical:!0,gap:4,children:[t.jsx(ut,{strong:!0,children:D.pattern||e("settings.keywordMaskingTab.emptyPattern")}),t.jsxs(V,{gap:8,children:[t.jsx(ut,{type:"secondary",style:{fontSize:12},children:D.match_type==="regex"?e("settings.keywordMaskingTab.regexPattern"):e("settings.keywordMaskingTab.exactMatch")}),!D.enabled&&t.jsx(ut,{type:"warning",style:{fontSize:12},children:e("settings.keywordMaskingTab.disabled")})]})]}),t.jsx(ge,{checked:D.enabled,onChange:O=>h(S,O),size:"small"})]})})})})]})})},{Text:yt,Paragraph:tr}=ie,sr=/^[A-Za-z_][A-Za-z0-9_]*$/,nr=()=>{const{t:e}=Z(),{message:s}=Kt.useApp(),[n,a]=i.useState([]),[o,r]=i.useState(!1),[l,m]=i.useState(!1),[c,p]=i.useState(null),[d]=_.useForm(),b=i.useCallback(async()=>{r(!0);try{const x=await Be.getEnvVars();a(x.entries)}catch{s.error(e("settings.envVars.fetchError","Failed to load environment variables"))}finally{r(!1)}},[e]);i.useEffect(()=>{b()},[b]);const f=async x=>{var T;const E={name:x.name.trim(),value:x.value,secret:x.secret??!1,description:((T=x.description)==null?void 0:T.trim())||void 0};try{const P=await Be.upsertEnvVar(E);a(P.entries),s.success(c?e("settings.envVars.updated","Variable updated"):e("settings.envVars.created","Variable created")),C()}catch(P){s.error((P instanceof Error?P.message:void 0)||e("settings.envVars.saveError","Failed to save variable"))}},w=async x=>{try{const E=await Be.deleteEnvVar(x);a(E.entries),s.success(e("settings.envVars.deleted","Variable deleted"))}catch(E){s.error((E instanceof Error?E.message:void 0)||e("settings.envVars.deleteError","Failed to delete variable"))}},v=()=>{p(null),d.resetFields(),d.setFieldsValue({secret:!1}),m(!0)},u=x=>{p(x.name),d.setFieldsValue({name:x.name,value:"",secret:x.secret,description:x.description??""}),m(!0)},C=()=>{m(!1),p(null),d.resetFields()},j=[{title:e("settings.envVars.name","Name"),dataIndex:"name",key:"name",render:x=>t.jsx(yt,{code:!0,children:x})},{title:e("settings.envVars.value","Value"),dataIndex:"value",key:"value",render:(x,E)=>E.secret?t.jsxs(yt,{type:"secondary",children:[t.jsx(Us,{style:{marginRight:4}}),E.has_value?"••••••••":e("settings.envVars.notSet","(not set)")]}):t.jsx(yt,{children:x||t.jsx(yt,{type:"secondary",children:e("settings.envVars.empty","(empty)")})})},{title:e("settings.envVars.type","Type"),key:"secret",width:100,render:(x,E)=>E.secret?t.jsx(ue,{color:"warning",icon:t.jsx(Us,{}),children:e("settings.envVars.secret","Secret")}):t.jsx(ue,{color:"processing",children:e("settings.envVars.plain","Plain")})},{title:e("settings.envVars.descriptionCol","Description"),dataIndex:"description",key:"description",ellipsis:!0,render:x=>x?t.jsx(yt,{type:"secondary",children:x}):t.jsx(yt,{type:"secondary",italic:!0,children:"—"})},{title:e("settings.envVars.actions","Actions"),key:"actions",width:120,render:(x,E)=>t.jsxs(F,{size:"small",children:[t.jsx(z,{type:"text",size:"small",icon:t.jsx(Is,{}),onClick:()=>u(E),"aria-label":e("settings.envVars.edit","Edit")}),t.jsx(os,{title:e("settings.envVars.deleteConfirm","Delete this variable?"),onConfirm:()=>w(E.name),okText:e("settings.envVars.yes","Yes"),cancelText:e("settings.envVars.no","No"),children:t.jsx(z,{type:"text",size:"small",danger:!0,icon:t.jsx(cs,{}),"aria-label":e("settings.envVars.delete","Delete")})})]})}];return t.jsxs("div",{style:{maxWidth:900},children:[t.jsxs(I,{className:"lotus-settings-card",title:e("settings.envVars.title","Environment Variables"),extra:t.jsx(z,{type:"primary",icon:t.jsx(Ut,{}),onClick:v,children:e("settings.envVars.addButton","Add Variable")}),children:[t.jsx(tr,{type:"secondary",style:{marginBottom:16},children:e("settings.envVars.description","Variables are injected into Bash tool processes. Secret variables are encrypted at rest.")}),t.jsx(et,{dataSource:n,columns:j,rowKey:"name",size:"small",pagination:!1,loading:o,locale:{emptyText:e("settings.envVars.noVars","No environment variables configured")}})]}),t.jsx(ot,{title:c?e("settings.envVars.editTitle","Edit Variable"):e("settings.envVars.addTitle","Add Environment Variable"),open:l,onCancel:C,onOk:()=>d.submit(),okText:e("settings.envVars.save","Save"),cancelText:e("settings.envVars.cancel","Cancel"),destroyOnClose:!0,children:t.jsxs(_,{form:d,layout:"vertical",onFinish:f,initialValues:{secret:!1},children:[t.jsx(_.Item,{name:"name",label:e("settings.envVars.name","Name"),rules:[{required:!0,message:e("settings.envVars.nameRequired","Variable name is required")},{pattern:sr,message:e("settings.envVars.nameInvalid","Must start with a letter or underscore, followed by letters, digits, or underscores")}],children:t.jsx(q,{placeholder:"GITHUB_TOKEN",disabled:c!==null,autoFocus:c===null})}),t.jsx(_.Item,{name:"value",label:e("settings.envVars.value","Value"),rules:[{required:c===null,message:e("settings.envVars.valueRequired","Value is required for new variables")}],extra:c?e("settings.envVars.valueEditHint","Leave empty to keep the existing value"):void 0,children:t.jsx(q.Password,{placeholder:c?e("settings.envVars.valuePlaceholderEdit","Enter new value or leave empty"):e("settings.envVars.valuePlaceholder","Enter value"),visibilityToggle:!0})}),t.jsx(_.Item,{name:"secret",label:e("settings.envVars.secret","Secret"),valuePropName:"checked",extra:e("settings.envVars.secretHint","Secret variables are encrypted on disk and masked in the UI"),children:t.jsx(ge,{})}),t.jsx(_.Item,{name:"description",label:e("settings.envVars.descriptionField","Description"),children:t.jsx(q,{placeholder:e("settings.envVars.descriptionPlaceholder","Optional description")})})]})})]})},ht=class ht{constructor(){}static getInstance(){return ht.instance||(ht.instance=new ht),ht.instance}async listWorkflows(){try{rt("[WorkflowManager]","[WorkflowManagerService] Listing workflows");const s=await Os.get("bamboo/workflows"),n=Array.isArray(s)?s:[];return rt("[WorkflowManager]","[WorkflowManagerService] Listed workflows:",n),n.map(a=>({name:String(a.name||""),filename:String(a.filename||(a.name||"workflow")+".md"),size:Number(a.size||0),modified_at:typeof a.modified_at=="string"?a.modified_at:void 0,source:"global"}))}catch(s){throw console.error("[WorkflowManagerService] Failed to list workflows:",s),s}}async getWorkflow(s){try{rt("[WorkflowManager]","[WorkflowManagerService] Getting workflow: "+s);const n=await Os.get("bamboo/workflows/"+encodeURIComponent(s)),a=n!=null&&n.name?String(n.name):s,o={name:a,filename:String((n==null?void 0:n.filename)||a+".md"),size:Number((n==null?void 0:n.size)||0),modified_at:n==null?void 0:n.modified_at,source:"global"};return rt("[WorkflowManager]","[WorkflowManagerService] Got workflow:",n),{name:a,content:String((n==null?void 0:n.content)||""),metadata:o}}catch(n){throw console.error("[WorkflowManagerService] Failed to get workflow "+s+":",n),Ia(n)&&n.status===404?new Error("Workflow '"+s+"' not found"):n instanceof Error&&n.message.includes("404")?new Error("Workflow '"+s+"' not found"):n}}};Ls(ht,"instance");let Ms=ht;const{Text:fs}=ie,{TextArea:ar}=q,{useToken:rr}=fe,or=e=>!(!e||e.includes("/")||e.includes("\\")||e.includes("..")),ir=()=>{const{t:e}=Z(),{token:s}=rr(),[n,a]=Tt.useMessage(),[o,r]=i.useState([]),[l,m]=i.useState(!1),[c,p]=i.useState(!1),[d,b]=i.useState(!1),[f,w]=i.useState(null),[v,u]=i.useState(""),[C,j]=i.useState(""),[x,E]=i.useState(!1),T=i.useMemo(()=>Ms.getInstance(),[]),P=i.useCallback(async()=>{m(!0);try{const h=await T.listWorkflows();return r(h),h}catch{return n.error(e("settings.workflowsTab.loadFailed")),[]}finally{m(!1)}},[n,e,T]);i.useEffect(()=>{P()},[P]);const ee=i.useCallback(async h=>{w(h),u(h.name),E(!1),p(!0);try{const y=await T.getWorkflow(h.name);j(y.content??"")}catch{n.error(e("settings.workflowsTab.loadContentFailed")),j("")}finally{p(!1)}},[n,e,T]),R=()=>{w(null),u(""),j(""),E(!1)},B=i.useCallback(async()=>{if(!or(v)){n.error(e("settings.workflowsTab.invalidName"));return}const h=o.some(y=>y.name===v);if(!f&&h){n.error(e("settings.workflowsTab.nameAlreadyExists"));return}b(!0);try{await Bt.getInstance().saveWorkflow(v,C),n.success(e("settings.workflowsTab.saved")),E(!1);const S=(await P()).find(O=>O.name===v);S&&w(S)}catch(y){n.error(y instanceof Error?y.message:e("settings.workflowsTab.saveFailed"))}finally{b(!1)}},[C,v,P,n,f,e,o]),G=i.useCallback(async h=>{try{await Bt.getInstance().deleteWorkflow(h.name),n.success(e("settings.workflowsTab.deleted")),(f==null?void 0:f.name)===h.name&&R(),await P()}catch(y){n.error(y instanceof Error?y.message:e("settings.workflowsTab.deleteFailed"))}},[P,n,f,e]);return t.jsxs("div",{style:{padding:"24px"},children:[a,t.jsxs(I,{title:e("settings.workflowsTab.title"),extra:t.jsxs(F,{children:[t.jsx(z,{icon:t.jsx(St,{}),onClick:P,loading:l,children:e("settings.workflowsTab.refresh")}),t.jsx(z,{"data-testid":"create-workflow",icon:t.jsx(Ut,{}),onClick:R,children:e("settings.workflowsTab.newWorkflow")}),t.jsx(z,{"data-testid":"save-workflow",type:"primary",icon:t.jsx(ds,{}),onClick:B,loading:d,disabled:!x,children:e("settings.workflowsTab.save")})]}),children:[t.jsx(fs,{type:"secondary",children:e("settings.workflowsTab.description")}),t.jsxs(V,{gap:s.marginLG,style:{marginTop:s.marginLG},children:[t.jsx("div",{style:{width:320,flexShrink:0},children:t.jsx(We,{loading:l,dataSource:o,locale:{emptyText:e("settings.workflowsTab.empty")},renderItem:h=>t.jsx(We.Item,{style:{cursor:"pointer",backgroundColor:(f==null?void 0:f.name)===h.name?s.colorFillSecondary:"transparent",borderRadius:s.borderRadius,padding:s.paddingSM},onClick:()=>ee(h),actions:[t.jsx(z,{"data-testid":`delete-workflow-${h.name}`,type:"text",danger:!0,size:"small",icon:t.jsx(cs,{}),onClick:y=>{y.stopPropagation(),G(h)},"aria-label":e("settings.workflowsTab.delete")},"delete")],children:t.jsxs(F,{direction:"vertical",size:0,children:[t.jsxs(fs,{strong:!0,children:["/",h.name]}),t.jsx(fs,{type:"secondary",style:{fontSize:12},children:h.filename})]})})})}),t.jsx("div",{style:{flex:1},children:t.jsxs(F,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(q,{"data-testid":"workflow-name",placeholder:e("settings.workflowsTab.namePlaceholder"),value:v,onChange:h=>{u(h.target.value),E(!0)},disabled:!!f,prefix:t.jsx(Is,{})}),t.jsx(ar,{"data-testid":"workflow-content",placeholder:e("settings.workflowsTab.contentPlaceholder"),value:C,onChange:h=>{j(h.target.value),E(!0)},autoSize:{minRows:12},disabled:c})]})})]})]})]})};var N=(e=>(e.Connecting="connecting",e.Ready="ready",e.Degraded="degraded",e.Stopped="stopped",e.Error="error",e))(N||{});const Xt=6e4,Yt=3e4,Ht=2e4,ls=1e4,us=e=>({id:e,enabled:!0,transport:{type:"stdio",command:"",args:[],env:{},startup_timeout_ms:Ht},request_timeout_ms:Xt,healthcheck_interval_ms:Yt,allowed_tools:[],denied_tools:[]}),lr=()=>({status:"stopped",tool_count:0,restart_count:0}),cr=e=>{switch(typeof e=="string"?e.trim().toLowerCase():""){case N.Connecting:return N.Connecting;case N.Ready:return N.Ready;case N.Degraded:return N.Degraded;case N.Error:return N.Error;case N.Stopped:default:return N.Stopped}},Qe=(e,s)=>{if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const n=Number(e);if(Number.isFinite(n))return n}return s},dr=(e,s)=>{if(!e||typeof e!="object")return s;const n=e;if(n.type==="sse"){const r=Array.isArray(n.headers)?n.headers.map(l=>{if(!l||typeof l!="object")return null;const m=l;return typeof m.name!="string"||typeof m.value!="string"?null:{name:m.name,value:m.value}}).filter(l=>!!l):[];return{type:"sse",url:typeof n.url=="string"?n.url:"",headers:r,connect_timeout_ms:Qe(n.connect_timeout_ms,ls)}}const a=Array.isArray(n.args)?n.args.filter(r=>typeof r=="string"):[],o=n.env&&typeof n.env=="object"?Object.entries(n.env):[];return{type:"stdio",command:typeof n.command=="string"?n.command:"",args:a,cwd:typeof n.cwd=="string"?n.cwd:void 0,env:o.reduce((r,[l,m])=>(typeof m=="string"&&(r[l]=m),r),{}),startup_timeout_ms:Qe(n.startup_timeout_ms,Ht)}},ur=(e,s)=>{const n=us(e.id),a=s??{};return{...n,...a,id:e.id,name:typeof a.name=="string"?a.name:typeof e.name=="string"?e.name:void 0,enabled:typeof e.enabled=="boolean"?e.enabled:typeof a.enabled=="boolean"?a.enabled:!0,request_timeout_ms:Qe(a.request_timeout_ms,Xt),healthcheck_interval_ms:Qe(a.healthcheck_interval_ms,Yt),allowed_tools:Array.isArray(a.allowed_tools)?a.allowed_tools.filter(r=>typeof r=="string"):[],denied_tools:Array.isArray(a.denied_tools)?a.denied_tools.filter(r=>typeof r=="string"):[],reconnect:a.reconnect&&typeof a.reconnect=="object"?{enabled:typeof a.reconnect.enabled=="boolean"?a.reconnect.enabled:!0,initial_backoff_ms:Qe(a.reconnect.initial_backoff_ms,1e3),max_backoff_ms:Qe(a.reconnect.max_backoff_ms,3e4),max_attempts:Qe(a.reconnect.max_attempts,0)}:void 0,transport:dr(a.transport,n.transport)}},gr=e=>{const s=lr(),a=e.runtime??{},o=a.status??e.status;return{status:cr(o),last_error:typeof a.last_error=="string"?a.last_error:typeof e.last_error=="string"?e.last_error:void 0,connected_at:typeof a.connected_at=="string"?a.connected_at:void 0,disconnected_at:typeof a.disconnected_at=="string"?a.disconnected_at:void 0,tool_count:Qe(a.tool_count??e.tool_count,s.tool_count),restart_count:Qe(a.restart_count??e.restart_count,s.restart_count),last_ping_at:typeof a.last_ping_at=="string"?a.last_ping_at:void 0}},mr=e=>{const s=ur(e,e.config);return{id:e.id,name:typeof e.name=="string"?e.name:typeof s.name=="string"?s.name:e.id,enabled:typeof e.enabled=="boolean"?e.enabled:s.enabled,config:s,runtime:gr(e)}},pr=(e,s)=>`mcp__${e}__${s}`,hr=e=>{if(!e.startsWith("mcp__"))return null;const s=e.slice(5),n=s.indexOf("__");if(n<=0)return null;const a=s.slice(0,n),o=s.slice(n+2);return!a||!o?null:{server_id:a,original_name:o}},fr=(e,s,n=0)=>{if(!e||typeof e!="object")return null;const a=e,o=typeof a.alias=="string"?a.alias:typeof a.name=="string"&&a.name.startsWith("mcp__")?a.name:void 0,r=o&&typeof o=="string"?hr(o):null,l=(typeof a.server_id=="string"?a.server_id:void 0)??(typeof a.serverId=="string"?a.serverId:void 0)??(r==null?void 0:r.server_id)??s??"",m=(typeof a.original_name=="string"?a.original_name:void 0)??(typeof a.originalName=="string"?a.originalName:void 0)??(r==null?void 0:r.original_name)??(typeof a.name=="string"?a.name:void 0)??"",c=o??(l&&m?pr(l,m):""),p=typeof a.description=="string"?a.description:"",d=a,b="parameters"in d?d.parameters:"inputSchema"in d?d.inputSchema:"input_schema"in d?d.input_schema:void 0,f=c||m||`mcp_tool_${n}`;return{alias:f,server_id:l||"unknown",original_name:m||f,description:p,parameters:b}};class yr{async getServers(){const s=await pe.get("mcp/servers");return Array.isArray(s.servers)?s.servers.map(mr):[]}async addServer(s){return pe.post("mcp/servers",s)}async updateServer(s,n){const a={...n,id:s};return pe.put(`mcp/servers/${s}`,a)}async deleteServer(s){return pe.delete(`mcp/servers/${s}`)}async connectServer(s){return pe.post(`mcp/servers/${s}/connect`)}async disconnectServer(s){return pe.post(`mcp/servers/${s}/disconnect`)}async refreshTools(s){return pe.post(`mcp/servers/${s}/refresh`)}async getTools(s){const n=s?`mcp/servers/${s}/tools`:"mcp/tools",a=await pe.get(n);return(Array.isArray(a.tools)?a.tools:[]).map((r,l)=>fr(r,s,l)).filter(r=>!!r)}async importServers(s){return pe.post("mcp/servers/import",s)}}const Rn=new yr,xr=5e3,Xe=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,Xs=(e,s)=>`${e}:${s}`,br=(e={})=>{const{service:s=Rn,autoRefreshMs:n=xr,autoRefreshEnabled:a=!0}=e,[o,r]=i.useState([]),[l,m]=i.useState(null),[c,p]=i.useState({}),[d,b]=i.useState({}),[f,w]=i.useState({}),[v,u]=i.useState(!1),[C,j]=i.useState(!1),[x,E]=i.useState(!1),[T,P]=i.useState(null),ee=i.useRef({}),R=i.useCallback(L=>{const W=new Set(L.map(te=>te.id)),Q=L.map(te=>{const qe=ee.current[te.id]??te.config,Pe={...qe,id:te.id,name:qe.name??te.name};return ee.current[te.id]=Pe,{...te,name:te.name||Pe.name||te.id,enabled:te.enabled??Pe.enabled,config:Pe}});return Object.keys(ee.current).forEach(te=>{W.has(te)||delete ee.current[te]}),Q},[]),B=i.useCallback(async({silent:L=!1}={})=>{L||u(!0);try{const W=await s.getServers(),Q=R(W);r(Q),m(te=>{var Me;return te&&Q.some(qe=>qe.id===te)?te:((Me=Q[0])==null?void 0:Me.id)??null}),P(null)}catch(W){throw P(Xe(W,"Failed to load MCP servers")),W}finally{L||u(!1)}},[R,s]),G=i.useCallback(async(L,W=!1)=>{if(!L)return[];if(!W&&c[L])return c[L];b(Q=>({...Q,[L]:!0}));try{const Q=await s.getTools(L);return p(te=>({...te,[L]:Q})),P(null),Q}catch(Q){throw P(Xe(Q,"Failed to load MCP tools")),Q}finally{b(Q=>({...Q,[L]:!1}))}},[s,c]),h=i.useCallback((L,W,Q)=>{const te=Xs(L,W);w(Me=>({...Me,[te]:Q}))},[]),y=i.useCallback(async L=>{j(!0);try{await s.addServer(L),ee.current[L.id]=L,await B()}catch(W){throw P(Xe(W,"Failed to add MCP server")),W}finally{j(!1)}},[B,s]),D=i.useCallback(async(L,W)=>{j(!0);try{const Q={...W,id:L};await s.updateServer(L,Q),ee.current[L]=Q,await B()}catch(Q){throw P(Xe(Q,"Failed to update MCP server")),Q}finally{j(!1)}},[B,s]),S=i.useCallback(async L=>{h(L,"delete",!0);try{await s.deleteServer(L),p(W=>{const Q={...W};return delete Q[L],Q}),delete ee.current[L],await B()}catch(W){throw P(Xe(W,"Failed to delete MCP server")),W}finally{h(L,"delete",!1)}},[B,s,h]),O=i.useCallback(async L=>{h(L,"connect",!0);try{await s.connectServer(L),await B({silent:!0})}catch(W){throw P(Xe(W,"Failed to connect MCP server")),W}finally{h(L,"connect",!1)}},[B,s,h]),X=i.useCallback(async L=>{h(L,"disconnect",!0);try{await s.disconnectServer(L),await B({silent:!0})}catch(W){throw P(Xe(W,"Failed to disconnect MCP server")),W}finally{h(L,"disconnect",!1)}},[B,s,h]),A=i.useCallback(async L=>{h(L,"refresh",!0);try{await s.refreshTools(L),await G(L,!0),await B({silent:!0})}catch(W){throw P(Xe(W,"Failed to refresh MCP tools")),W}finally{h(L,"refresh",!1)}},[G,B,s,h]),U=i.useCallback(async()=>{E(!0);try{const L=o.map(W=>W.id);await Promise.all(L.map(async W=>{try{await s.refreshTools(W)}catch{}})),await B(),l&&await G(l,!0)}catch(L){throw P(Xe(L,"Failed to refresh MCP status")),L}finally{E(!1)}},[G,B,l,o,s]),$=i.useCallback(L=>{m(L)},[]),oe=i.useCallback((L,W)=>!!f[Xs(L,W)],[f]),de=i.useMemo(()=>l?c[l]??[]:[],[l,c]),K=i.useMemo(()=>l?!!d[l]:!1,[l,d]);return i.useEffect(()=>{B().catch(()=>{})},[B]),i.useEffect(()=>{if(!a||n<=0)return;const L=window.setInterval(()=>{B({silent:!0}).catch(()=>{})},n);return()=>{window.clearInterval(L)}},[a,n,B]),i.useEffect(()=>{l&&G(l).catch(()=>{})},[G,l]),{servers:o,selectedServerId:l,selectedServerTools:de,isLoadingServers:v,isMutatingConfig:C,isRefreshingAll:x,isSelectedServerToolsLoading:K,error:T,setSelectedServerId:$,refreshServers:B,addServer:y,updateServer:D,deleteServer:S,connectServer:O,disconnectServer:X,refreshServerTools:A,refreshAll:U,isServerActionLoading:oe}},vr={[N.Connecting]:"blue",[N.Ready]:"green",[N.Degraded]:"orange",[N.Stopped]:"default",[N.Error]:"red"},jr=e=>e===N.Connecting||e===N.Ready||e===N.Degraded,Tr=e=>{if(!e)return;const s=e.replace(/\s+/g," ").trim();if(s)return s.length>180?`${s.slice(0,180)}...`:s},Sr=({servers:e,loading:s=!1,selectedServerId:n,onSelectServer:a,onEditServer:o,onDeleteServer:r,onConnectServer:l,onDisconnectServer:m,onRefreshTools:c,isServerActionLoading:p})=>{const{t:d}=Z(),{token:b}=fe.useToken(),f=i.useMemo(()=>({[N.Connecting]:d("settings.mcpTab.statusHelp.connecting"),[N.Ready]:d("settings.mcpTab.statusHelp.ready"),[N.Degraded]:d("settings.mcpTab.statusHelp.degraded"),[N.Stopped]:d("settings.mcpTab.statusHelp.stopped"),[N.Error]:d("settings.mcpTab.statusHelp.error")}),[d]),w=i.useMemo(()=>[{key:"name",title:d("settings.mcpServerTable.columns.name"),render:(v,u)=>u.name||u.id},{key:"transport",title:d("settings.mcpServerTable.columns.transportType"),render:(v,u)=>u.config.transport.type==="sse"?d("settings.mcpServerTable.transportOptions.sse"):d("settings.mcpServerTable.transportOptions.stdio"),width:140},{key:"status",title:d("settings.mcpServerTable.columns.status"),render:(v,u)=>{var T,P;const C=((T=u.runtime)==null?void 0:T.status)??N.Stopped,j=Tr((P=u.runtime)==null?void 0:P.last_error),x=f[C],E={[N.Connecting]:d("settings.mcpTab.status.connecting"),[N.Ready]:d("settings.mcpTab.status.ready"),[N.Degraded]:d("settings.mcpTab.status.degraded"),[N.Stopped]:d("settings.mcpTab.status.stopped"),[N.Error]:d("settings.mcpTab.status.error")};return t.jsx(ve,{title:j?`${x} ${d("settings.mcpTab.statusLastError",{error:j})}`:x,children:t.jsx(ue,{color:C===N.Stopped?void 0:vr[C],style:{marginInlineEnd:0,cursor:"help",...C===N.Stopped?{background:b.colorFillSecondary,borderColor:b.colorBorderSecondary,color:b.colorTextSecondary}:void 0},children:E[C]})})},width:120},{key:"toolCount",title:d("settings.mcpServerTable.columns.toolCount"),render:(v,u)=>{var C;return((C=u.runtime)==null?void 0:C.tool_count)??0},width:100},{key:"actions",title:d("settings.mcpServerTable.columns.actions"),width:360,render:(v,u)=>{var x;const C=((x=u.runtime)==null?void 0:x.status)??N.Stopped,j=jr(C);return t.jsxs(F,{size:b.marginXS,children:[t.jsx(z,{size:"small",onClick:E=>{E.stopPropagation(),o==null||o(u)},children:d("settings.mcpServerTable.actions.edit")}),t.jsx(os,{title:d("settings.mcpServerTable.deleteTitle"),description:d("settings.mcpServerTable.deleteDescription",{name:u.name||u.id}),onConfirm:()=>r==null?void 0:r(u),okText:d("settings.mcpServerTable.actions.delete"),okButtonProps:{danger:!0,loading:p==null?void 0:p(u.id,"delete")},children:t.jsx(z,{size:"small",danger:!0,loading:p==null?void 0:p(u.id,"delete"),onClick:E=>E.stopPropagation(),children:d("settings.mcpServerTable.actions.delete")})}),j?t.jsx(z,{size:"small",onClick:E=>{E.stopPropagation(),m==null||m(u)},loading:p==null?void 0:p(u.id,"disconnect"),children:d("settings.mcpServerTable.actions.disconnect")}):t.jsx(z,{size:"small",type:"primary",ghost:!0,onClick:E=>{E.stopPropagation(),l==null||l(u)},loading:p==null?void 0:p(u.id,"connect"),children:d("settings.mcpServerTable.actions.connect")}),t.jsx(z,{size:"small",onClick:E=>{E.stopPropagation(),c==null||c(u)},loading:p==null?void 0:p(u.id,"refresh"),children:d("settings.mcpServerTable.actions.refreshTools")})]})}}],[p,l,r,m,o,c,f,d,b.colorBorderSecondary,b.colorFillSecondary,b.colorTextSecondary,b.marginXS]);return t.jsx(et,{rowKey:"id",columns:w,dataSource:e,loading:s,pagination:!1,locale:{emptyText:d("settings.mcpServerTable.empty")},onRow:v=>({onClick:()=>a==null?void 0:a(v.id),style:{cursor:a?"pointer":"default",backgroundColor:n===v.id?b.colorFillSecondary:void 0}})})},{Text:Ys}=ie,{TextArea:_r}=q,Zs=e=>{const s=e??us(""),n=s.transport,a=n.type==="stdio"?Object.entries(n.env??{}).map(([r,l])=>({key:r,value:l})):[],o=n.type==="sse"?n.headers.map(r=>({name:r.name,value:r.value})):[];return{id:s.id,name:s.name,enabled:s.enabled,transportType:n.type,command:n.type==="stdio"?n.command:void 0,args:n.type==="stdio"?n.args:[],envEntries:a,url:n.type==="sse"?n.url:void 0,headerEntries:o,requestTimeoutMs:s.request_timeout_ms||Xt,healthcheckIntervalMs:s.healthcheck_interval_ms||Yt,allowedTools:s.allowed_tools||[],deniedTools:s.denied_tools||[]}},wr=e=>e.reduce((s,n)=>{var o;const a=(o=n.key)==null?void 0:o.trim();return a&&(s[a]=n.value??""),s},{}),kr=e=>e.filter(s=>{var n;return(n=s.name)==null?void 0:n.trim()}).map(s=>{var n;return{name:((n=s.name)==null?void 0:n.trim())||"",value:s.value??""}}),Qs=(e,s,n)=>{var d,b,f;const a=s==="edit"&&(n==null?void 0:n.id)||e.id,o=(d=e.name)==null?void 0:d.trim(),r=typeof e.requestTimeoutMs=="number"?e.requestTimeoutMs:(n==null?void 0:n.request_timeout_ms)??Xt,l=typeof e.healthcheckIntervalMs=="number"?e.healthcheckIntervalMs:(n==null?void 0:n.healthcheck_interval_ms)??Yt,m=Array.isArray(e.allowedTools)?e.allowedTools:(n==null?void 0:n.allowed_tools)??[],c=Array.isArray(e.deniedTools)?e.deniedTools:(n==null?void 0:n.denied_tools)??[],p=e.transportType==="sse"?{type:"sse",url:((b=e.url)==null?void 0:b.trim())||"",headers:kr(e.headerEntries||[]),connect_timeout_ms:(n==null?void 0:n.transport.type)==="sse"?n.transport.connect_timeout_ms??ls:ls}:{type:"stdio",command:((f=e.command)==null?void 0:f.trim())||"",args:e.args||[],env:wr(e.envEntries||[]),cwd:(n==null?void 0:n.transport.type)==="stdio"?n.transport.cwd:void 0,startup_timeout_ms:(n==null?void 0:n.transport.type)==="stdio"?n.transport.startup_timeout_ms??Ht:Ht};return{id:a,name:o||void 0,enabled:e.enabled,transport:p,request_timeout_ms:r,healthcheck_interval_ms:l,allowed_tools:m,denied_tools:c,reconnect:n==null?void 0:n.reconnect}},en=e=>JSON.stringify(e||us(""),null,2),ys=(e,s)=>{try{const n=JSON.parse(e);if(!n||typeof n!="object")return{valid:!1,error:s("settings.mcpServerForm.jsonMustBeObject")};const a=n;if(a.mcpServers&&typeof a.mcpServers=="object")return{valid:!1,error:s("settings.mcpServerForm.detectedBulkConfig")};const o=typeof a.id=="string"?a.id:"";if(!o.trim())return{valid:!1,error:s("settings.mcpServerForm.missingIdField")};if(a.transport&&typeof a.transport=="object"){const b=a;return!b.transport||typeof b.transport!="object"?{valid:!1,error:s("settings.mcpServerForm.missingTransportField")}:{valid:!0,config:b}}const r=typeof a.enabled=="boolean"?a.enabled:typeof a.disabled=="boolean"?!a.disabled:!0,l=typeof a.request_timeout_ms=="number"?a.request_timeout_ms:Xt,m=typeof a.healthcheck_interval_ms=="number"?a.healthcheck_interval_ms:Yt,c=Array.isArray(a.allowed_tools)?a.allowed_tools.filter(b=>typeof b=="string"):[],p=Array.isArray(a.denied_tools)?a.denied_tools.filter(b=>typeof b=="string"):[],d=typeof a.name=="string"?a.name:void 0;if(typeof a.url=="string"){const b=a.headers,f=Array.isArray(b)?b.map(v=>{if(!v||typeof v!="object")return null;const u=v,C=typeof u.name=="string"?u.name:"",j=typeof u.value=="string"?u.value:"";return C.trim()?{name:C,value:j}:null}).filter(v=>!!v):b&&typeof b=="object"?Object.entries(b).filter(([v])=>v.trim()).map(([v,u])=>({name:v,value:typeof u=="string"?u:""})):[],w=typeof a.connect_timeout_ms=="number"?a.connect_timeout_ms:ls;return{valid:!0,config:{id:o,name:d,enabled:r,transport:{type:"sse",url:a.url,headers:f,connect_timeout_ms:w},request_timeout_ms:l,healthcheck_interval_ms:m,allowed_tools:c,denied_tools:p,reconnect:void 0}}}if(typeof a.command=="string"){const b=Array.isArray(a.args)?a.args.filter(u=>typeof u=="string"):[],f=a.env,w=f&&typeof f=="object"?Object.entries(f).reduce((u,[C,j])=>(typeof j=="string"&&(u[C]=j),u),{}):{},v=typeof a.startup_timeout_ms=="number"?a.startup_timeout_ms:Ht;return{valid:!0,config:{id:o,name:d,enabled:r,transport:{type:"stdio",command:a.command,args:b,cwd:typeof a.cwd=="string"?a.cwd:void 0,env:w,startup_timeout_ms:v},request_timeout_ms:l,healthcheck_interval_ms:m,allowed_tools:c,denied_tools:p,reconnect:void 0}}}return{valid:!1,error:s("settings.mcpServerForm.missingTransportInfo")}}catch(n){return{valid:!1,error:s("settings.mcpServerForm.invalidJson",{message:n instanceof Error?n.message:s("settings.mcpServerForm.unknownError")})}}},Mr=({open:e,mode:s,initialConfig:n,confirmLoading:a=!1,onCancel:o,onSubmit:r})=>{const{t:l}=Z(),[m]=_.useForm(),[c,p]=i.useState("form"),[d,b]=i.useState(""),[f,w]=i.useState(null),v=i.useMemo(()=>Zs(n),[n]),u=_.useWatch("transportType",m)??"stdio";i.useEffect(()=>{e&&(m.setFieldsValue(v),b(en(n)),w(null),p("form"))},[m,v,n,e]);const C=()=>{m.resetFields(),b(""),w(null),o()},j=async()=>{if(c==="json"){const T=ys(d,l);if(!T.valid){w(T.error);return}w(null);try{await r(T.config),b("")}catch(P){console.error("MCP server JSON submission error:",P)}return}try{const T=await m.validateFields(),P=Qs(T,s,n);await r(P),m.resetFields()}catch(T){console.error("MCP server form submission error:",T)}},x=T=>{b(T),f&&ys(T,l).valid&&w(null)},E=T=>{if(T==="json")try{const P=m.getFieldsValue(),ee=Qs(P,s,n);b(JSON.stringify(ee,null,2))}catch{b(en(n))}else{const P=ys(d,l);P.valid&&m.setFieldsValue(Zs(P.config))}p(T),w(null)};return t.jsxs(ot,{title:l(s==="edit"?"settings.mcpServerForm.editTitle":"settings.mcpServerForm.addTitle"),open:e,onCancel:C,onOk:()=>{j()},okText:l("settings.mcpServerForm.save"),destroyOnClose:!0,forceRender:!0,confirmLoading:a,width:720,children:[t.jsx("div",{style:{marginBottom:16},children:t.jsxs(vt.Group,{value:c,onChange:T=>E(T.target.value),optionType:"button",buttonStyle:"solid",children:[t.jsxs(vt.Button,{value:"form",children:[t.jsx(ha,{})," ",l("settings.mcpServerForm.modeForm")]}),t.jsxs(vt.Button,{value:"json",children:[t.jsx(fa,{})," ",l("settings.mcpServerForm.modeJson")]})]})}),c==="json"&&f&&t.jsx(ke,{type:"error",message:l("settings.mcpServerForm.jsonError"),description:f,showIcon:!0,style:{marginBottom:16},closable:!0,onClose:()=>w(null)}),c==="json"?t.jsx(_r,{value:d,onChange:T=>x(T.target.value),rows:20,style:{fontFamily:"monospace",fontSize:13},placeholder:JSON.stringify(us("example-server"),null,2)}):t.jsxs(_,{layout:"vertical",form:m,preserve:!0,initialValues:v,children:[t.jsx(_.Item,{name:"id",label:l("settings.mcpServerForm.serverId"),rules:[{required:!0,message:l("settings.mcpServerForm.serverIdRequired")},{pattern:/^[a-zA-Z0-9_-]+$/,message:l("settings.mcpServerForm.serverIdPatternError")}],children:t.jsx(q,{placeholder:"filesystem",disabled:s==="edit",autoComplete:"off"})}),t.jsx(_.Item,{name:"name",label:l("settings.mcpServerForm.displayName"),children:t.jsx(q,{placeholder:"Filesystem MCP",autoComplete:"off"})}),t.jsx(_.Item,{name:"enabled",label:l("settings.mcpServerForm.enabled"),valuePropName:"checked",extra:l("settings.mcpServerForm.enabledHelp"),children:t.jsx(ge,{})}),t.jsx(_.Item,{name:"transportType",label:l("settings.mcpServerForm.transportType"),rules:[{required:!0,message:l("settings.mcpServerForm.transportTypeRequired")}],children:t.jsx(re,{options:[{label:l("settings.mcpServerForm.transportOptions.stdio"),value:"stdio"},{label:l("settings.mcpServerForm.transportOptions.sse"),value:"sse"}]})}),u==="stdio"?t.jsxs(t.Fragment,{children:[t.jsx(_.Item,{name:"command",label:l("settings.mcpServerForm.command"),rules:[{required:!0,message:l("settings.mcpServerForm.commandRequired")}],children:t.jsx(q,{placeholder:"npx",autoComplete:"off"})}),t.jsx(_.Item,{name:"args",label:l("settings.mcpServerForm.arguments"),children:t.jsx(re,{mode:"tags",tokenSeparators:[","],placeholder:l("settings.mcpServerForm.argumentsPlaceholder"),open:!1})}),t.jsx(_.List,{name:"envEntries",children:(T,{add:P,remove:ee})=>t.jsxs(F,{direction:"vertical",style:{width:"100%"},children:[t.jsxs(F,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[t.jsx(Ys,{strong:!0,children:l("settings.mcpServerForm.envVars")}),t.jsx(z,{icon:t.jsx(Ut,{}),onClick:()=>P({key:"",value:""}),type:"dashed",children:l("settings.mcpServerForm.addEnv")})]}),T.map(R=>t.jsxs(F,{align:"baseline",style:{display:"flex"},children:[t.jsx(_.Item,{...R,name:[R.name,"key"],rules:[{required:!0,message:l("settings.mcpServerForm.keyRequired")}],children:t.jsx(q,{placeholder:"MCP_ROOT",autoComplete:"off"})}),t.jsx(_.Item,{...R,name:[R.name,"value"],children:t.jsx(q,{placeholder:"/Users/me/workspace",autoComplete:"off"})}),t.jsx(z,{danger:!0,type:"text",icon:t.jsx(Hs,{}),onClick:()=>ee(R.name),"aria-label":l("settings.mcpServerForm.removeEnv","Remove environment variable")})]},R.key))]})})]}):t.jsxs(t.Fragment,{children:[t.jsx(_.Item,{name:"url",label:l("settings.mcpServerForm.sseUrl"),rules:[{required:!0,message:l("settings.mcpServerForm.sseUrlRequired")},{validator:async(T,P)=>{if(P)try{new URL(P)}catch{throw new Error(l("settings.mcpServerForm.validUrlRequired"))}}}],children:t.jsx(q,{placeholder:"http://localhost:4000/sse",autoComplete:"off"})}),t.jsx(_.List,{name:"headerEntries",children:(T,{add:P,remove:ee})=>t.jsxs(F,{direction:"vertical",style:{width:"100%"},children:[t.jsxs(F,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[t.jsx(Ys,{strong:!0,children:l("settings.mcpServerForm.headers")}),t.jsx(z,{icon:t.jsx(Ut,{}),onClick:()=>P({name:"",value:""}),type:"dashed",children:l("settings.mcpServerForm.addHeader")})]}),T.map(R=>t.jsxs(F,{align:"baseline",style:{display:"flex"},children:[t.jsx(_.Item,{...R,name:[R.name,"name"],rules:[{required:!0,message:l("settings.mcpServerForm.headerNameRequired")}],children:t.jsx(q,{placeholder:"Authorization",autoComplete:"off"})}),t.jsx(_.Item,{...R,name:[R.name,"value"],children:t.jsx(q,{placeholder:"Bearer token",autoComplete:"off"})}),t.jsx(z,{danger:!0,type:"text",icon:t.jsx(Hs,{}),onClick:()=>ee(R.name),"aria-label":l("settings.mcpServerForm.removeHeader","Remove header")})]},R.key))]})})]})]})]})},as=e=>!!e&&typeof e=="object"&&!Array.isArray(e),gt=(e,s)=>{const n=e[s];return typeof n=="string"?n:void 0},tn=(e,s)=>{const n=e[s];return typeof n=="boolean"?n:void 0},Cr=(e,s)=>{const n=e[s];return Array.isArray(n)?n:void 0},Nt=e=>{if(!as(e))return"any";const s=e.type;if(typeof s=="string"){if(s==="array"){const r=e.items;return`array<${Nt(r)}>`}return s==="object"?"object":s}if(Array.isArray(s)){const r=s.filter(l=>typeof l=="string").map(l=>l==="array"?"array<any>":l);return r.length>0?r.join(" | "):"any"}const n=Array.isArray(e.oneOf)?e.oneOf:null;if(n)return n.map(Nt).join(" | ")||"any";const a=Array.isArray(e.anyOf)?e.anyOf:null;if(a)return a.map(Nt).join(" | ")||"any";const o=Array.isArray(e.allOf)?e.allOf:null;return o&&o.map(Nt).join(" & ")||"any"},Er=e=>{if(!as(e))return null;const s=e.properties;if(!as(s))return{schemaUri:gt(e,"$schema"),title:gt(e,"title"),description:gt(e,"description"),additionalProperties:tn(e,"additionalProperties"),fields:[]};const n=new Set((Cr(e,"required")??[]).filter(o=>typeof o=="string").map(o=>o)),a=Object.entries(s).map(([o,r])=>{const l=as(r)?r:void 0;return{name:o,type:Nt(r),required:n.has(o),description:l?gt(l,"description"):void 0,defaultValue:l?l.default:void 0,enumValues:l&&Array.isArray(l.enum)?l.enum:void 0}});return a.sort((o,r)=>o.required!==r.required?o.required?-1:1:o.name.localeCompare(r.name)),{schemaUri:gt(e,"$schema"),title:gt(e,"title"),description:gt(e,"description"),additionalProperties:tn(e,"additionalProperties"),fields:a}},{Text:He}=ie,Dr=e=>e===void 0?"":e===null?"null":typeof e=="string"?e:Dn(e,0),Ir=({schema:e})=>{const{token:s}=fe.useToken(),{t:n}=Z(),a=i.useMemo(()=>Er(e),[e]);if(!a)return t.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:Dn(e,2)});const o=[{title:n("components.jsonSchema.field"),dataIndex:"name",key:"name",width:180,render:l=>t.jsx(He,{code:!0,children:l})},{title:n("components.jsonSchema.type"),dataIndex:"type",key:"type",width:140,render:l=>t.jsx(He,{children:l})},{title:n("components.jsonSchema.required"),dataIndex:"required",key:"required",width:110,render:l=>l?t.jsx(He,{strong:!0,style:{color:s.colorError},children:n("components.jsonSchema.yes")}):t.jsx(He,{type:"secondary",children:n("components.jsonSchema.no")})},{title:n("components.jsonSchema.default"),dataIndex:"defaultValue",key:"default",width:160,render:l=>l===void 0?t.jsx(He,{type:"secondary",children:"-"}):t.jsx(He,{children:Dr(l)})},{title:n("components.jsonSchema.description"),dataIndex:"description",key:"description",render:l=>l?t.jsx(He,{style:{whiteSpace:"pre-wrap"},children:l}):t.jsx(He,{type:"secondary",children:"-"})}],r=(a.fields??[]).map(l=>({...l,key:l.name}));return t.jsxs("div",{style:{width:"100%"},children:[t.jsx(we,{size:"small",column:1,items:[a.schemaUri?{key:"schema",label:"$schema",children:t.jsx(He,{code:!0,children:a.schemaUri})}:null,typeof a.additionalProperties=="boolean"?{key:"additionalProperties",label:"additionalProperties",children:t.jsx(He,{children:a.additionalProperties?"true":"false"})}:null].filter(Boolean)}),t.jsx(et,{size:"small",pagination:!1,columns:o,dataSource:r,locale:{emptyText:n("components.jsonSchema.noProperties")},style:{marginTop:s.marginSM}})]})},{Text:It}=ie,Pr=(e,s)=>`mcp__${e}__${s}`,Fr=({server:e,tools:s,loading:n=!1})=>{const{t:a}=Z();return t.jsx(I,{title:a("settings.mcpToolList.title"),size:"small",children:e?t.jsx(We,{loading:n,dataSource:s,locale:{emptyText:a("settings.mcpToolList.empty")},renderItem:o=>{const r=Pr(o.server_id,o.original_name);return t.jsx(We.Item,{children:t.jsxs(F,{direction:"vertical",size:2,style:{width:"100%"},children:[t.jsx(It,{strong:!0,children:o.original_name}),t.jsx(It,{type:"secondary",children:o.description||a("settings.mcpToolList.noDescription")}),t.jsx(It,{code:!0,children:o.alias}),t.jsxs(It,{type:"secondary",children:[a("settings.mcpToolList.aliasMapping"),": ",t.jsx(It,{code:!0,children:r})]}),o.parameters!==void 0&&t.jsx(Ds,{size:"small",items:[{key:"schema",label:a("settings.mcpToolList.parametersSchema"),children:t.jsx(Ir,{schema:o.parameters})}]})]})})}}):t.jsx(Le,{image:Le.PRESENTED_IMAGE_SIMPLE,description:a("settings.mcpToolList.selectServerHint")})})},{Text:Pt}=ie,{useToken:Rr}=fe,{TextArea:Ar}=q,sn={[N.Connecting]:"processing",[N.Ready]:"success",[N.Degraded]:"warning",[N.Stopped]:"default",[N.Error]:"error"},Lr=()=>({[N.Connecting]:0,[N.Ready]:0,[N.Degraded]:0,[N.Stopped]:0,[N.Error]:0}),mt=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,zr=e=>{var n,a,o;const s={};for(const r of e){const l=(n=r.id)==null?void 0:n.trim();if(!l)continue;const c=!(r.enabled??r.config.enabled),p=r.config.transport;if(p.type==="sse"){const b={};for(const w of p.headers??[]){const v=(a=w.name)==null?void 0:a.trim();v&&(b[v]=w.value??"")}const f={url:p.url};c&&(f.disabled=!0),Object.keys(b).length&&(f.headers=b),s[l]=f;continue}const d={command:p.command};c&&(d.disabled=!0),(o=p.args)!=null&&o.length&&(d.args=p.args),p.cwd&&(d.cwd=p.cwd),p.env&&Object.keys(p.env).length&&(d.env=p.env),s[l]=d}return{mcpServers:s}},Or=()=>{const{t:e}=Z(),{token:s}=Rr(),[n,a]=Tt.useMessage(),{servers:o,selectedServerId:r,selectedServerTools:l,isLoadingServers:m,isMutatingConfig:c,isRefreshingAll:p,isSelectedServerToolsLoading:d,error:b,setSelectedServerId:f,addServer:w,updateServer:v,deleteServer:u,connectServer:C,disconnectServer:j,refreshServerTools:x,refreshAll:E,isServerActionLoading:T}=br(),P=i.useMemo(()=>({[N.Connecting]:e("settings.mcpTab.status.connecting"),[N.Ready]:e("settings.mcpTab.status.ready"),[N.Degraded]:e("settings.mcpTab.status.degraded"),[N.Stopped]:e("settings.mcpTab.status.stopped"),[N.Error]:e("settings.mcpTab.status.error")}),[e]),ee=i.useMemo(()=>({[N.Connecting]:e("settings.mcpTab.statusHelp.connecting"),[N.Ready]:e("settings.mcpTab.statusHelp.ready"),[N.Degraded]:e("settings.mcpTab.statusHelp.degraded"),[N.Stopped]:e("settings.mcpTab.statusHelp.stopped"),[N.Error]:e("settings.mcpTab.statusHelp.error")}),[e]),[R,B]=i.useState(!1),[G,h]=i.useState("create"),[y,D]=i.useState(null),[S,O]=i.useState(!1),[X,A]=i.useState("merge"),[U,$]=i.useState(""),[oe,de]=i.useState(null),[K,L]=i.useState(!1),W=i.useMemo(()=>r?o.find(g=>g.id===r)??null:null,[r,o]),Q=i.useMemo(()=>{const g=Lr();let se=0;return o.forEach(le=>{var me,Ee;const Ce=((me=le.runtime)==null?void 0:me.status)??N.Stopped;g[Ce]+=1,se+=((Ee=le.runtime)==null?void 0:Ee.tool_count)??0}),{byStatus:g,totalServers:o.length,totalTools:se}},[o]),te={background:s.colorFillSecondary,borderColor:s.colorBorderSecondary,color:s.colorTextSecondary},Me=async g=>{try{await u(g.id),n.success(e("settings.mcpTab.serverDeleted"))}catch(se){n.error(mt(se,e("settings.mcpTab.deleteServerFailed")))}},qe=async g=>{try{await C(g.id),n.success(e("settings.mcpTab.connectedTo",{name:g.name||g.id}))}catch(se){n.error(mt(se,e("settings.mcpTab.connectServerFailed")))}},Pe=async g=>{try{await j(g.id),n.success(e("settings.mcpTab.disconnected",{name:g.name||g.id}))}catch(se){n.error(mt(se,e("settings.mcpTab.disconnectServerFailed")))}},kt=async g=>{try{await x(g.id),n.success(e("settings.mcpTab.toolsRefreshedFor",{name:g.name||g.id}))}catch(se){n.error(mt(se,e("settings.mcpTab.refreshToolsFailed")))}},ft=async()=>{try{await E(),n.success(e("settings.mcpTab.statusRefreshed"))}catch(g){n.error(mt(g,e("settings.mcpTab.refreshStatusFailed")))}},Mt=()=>{D(null),h("create"),B(!0)},Ct=g=>{D(g),h("edit"),B(!0)},it=async g=>{try{if(G==="edit"){if(!y){n.error(e("settings.mcpTab.noServerForEditing"));return}await v(y.id,g),n.success(e("settings.mcpTab.savedServer",{name:y.name||y.id}))}else await w(g),n.success(e("settings.mcpTab.addedServer",{name:g.name||g.id}));B(!1),D(null)}catch(se){n.error(mt(se,e("settings.mcpTab.saveServerFailed")))}},lt=()=>{O(!0),de(null),A("merge"),$("")},ze=async()=>{const g=zr(o),se=JSON.stringify(g,null,2);try{await In(se),n.success(e("settings.mcpTab.copiedConfig"))}catch{O(!0),de(null),A("merge"),$(se),n.warning(e("settings.mcpTab.clipboardUnavailable"))}},Et=async()=>{var Ce;de(null);let g;try{g=JSON.parse(U)}catch(me){de(`${e("settings.mcpTab.invalidJsonPrefix")}: ${me instanceof Error?me.message:e("settings.mcpTab.unknownError")}`);return}if(!g||typeof g!="object"){de(e("settings.mcpTab.jsonMustBeObject"));return}const le=g.mcpServers;if(!le||typeof le!="object"){de(e("settings.mcpTab.missingMcpServers"));return}L(!0);try{const me=await Rn.importServers({mcpServers:le,mode:X}),Ee=((Ce=me.start_errors)==null?void 0:Ce.length)??0;n.success(e("settings.mcpTab.importSummary",{count:me.server_ids.length,added:me.added,updated:me.updated,removed:me.removed,failed:Ee})),Ee&&n.warning(e("settings.mcpTab.importStartFailures")),O(!1),$(""),await ft()}catch(me){de(mt(me,e("settings.mcpTab.importFailed")))}finally{L(!1)}};return t.jsxs(F,{direction:"vertical",size:s.marginMD,style:{width:"100%"},children:[a,b?t.jsx(ke,{type:"error",showIcon:!0,message:b}):null,t.jsx(I,{size:"small",title:e("settings.mcpTab.overviewTitle"),children:t.jsxs(F,{direction:"vertical",size:s.marginXS,style:{width:"100%"},children:[t.jsx(Pt,{type:"secondary",children:e("settings.mcpTab.overviewDescription")}),t.jsxs(F,{wrap:!0,children:[t.jsx(ue,{style:te,children:e("settings.mcpTab.totalServers",{count:Q.totalServers})}),t.jsx(ue,{style:te,children:e("settings.mcpTab.totalTools",{count:Q.totalTools})}),Object.values(N).map(g=>t.jsx(ve,{title:ee[g],children:t.jsxs(ue,{color:g===N.Stopped?void 0:sn[g],style:{cursor:"help",...g===N.Stopped?te:void 0},children:[P[g],": ",Q.byStatus[g]]})},g))]}),t.jsx(Pt,{type:"secondary",children:e("settings.mcpTab.statusGuideTitle")}),t.jsx(F,{direction:"vertical",size:2,style:{width:"100%"},children:Object.values(N).map(g=>t.jsxs(Pt,{type:"secondary",children:[t.jsx(ue,{color:g===N.Stopped?void 0:sn[g],style:{marginInlineEnd:8,...g===N.Stopped?te:void 0},children:P[g]}),ee[g]]},`guide-${g}`))})]})}),t.jsx(I,{size:"small",title:e("settings.mcpTab.serversTitle"),extra:t.jsxs(F,{children:[t.jsx(z,{type:"primary",onClick:Mt,children:e("settings.mcpTab.addServer")}),t.jsx(z,{icon:t.jsx(St,{}),loading:p,onClick:()=>{ft()},children:e("settings.mcpTab.refreshAll")}),t.jsx(z,{icon:t.jsx(Pn,{}),onClick:()=>void ze(),children:e("settings.mcpTab.export")}),t.jsx(z,{icon:t.jsx(ya,{}),onClick:lt,children:e("settings.mcpTab.import")})]}),children:t.jsx(Sr,{servers:o,loading:m,selectedServerId:r,onSelectServer:f,onEditServer:Ct,onDeleteServer:Me,onConnectServer:qe,onDisconnectServer:Pe,onRefreshTools:kt,isServerActionLoading:T})}),t.jsx(Fr,{server:W,tools:l,loading:d}),t.jsx(Mr,{open:R,mode:G,initialConfig:(y==null?void 0:y.config)??null,confirmLoading:c,onCancel:()=>{c||(B(!1),D(null))},onSubmit:g=>void it(g)}),t.jsx(ot,{open:S,title:e("settings.mcpTab.importModalTitle"),okText:e("settings.mcpTab.import"),onOk:()=>void Et(),okButtonProps:{loading:K},onCancel:()=>{K||(O(!1),de(null))},width:800,destroyOnClose:!1,children:t.jsxs(F,{direction:"vertical",style:{width:"100%"},size:"middle",children:[t.jsxs(Pt,{type:"secondary",children:[e("settings.mcpTab.importHint"),t.jsx("br",{}),t.jsx(Pt,{code:!0,children:'{ "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "..."] } } }'})]}),t.jsxs(vt.Group,{value:X,onChange:g=>A(g.target.value),optionType:"button",buttonStyle:"solid",children:[t.jsx(vt.Button,{value:"merge",children:e("settings.mcpTab.importModeMerge")}),t.jsx(vt.Button,{value:"replace",children:e("settings.mcpTab.importModeReplace")})]}),X==="replace"?t.jsx(ke,{type:"warning",showIcon:!0,message:e("settings.mcpTab.replaceWarning")}):null,oe?t.jsx(ke,{type:"error",showIcon:!0,message:oe}):null,t.jsx(Ar,{value:U,onChange:g=>$(g.target.value),rows:14,placeholder:'{"mcpServers": { "filesystem": { "command": "...", "args": [], "env": {} } }}',spellCheck:!1})]})})]})},Ne=e=>{const s=new URLSearchParams;Object.entries(e).forEach(([a,o])=>{o===void 0||o===""||s.set(a,String(o))});const n=s.toString();return n?`?${n}`:""};class Nr{async getSummary(s={}){const n=Ne({start_date:s.startDate,end_date:s.endDate});return pe.get(`metrics/summary${n}`)}async getByModel(s={}){const n=Ne({start_date:s.startDate,end_date:s.endDate});return pe.get(`metrics/by-model${n}`)}async getSessions(s={}){const n=Ne({start_date:s.startDate,end_date:s.endDate,model:s.model,limit:s.limit});return pe.get(`metrics/sessions${n}`)}async getSessionDetail(s){try{return await pe.get(`metrics/sessions/${encodeURIComponent(s)}`)}catch(n){if(n instanceof Error&&n.message.includes("not found"))return null;throw n}}async getUsageBreakdown(s={}){const n=Ne({start_date:s.startDate,end_date:s.endDate,model:s.model});return pe.get(`metrics/usage-breakdown${n}`)}async getDaily(s={}){const n=Ne({days:s.days,end_date:s.endDate,granularity:s.granularity});return pe.get(`metrics/daily${n}`)}async getForwardSummary(s={}){const n=Ne({start_date:s.startDate,end_date:s.endDate,endpoint:s.endpoint,model:s.model,limit:s.limit});return pe.get(`metrics/forward/summary${n}`)}async getForwardByEndpoint(s={}){const n=Ne({start_date:s.startDate,end_date:s.endDate,endpoint:s.endpoint,model:s.model,limit:s.limit});return pe.get(`metrics/forward/by-endpoint${n}`)}async getForwardRequests(s={}){const n=Ne({start_date:s.startDate,end_date:s.endDate,endpoint:s.endpoint,model:s.model,limit:s.limit});return pe.get(`metrics/forward/requests${n}`)}async getMemorySummary(s={}){const n=Ne({scope:s.scope,project_key:s.projectKey});return pe.get(`metrics/memory/summary${n}`)}async getMemoryTimeline(s={}){const n=Ne({scope:s.scope,project_key:s.projectKey,days:s.days,end_date:s.endDate,granularity:s.granularity});return pe.get(`metrics/memory/timeline${n}`)}async getUnifiedSummary(s={}){const n=Ne({start_date:s.startDate,end_date:s.endDate});return pe.get(`metrics/v2/summary${n}`)}async getUnifiedTimeline(s={}){const n=Ne({days:s.days,end_date:s.endDate,granularity:s.granularity});return pe.get(`metrics/v2/timeline${n}`)}}const $t=new Nr,An=1,$r=365,Ln=e=>Number.isFinite(e)?Math.min($r,Math.max(An,Math.floor(e??30))):30,xs=e=>{if(!e)return null;const s=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!s)return null;const n=Number(s[1]),a=Number(s[2]),o=Number(s[3]),r=new Date(Date.UTC(n,a-1,o));return r.getUTCFullYear()!==n||r.getUTCMonth()!==a-1||r.getUTCDate()!==o?null:r},Ft=e=>e.toISOString().slice(0,10),Vr=(e,s)=>{const n=new Date(e.getTime());return n.setUTCDate(n.getUTCDate()+s),n},Br=(e,s)=>{const n=s.getTime()-e.getTime(),a=Math.floor(n/864e5)+1;return Ln(a)},Rs=(e,s=new Date)=>{const n=Ln(e.days),a=Ft(s),o=xs(e.endDate)??xs(a);if(!o)return{startDate:a,endDate:a,days:An};const r=xs(e.startDate);if(r){const m=o<r?r:o;return{startDate:Ft(r),endDate:Ft(m),days:Br(r,m)}}const l=Vr(o,-(n-1));return{startDate:Ft(l),endDate:Ft(o),days:n}},qr=15e3,Ur=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,Hr=(e={})=>{const{filters:s,autoRefreshMs:n=qr}=e,a=i.useMemo(()=>({startDate:s==null?void 0:s.startDate,endDate:s==null?void 0:s.endDate,days:(s==null?void 0:s.days)??30,endpoint:s==null?void 0:s.endpoint,model:s==null?void 0:s.model,limit:(s==null?void 0:s.limit)??100}),[s==null?void 0:s.startDate,s==null?void 0:s.endDate,s==null?void 0:s.days,s==null?void 0:s.endpoint,s==null?void 0:s.model,s==null?void 0:s.limit]),o=i.useMemo(()=>Rs({startDate:a.startDate,endDate:a.endDate,days:a.days}),[a.days,a.endDate,a.startDate]),[r,l]=i.useState(null),[m,c]=i.useState([]),[p,d]=i.useState([]),[b,f]=i.useState(!1),[w,v]=i.useState(!1),[u,C]=i.useState(null),j=i.useCallback(async E=>{E?f(!0):v(!0);try{const T={startDate:o.startDate,endDate:o.endDate,endpoint:a.endpoint,model:a.model,limit:a.limit},[P,ee,R]=await Promise.all([$t.getForwardSummary(T),$t.getForwardByEndpoint(T),$t.getForwardRequests(T)]);l(P),c(ee),d(R),C(null)}catch(T){C(Ur(T,"Failed to load forward metrics"))}finally{E?f(!1):v(!1)}},[a.endpoint,a.model,a.limit,o.endDate,o.startDate]),x=i.useCallback(async()=>{await j(!1)},[j]);return i.useEffect(()=>{j(!0)},[j]),i.useEffect(()=>{if(n<=0)return;const E=window.setInterval(()=>{j(!1)},n);return()=>{window.clearInterval(E)}},[n,j]),{summary:r,endpointMetrics:m,requests:p,isLoading:b,isRefreshing:w,error:u,refresh:x}},Kr=15e3,nn=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,Wr=(e={})=>{const{filters:s,autoRefreshMs:n=Kr,service:a=$t}=e,o=i.useMemo(()=>({startDate:s==null?void 0:s.startDate,endDate:s==null?void 0:s.endDate,model:s==null?void 0:s.model,days:(s==null?void 0:s.days)??30,granularity:(s==null?void 0:s.granularity)??"daily",sessionLimit:(s==null?void 0:s.sessionLimit)??200}),[s==null?void 0:s.startDate,s==null?void 0:s.endDate,s==null?void 0:s.model,s==null?void 0:s.days,s==null?void 0:s.granularity,s==null?void 0:s.sessionLimit]),r=i.useMemo(()=>Rs({startDate:o.startDate,endDate:o.endDate,days:o.days}),[o.days,o.endDate,o.startDate]),[l,m]=i.useState(null),[c,p]=i.useState([]),[d,b]=i.useState([]),[f,w]=i.useState([]),[v,u]=i.useState(null),[C,j]=i.useState([]),[x,E]=i.useState(null),[T,P]=i.useState(!1),[ee,R]=i.useState(!1),[B,G]=i.useState(!1),[h,y]=i.useState(null),D=i.useCallback(async A=>{A?R(!0):G(!0);try{const U=a.getMemorySummary?a.getMemorySummary().catch(()=>null):Promise.resolve(null),$=a.getMemoryTimeline?a.getMemoryTimeline({days:r.days,endDate:r.endDate,granularity:o.granularity}).catch(()=>[]):Promise.resolve([]),[oe,de,K,L,W,Q]=await Promise.all([a.getSummary({startDate:r.startDate,endDate:r.endDate}),a.getByModel({startDate:r.startDate,endDate:r.endDate}),a.getSessions({startDate:r.startDate,endDate:r.endDate,model:o.model,limit:o.sessionLimit}),a.getDaily({days:r.days,endDate:r.endDate,granularity:o.granularity}),U,$]);m(oe),p(de),b(K),w(L),u(W),j(Q),y(null)}catch(U){y(nn(U,"Failed to load metrics"))}finally{A?R(!1):G(!1)}},[o.granularity,o.model,o.sessionLimit,r.days,r.endDate,r.startDate,a]),S=i.useCallback(async()=>{await D(!1)},[D]),O=i.useCallback(async A=>{P(!0);try{const U=await a.getSessionDetail(A);E(U)}catch(U){y(nn(U,"Failed to load session detail"))}finally{P(!1)}},[a]),X=i.useCallback(()=>{E(null)},[]);return i.useEffect(()=>{D(!0)},[D]),i.useEffect(()=>{if(n<=0)return;const A=window.setInterval(()=>{D(!1)},n);return()=>{window.clearInterval(A)}},[n,D]),{summary:l,modelMetrics:c,sessions:d,timeline:f,memorySummary:v,memoryTimeline:C,sessionDetail:x,isLoading:ee,isRefreshing:B,isSessionDetailLoading:T,error:h,refresh:S,loadSessionDetail:O,clearSessionDetail:X}},Gr=15e3,Jr=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,Xr=(e={})=>{const{filters:s,autoRefreshMs:n=Gr}=e,a=i.useMemo(()=>({startDate:s==null?void 0:s.startDate,endDate:s==null?void 0:s.endDate,days:(s==null?void 0:s.days)??30,model:s==null?void 0:s.model}),[s==null?void 0:s.days,s==null?void 0:s.endDate,s==null?void 0:s.model,s==null?void 0:s.startDate]),o=i.useMemo(()=>Rs({startDate:a.startDate,endDate:a.endDate,days:a.days}),[a.days,a.endDate,a.startDate]),[r,l]=i.useState(null),[m,c]=i.useState(!1),[p,d]=i.useState(!1),[b,f]=i.useState(null),w=i.useCallback(async u=>{u?c(!0):d(!0);try{const C=await $t.getUsageBreakdown({startDate:o.startDate,endDate:o.endDate,model:a.model});l(C),f(null)}catch(C){f(Jr(C,"Failed to load usage breakdown"))}finally{u?c(!1):d(!1)}},[a.model,o.endDate,o.startDate]),v=i.useCallback(async()=>{await w(!1)},[w]);return i.useEffect(()=>{w(!0)},[w]),i.useEffect(()=>{if(n<=0)return;const u=window.setInterval(()=>{w(!1)},n);return()=>{window.clearInterval(u)}},[n,w]),{data:r,isLoading:m,isRefreshing:p,error:b,refresh:v}},{useToken:Yr}=fe,Zr=({data:e,loading:s})=>{const{t:n}=Z(),{token:a}=Yr();if(s)return t.jsx(I,{size:"small",className:"lotus-metric-card",title:n("settings.charts.endpointDistribution"),children:t.jsx("div",{style:{width:"100%",height:240},children:t.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100%",color:a.colorTextSecondary},children:n("settings.common.loading")})})});if(e.length===0)return t.jsx(I,{size:"small",className:"lotus-metric-card",title:n("settings.charts.endpointDistribution"),children:t.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:240,color:a.colorTextSecondary},children:n("settings.charts.noForwardMetrics")})});const o=e.map(r=>({endpoint:r.endpoint.split(".").pop()||r.endpoint,requests:r.requests,successful:r.successful,failed:r.failed}));return t.jsx(I,{size:"small",className:"lotus-metric-card",title:n("settings.charts.endpointDistribution"),children:t.jsx("div",{style:{width:"100%",height:240},children:t.jsx(_t,{children:t.jsxs(Ps,{data:o,children:[t.jsx(Wt,{strokeDasharray:"3 3"}),t.jsx(Gt,{dataKey:"endpoint"}),t.jsx(Jt,{}),t.jsx(wt,{formatter:(r,l)=>[`${r}`,l.charAt(0).toUpperCase()+l.slice(1)]}),t.jsx(Fs,{}),t.jsx(is,{dataKey:"successful",fill:"var(--lotus-chart-secondary)",name:n("settings.common.successful"),fillOpacity:.9,radius:[4,4,0,0]}),t.jsx(is,{dataKey:"failed",fill:"var(--lotus-chart-danger)",name:n("settings.common.failed"),fillOpacity:.9,radius:[4,4,0,0]})]})})})})},{useToken:Qr}=fe,eo=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),n=Math.floor(s/60),a=s%60;if(n>=60){const o=Math.floor(n/60),r=n%60;return`${o}h ${r}m`}return n>0?`${n}m ${a}s`:`${a}s`},an=({summary:e,loading:s})=>{const{t:n}=Z(),{token:a}=Qr();if(s)return t.jsx(tt,{active:!0,paragraph:{rows:1}});const o=e&&e.total_requests>0?(e.successful_requests/e.total_requests*100).toFixed(1):"0.0";return t.jsxs(Ve,{gutter:[a.marginSM,a.marginSM],children:[t.jsx(ae,{xs:24,sm:12,xl:6,children:t.jsx(I,{size:"small",className:"lotus-metric-card",children:t.jsx(ye,{title:n("settings.forwardMetricsCards.totalForwardRequests"),value:(e==null?void 0:e.total_requests)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),t.jsx(ae,{xs:24,sm:12,xl:6,children:t.jsx(I,{size:"small",className:"lotus-metric-card",children:t.jsx(ye,{title:n("settings.forwardMetricsCards.successRate"),value:o,suffix:"%",valueStyle:{color:Number(o)>=95?"var(--lotus-chart-secondary)":Number(o)>=80?"var(--lotus-chart-accent)":"var(--lotus-chart-danger)"}})})}),t.jsx(ae,{xs:24,sm:12,xl:6,children:t.jsx(I,{size:"small",className:"lotus-metric-card",children:t.jsx(ye,{title:n("settings.forwardMetricsCards.forwardTokens"),value:(e==null?void 0:e.total_tokens.total_tokens)??0,precision:0,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})}),t.jsx(ae,{xs:24,sm:12,xl:6,children:t.jsx(I,{size:"small",className:"lotus-metric-card",children:t.jsx(ye,{title:n("settings.forwardMetricsCards.avgResponseTime"),value:eo(e==null?void 0:e.avg_duration_ms),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:pt}=ie,to=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),n=Math.floor(s/60),a=s%60;return n>0?`${n}m ${a}s`:`${a}s`},so=e=>new Date(e).toLocaleString(),no=({requests:e,loading:s})=>{const{t:n}=Z(),a=[{title:n("settings.metricsTable.forward.columns.id"),dataIndex:"forward_id",key:"forward_id",width:120,render:o=>t.jsxs(pt,{style:{fontSize:12},copyable:!0,children:[o.slice(0,8),"..."]})},{title:n("settings.metricsTable.forward.columns.endpoint"),dataIndex:"endpoint",key:"endpoint",width:150,render:o=>t.jsx(ue,{color:"processing",children:o.split(".").pop()||o})},{title:n("settings.metricsTable.forward.columns.model"),dataIndex:"model",key:"model",width:120},{title:n("settings.metricsTable.forward.columns.type"),dataIndex:"is_stream",key:"is_stream",width:80,render:o=>t.jsx(ue,{color:o?"purple":"processing",children:n(o?"settings.metricsTable.forward.typeStream":"settings.metricsTable.forward.typeSync")})},{title:n("settings.metricsTable.forward.columns.status"),key:"status",width:100,render:(o,r)=>{const l=r.status==="success"?"success":r.status==="error"?"error":"default";return t.jsx(xa,{status:l,text:r.status_code?t.jsxs("span",{children:[r.status,t.jsxs(pt,{type:"secondary",style:{marginLeft:4},children:["(",r.status_code,")"]})]}):r.status||"-"})}},{title:n("settings.metricsTable.forward.columns.tokens"),key:"tokens",width:100,render:(o,r)=>r.token_usage?t.jsx(pt,{children:r.token_usage.total_tokens.toLocaleString()}):t.jsx(pt,{type:"secondary",children:"-"})},{title:n("settings.metricsTable.forward.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",width:100,render:o=>to(o)},{title:n("settings.metricsTable.forward.columns.started"),dataIndex:"started_at",key:"started_at",width:160,render:o=>t.jsx(pt,{type:"secondary",style:{fontSize:12},children:so(o)})},{title:n("settings.metricsTable.forward.columns.error"),dataIndex:"error",key:"error",width:200,render:o=>o?t.jsx(pt,{type:"danger",ellipsis:!0,style:{maxWidth:180},children:o}):t.jsx(pt,{type:"secondary",children:"-"})}];return t.jsx(et,{rowKey:"forward_id",className:"lotus-metric-table",columns:a,dataSource:e,loading:s,size:"small",pagination:{pageSize:10,showSizeChanger:!0,showTotal:o=>n("settings.metricsTable.forward.totalRequests",{total:o}),pageSizeOptions:["10","20","50","100"]},scroll:{x:1200},locale:{emptyText:n("settings.metricsTable.forward.empty")}})},{useToken:ao}=fe,ro=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString()},rn=({summary:e,loading:s})=>{const{t:n}=Z(),{token:a}=ao();return s?t.jsx(tt,{active:!0,paragraph:{rows:1}}):t.jsxs(Ve,{gutter:[a.marginSM,a.marginSM],children:[t.jsx(ae,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(I,{size:"small",className:"lotus-metric-card",children:t.jsx(ye,{title:n("settings.unifiedMetricsCards.totalMemories"),value:(e==null?void 0:e.total_memories)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),t.jsx(ae,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(I,{size:"small",className:"lotus-metric-card",children:t.jsx(ye,{title:n("settings.unifiedMetricsCards.staleCandidates"),value:(e==null?void 0:e.stale_candidate_count)??0,precision:0,valueStyle:{color:((e==null?void 0:e.stale_candidate_count)??0)>0?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)"}})})}),t.jsx(ae,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(I,{size:"small",className:"lotus-metric-card",children:t.jsx(ye,{title:n("settings.unifiedMetricsCards.memoryProjects"),value:(e==null?void 0:e.project_count)??0,precision:0,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),t.jsx(ae,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(I,{size:"small",className:"lotus-metric-card",children:t.jsx(ye,{title:n("settings.unifiedMetricsCards.lastReindex"),value:ro(e==null?void 0:e.last_reindex_at),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:oo}=ie,io=({data:e,loading:s})=>{const{t:n}=Z();return s?t.jsx(I,{size:"small",className:"lotus-metric-card",title:n("settings.charts.memoryTrendTitle"),children:t.jsx(tt,{active:!0,paragraph:{rows:5}})}):t.jsx(I,{size:"small",className:"lotus-metric-card",title:n("settings.charts.memoryTrendTitle"),children:e.length===0?t.jsx(Le,{image:Le.PRESENTED_IMAGE_SIMPLE,description:n("settings.charts.noMemoryTrend")}):t.jsxs(t.Fragment,{children:[t.jsx(oo,{type:"secondary",children:n("settings.charts.memoryTrendDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(_t,{children:t.jsxs(Fn,{data:e,children:[t.jsx(Wt,{strokeDasharray:"3 3"}),t.jsx(Gt,{dataKey:"label",minTickGap:24}),t.jsx(Jt,{allowDecimals:!1}),t.jsx(wt,{}),t.jsx(Fs,{}),t.jsx(jt,{type:"monotone",dataKey:"total_memories",name:n("settings.charts.totalMemories"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),t.jsx(jt,{type:"monotone",dataKey:"created_memories",name:n("settings.charts.createdMemories"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),t.jsx(jt,{type:"monotone",dataKey:"updated_memories",name:n("settings.charts.updatedMemories"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{useToken:lo}=fe,co=e=>{const s=Math.floor(e/1e3),n=Math.floor(s/60),a=s%60;return n>0?`${n}m ${a}s`:`${a}s`},uo=e=>{const s=e.filter(a=>typeof a.duration_ms=="number"&&a.duration_ms>0);if(s.length===0)return 0;const n=s.reduce((a,o)=>a+(o.duration_ms??0),0);return Math.floor(n/s.length)},on=({summary:e,sessions:s,loading:n})=>{const{t:a}=Z(),{token:o}=lo();if(n)return t.jsx(tt,{active:!0,paragraph:{rows:1}});const r=uo(s);return t.jsxs(Ve,{gutter:[o.marginSM,o.marginSM],children:[t.jsx(ae,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(I,{size:"small",className:"lotus-metric-card",children:t.jsx(ye,{title:a("settings.metricsCards.syncMismatches",{defaultValue:"Sync Mismatches"}),value:(e==null?void 0:e.total_sync_mismatches)??0,precision:0,valueStyle:{color:((e==null?void 0:e.total_sync_mismatches)??0)>0?"var(--lotus-chart-danger)":"var(--lotus-chart-secondary)"}})})}),t.jsx(ae,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(I,{size:"small",className:"lotus-metric-card",children:t.jsx(ye,{title:a("settings.metricsCards.totalSessions"),value:(e==null?void 0:e.total_sessions)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),t.jsx(ae,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(I,{size:"small",className:"lotus-metric-card",children:t.jsx(ye,{title:a("settings.metricsCards.chatTokens"),value:(e==null?void 0:e.total_tokens.total_tokens)??0,precision:0,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})}),t.jsx(ae,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(I,{size:"small",className:"lotus-metric-card",children:t.jsx(ye,{title:a("settings.metricsCards.totalToolCalls"),value:(e==null?void 0:e.total_tool_calls)??0,precision:0,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),t.jsx(ae,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(I,{size:"small",className:"lotus-metric-card",children:t.jsx(ye,{title:a("settings.metricsCards.avgSessionDuration"),value:r>0?co(r):"-",valueStyle:{color:"var(--lotus-chart-accent)"}})})})]})},{Text:go}=ie,ln=["var(--lotus-chart-primary)","var(--lotus-chart-secondary)","var(--lotus-chart-accent)","var(--lotus-chart-purple)","var(--lotus-chart-cyan)"],mo=({data:e,loading:s})=>{const{t:n}=Z();if(s)return t.jsx(I,{size:"small",className:"lotus-metric-card",title:n("settings.charts.modelDistribution"),children:t.jsx(tt,{active:!0,paragraph:{rows:5}})});const a=e.map(o=>({name:o.model,value:o.tokens.total_tokens}));return t.jsx(I,{size:"small",className:"lotus-metric-card",title:n("settings.charts.modelDistribution"),children:a.length===0?t.jsx(Le,{image:Le.PRESENTED_IMAGE_SIMPLE,description:n("settings.charts.noModelMetrics")}):t.jsxs(t.Fragment,{children:[t.jsx(go,{type:"secondary",children:n("settings.charts.modelDistributionDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(_t,{children:t.jsxs(Ca,{children:[t.jsx(Ea,{data:a,cx:"50%",cy:"50%",outerRadius:90,fill:"var(--lotus-chart-primary)",dataKey:"value",nameKey:"name",label:!0,children:a.map((o,r)=>t.jsx(Da,{fill:ln[r%ln.length]},`${o.name}-${r}`))}),t.jsx(wt,{})]})})})]})})},po=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?"-":s.toLocaleString()},ho=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),n=Math.floor(s/60),a=s%60;if(n>=60){const o=Math.floor(n/60),r=n%60;return`${o}h ${r}m`}return n>0?`${n}m ${a}s`:`${a}s`},fo=e=>{switch(e){case"completed":return"success";case"running":return"processing";case"awaiting_response":return"gold";case"error":return"error";case"cancelled":return"warning";default:return"default"}},yo=(e,s)=>{switch(e){case"awaiting_response":return s("settings.metricsTable.session.status.awaitingResponse",{defaultValue:"Awaiting Response"});case"running":return s("settings.metricsTable.session.status.running",{defaultValue:"Running"});case"completed":return s("settings.metricsTable.session.status.completed",{defaultValue:"Completed"});case"error":return s("settings.metricsTable.session.status.error",{defaultValue:"Error"});case"cancelled":return s("settings.metricsTable.session.status.cancelled",{defaultValue:"Cancelled"});default:return e}},xo=({sessions:e,loading:s,onSelectSession:n})=>{const{t:a}=Z(),o=[{title:a("settings.metricsTable.session.columns.session"),dataIndex:"session_id",key:"session_id",render:r=>t.jsx(ve,{title:r,children:t.jsxs("span",{children:[r.slice(0,8),"..."]})}),width:120},{title:a("settings.metricsTable.session.columns.model"),dataIndex:"model",key:"model",width:160},{title:a("settings.metricsTable.session.columns.status"),dataIndex:"status",key:"status",width:120,render:r=>t.jsx(ue,{color:fo(r),children:yo(r,a)})},{title:a("settings.metricsTable.session.columns.started"),dataIndex:"started_at",key:"started_at",render:r=>po(r),width:200,sorter:(r,l)=>new Date(r.started_at).getTime()-new Date(l.started_at).getTime(),defaultSortOrder:"descend"},{title:a("settings.metricsTable.session.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",render:r=>ho(r),width:120},{title:a("settings.metricsTable.session.columns.tokens"),key:"tokens",render:(r,l)=>l.total_token_usage.total_tokens.toLocaleString(),width:120,sorter:(r,l)=>r.total_token_usage.total_tokens-l.total_token_usage.total_tokens},{title:a("settings.metricsTable.session.columns.toolCalls"),dataIndex:"tool_call_count",key:"tool_call_count",width:120,sorter:(r,l)=>r.tool_call_count-l.tool_call_count},{title:a("settings.metricsTable.session.columns.messages"),dataIndex:"message_count",key:"message_count",width:120,sorter:(r,l)=>r.message_count-l.message_count},{title:a("settings.metricsTable.session.columns.action"),key:"action",fixed:"right",width:120,render:(r,l)=>t.jsx(z,{type:"link",onClick:()=>{n(l.session_id)},children:a("settings.metricsTable.session.view")})}];return t.jsx(et,{rowKey:"session_id",size:"small",className:"lotus-metric-table",columns:o,loading:s,dataSource:e,pagination:{pageSize:10,showSizeChanger:!1},scroll:{x:1100}})},{Text:bo}=ie,cn={message_count:"Message Count",last_message_id:"Last Message",pending_question:"Pending Question"},vo=e=>cn[e]?cn[e]:e.split("_").map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "),jo=({breakdown:e,loading:s})=>{const{t:n}=Z();if(s)return t.jsx(I,{size:"small",className:"lotus-metric-card",title:n("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),children:t.jsx(tt,{active:!0,paragraph:{rows:5}})});const a=Object.entries(e??{}).map(([o,r])=>({reason:o,label:n(`settings.syncMismatchReasons.${o}`,{defaultValue:vo(o)}),count:r})).sort((o,r)=>r.count-o.count);return t.jsx(I,{size:"small",className:"lotus-metric-card",title:n("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),extra:t.jsx(bo,{type:"secondary",children:n("settings.metricsDashboard.syncMismatchBreakdownSubtitle",{defaultValue:"Grouped by execute sync mismatch reason"})}),children:a.length===0?t.jsx(Le,{image:Le.PRESENTED_IMAGE_SIMPLE,description:n("settings.metricsDashboard.noSyncMismatchBreakdown",{defaultValue:"No sync mismatches recorded for the selected range"})}):t.jsx("div",{style:{width:"100%",minWidth:0,height:280,minHeight:280},children:t.jsx(_t,{children:t.jsxs(Ps,{data:a,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[t.jsx(Wt,{strokeDasharray:"3 3"}),t.jsx(Gt,{type:"number",allowDecimals:!1}),t.jsx(Jt,{dataKey:"label",type:"category",width:110}),t.jsx(wt,{formatter:o=>[o.toLocaleString(),n("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})],labelFormatter:o=>n("settings.metricsDashboard.syncMismatchReasonLabel",{defaultValue:"Reason: {{label}}",label:o})}),t.jsx(is,{dataKey:"count",fill:"var(--lotus-chart-danger)",radius:[0,6,6,0],name:n("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})})]})})})})},{Text:To}=ie,So=({data:e,loading:s})=>{const{t:n}=Z();return s?t.jsx(I,{size:"small",className:"lotus-metric-card",title:n("settings.charts.tokenUsageOverTime"),children:t.jsx(tt,{active:!0,paragraph:{rows:5}})}):t.jsx(I,{size:"small",className:"lotus-metric-card",title:n("settings.charts.tokenUsageOverTime"),children:e.length===0?t.jsx(Le,{image:Le.PRESENTED_IMAGE_SIMPLE,description:n("settings.charts.noTokenUsage")}):t.jsxs(t.Fragment,{children:[t.jsx(To,{type:"secondary",children:n("settings.charts.tokenUsageDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(_t,{children:t.jsxs(Fn,{data:e,children:[t.jsx(Wt,{strokeDasharray:"3 3"}),t.jsx(Gt,{dataKey:"label",minTickGap:24}),t.jsx(Jt,{allowDecimals:!1}),t.jsx(wt,{}),t.jsx(Fs,{}),t.jsx(jt,{type:"monotone",dataKey:"totalTokens",name:n("settings.charts.total"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),t.jsx(jt,{type:"monotone",dataKey:"promptTokens",name:n("settings.charts.prompt"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),t.jsx(jt,{type:"monotone",dataKey:"completionTokens",name:n("settings.charts.completion"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{Text:_o}=ie,Rt=({title:e,subtitle:s,emptyText:n,color:a="var(--lotus-chart-primary)",data:o,loading:r,countLabel:l})=>{const{t:m}=Z();return r?t.jsx(I,{size:"small",className:"lotus-metric-card",title:e,children:t.jsx(tt,{active:!0,paragraph:{rows:5}})}):t.jsx(I,{size:"small",className:"lotus-metric-card",title:e,children:o.length===0?t.jsx(Le,{image:Le.PRESENTED_IMAGE_SIMPLE,description:n}):t.jsxs(t.Fragment,{children:[s?t.jsx(_o,{type:"secondary",children:s}):null,t.jsx("div",{style:{width:"100%",minWidth:0,height:280,marginTop:s?12:0},children:t.jsx(_t,{children:t.jsxs(Ps,{data:o,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[t.jsx(Wt,{strokeDasharray:"3 3"}),t.jsx(Gt,{type:"number",allowDecimals:!1}),t.jsx(Jt,{dataKey:"label",type:"category",width:110}),t.jsx(wt,{formatter:c=>[c.toLocaleString(),l??m("settings.metricsDashboard.calls",{defaultValue:"Calls"})],labelFormatter:(c,p)=>{var b,f;const d=(f=(b=p==null?void 0:p[0])==null?void 0:b.payload)==null?void 0:f.meta;return d?`${c} · ${d}`:String(c)}}),t.jsx(is,{dataKey:"count",fill:a,radius:[0,6,6,0],name:l??m("settings.metricsDashboard.calls",{defaultValue:"Calls"})})]})})})]})})},{useToken:wo}=fe,dn=({summary:e,loading:s})=>{const{t:n}=Z(),{token:a}=wo();return s?t.jsx(tt,{active:!0,paragraph:{rows:1}}):t.jsxs(Ve,{gutter:[a.marginSM,a.marginSM],children:[t.jsx(ae,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(I,{size:"small",className:"lotus-metric-card",children:t.jsx(ye,{title:n("settings.metricsDashboard.skillsAndMcp.cards.skillLoadCalls",{defaultValue:"Skill Loads"}),value:(e==null?void 0:e.skill_load_calls)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),t.jsx(ae,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(I,{size:"small",className:"lotus-metric-card",children:t.jsx(ye,{title:n("settings.metricsDashboard.skillsAndMcp.cards.uniqueSkills",{defaultValue:"Unique Skills"}),value:(e==null?void 0:e.unique_skills)??0,precision:0,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),t.jsx(ae,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(I,{size:"small",className:"lotus-metric-card",children:t.jsx(ye,{title:n("settings.metricsDashboard.skillsAndMcp.cards.mcpCalls",{defaultValue:"MCP Calls"}),value:(e==null?void 0:e.mcp_calls)??0,precision:0,valueStyle:{color:"var(--lotus-chart-accent)"}})})}),t.jsx(ae,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(I,{size:"small",className:"lotus-metric-card",children:t.jsx(ye,{title:n("settings.metricsDashboard.skillsAndMcp.cards.uniqueMcpServers",{defaultValue:"MCP Servers"}),value:(e==null?void 0:e.unique_mcp_servers)??0,precision:0,valueStyle:{color:"var(--lotus-chart-cyan)"}})})}),t.jsx(ae,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(I,{size:"small",className:"lotus-metric-card",children:t.jsx(ye,{title:n("settings.metricsDashboard.skillsAndMcp.cards.uniqueMcpTools",{defaultValue:"MCP Tools"}),value:(e==null?void 0:e.unique_mcp_tools)??0,precision:0,valueStyle:{color:"var(--lotus-chart-secondary)"}})})}),t.jsx(ae,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(I,{size:"small",className:"lotus-metric-card",children:t.jsx(ye,{title:n("settings.metricsDashboard.skillsAndMcp.cards.coreToolCalls",{defaultValue:"Core Tool Calls"}),value:(e==null?void 0:e.core_tool_calls)??0,precision:0,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})})]})},{Text:xt}=ie,{useToken:ko}=fe,un=70,gn=130,mn=2,pn=1.2,hn=.65,fn=45,yn=1.8,xn=e=>"date"in e?e.date:e.label,Mo=(e,s)=>{if(s<=0||e<=0)return"var(--lotus-heat-0)";const n=e/s;return n>=.8?"var(--lotus-heat-4)":n>=.6?"var(--lotus-heat-3)":n>=.4?"var(--lotus-heat-2)":n>=.2?"var(--lotus-heat-1)":"var(--lotus-heat-0)"},At=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),n=Math.floor(s/60),a=s%60;if(n>=60){const o=Math.floor(n/60),r=n%60;return`${o}h ${r}m`}return n>0?`${n}m ${a}s`:`${a}s`},bn=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString()},bs=e=>{const s=Object.entries(e??{}).sort((n,a)=>a[1]-n[1]);return s.length===0?"-":s.slice(0,6).map(([n,a])=>`${n}: ${a.toLocaleString()}`).join(" • ")},vs=(e,s=320)=>({width:"100%",display:"grid",gridTemplateColumns:`repeat(auto-fit, minmax(${s}px, 1fr))`,gap:e}),Co=()=>{const{t:e}=Z(),{token:s}=ko(),n=Xn(g=>g.themeMode)==="dark",[a,o]=i.useState(void 0),[r,l]=i.useState(void 0),[m,c]=i.useState(void 0),[p,d]=i.useState(30),[b,f]=i.useState("daily"),{summary:w,modelMetrics:v,sessions:u,timeline:C,memorySummary:j,memoryTimeline:x,sessionDetail:E,isLoading:T,isRefreshing:P,isSessionDetailLoading:ee,error:R,refresh:B,loadSessionDetail:G,clearSessionDetail:h}=Wr({filters:{startDate:a,endDate:r,model:m,days:p,granularity:b}}),{summary:y,endpointMetrics:D,requests:S,isLoading:O,isRefreshing:X,error:A,refresh:U}=Hr({filters:{startDate:a,endDate:r,days:p,model:m}}),{data:$,isLoading:oe,isRefreshing:de,error:K,refresh:L}=Xr({filters:{startDate:a,endDate:r,days:p,model:m}}),W=i.useMemo(()=>C.map(g=>({label:xn(g),promptTokens:g.total_token_usage.prompt_tokens,completionTokens:g.total_token_usage.completion_tokens,totalTokens:g.total_token_usage.total_tokens})),[C]),Q=i.useMemo(()=>v.map(g=>({label:g.model,value:g.model})),[v]),te=i.useMemo(()=>{const g=C.map(le=>({label:xn(le),sessions:le.total_sessions,tokens:le.total_token_usage.total_tokens})),se=g.reduce((le,Ce)=>Math.max(le,Ce.sessions),0);return{points:g,maxSessions:se}},[C]),Me=i.useMemo(()=>{const g=S.map(le=>le.duration_ms).filter(le=>typeof le=="number"&&le>0).sort((le,Ce)=>le-Ce);if(g.length===0)return null;const se=Math.ceil(g.length*.95)-1;return g[Math.max(0,Math.min(se,g.length-1))]},[S]),qe=i.useMemo(()=>[{title:e("settings.metricsDashboard.roundColumns.round"),dataIndex:"round_id",key:"round_id",render:g=>`${g.slice(0,8)}...`},{title:e("settings.metricsDashboard.roundColumns.status"),dataIndex:"status",key:"status"},{title:e("settings.metricsDashboard.roundColumns.duration"),dataIndex:"duration_ms",key:"duration_ms",render:g=>At(g)},{title:e("settings.metricsDashboard.roundColumns.tokens"),key:"tokens",render:(g,se)=>se.token_usage.total_tokens.toLocaleString()},{title:e("settings.metricsDashboard.roundColumns.toolCalls"),key:"tool_calls",render:(g,se)=>se.tool_calls.length}],[e]),Pe=i.useMemo(()=>{const g=(w==null?void 0:w.total_sessions)??0,se=(w==null?void 0:w.total_tokens.total_tokens)??0,le=(w==null?void 0:w.total_tool_calls)??0,Ce=(w==null?void 0:w.active_sessions)??0,me=u.reduce((Je,ct)=>Je+ct.total_rounds,0),Ee=(y==null?void 0:y.total_requests)??0,gs=(y==null?void 0:y.total_tokens.total_tokens)??0,M=(y==null?void 0:y.failed_requests)??0,k=S.filter(Je=>Je.is_stream).length,J=g>0?Ce/g*100:0,H=Ee>0?M/Ee*100:0,Y=S.length>0?k/S.length*100:0,ce=se/un+le*mn,ne=se/gn+le*pn,De=Math.max(0,ce-ne)*hn,Se=Math.max(ne,ce-De),Ue=At(De*6e4),xe=Number((De/(8*60)).toFixed(2)),_e=ce>0?Math.min(fn,Number((De/ce*100).toFixed(1))):0,Ge=Se>0?Math.min(yn,Number((ce/Se).toFixed(2))):1;return[{title:e("settings.metricsDashboard.compactStats.avgTokensPerSession"),value:g>0?Math.round(se/g):0},{title:e("settings.metricsDashboard.compactStats.estimatedTimeSaved"),value:Ue},{title:e("settings.metricsDashboard.compactStats.estimatedEfficiencyLift"),value:_e,suffix:"%"},{title:e("settings.metricsDashboard.compactStats.estimatedSpeedMultiplier"),value:Ge,suffix:e("settings.metricsDashboard.multiplierSuffix")},{title:e("settings.metricsDashboard.compactStats.estimatedSavedWorkdays"),value:xe},{title:e("settings.metricsDashboard.compactStats.avgRoundsPerSession"),value:g>0?Number((me/g).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.toolCallsPerSession"),value:g>0?Number((le/g).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.activeSessionRate"),value:Number(J.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.avgTokensPerForward"),value:Ee>0?Math.round(gs/Ee):0},{title:e("settings.metricsDashboard.compactStats.forwardErrorRate"),value:Number(H.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.streamingRatio"),value:Number(Y.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.p95ForwardLatency"),value:At(Me)},{title:e("settings.metricsDashboard.compactStats.modelCoverage"),value:v.length},{title:e("settings.metricsDashboard.compactStats.endpointCoverage"),value:D.length}]},[D.length,S,y,v.length,Me,u,w,e]),kt=i.useMemo(()=>{const g=(y==null?void 0:y.total_requests)??0,se=(y==null?void 0:y.failed_requests)??0,le=S.filter(Ee=>Ee.is_stream).length,Ce=S.length>0?le/S.length*100:0,me=g>0?se/g*100:0;return[{title:e("settings.metricsDashboard.forward.performance.p95Latency",{defaultValue:"P95 Latency"}),value:At(Me)},{title:e("settings.metricsDashboard.forward.performance.errorRate",{defaultValue:"Error Rate"}),value:Number(me.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.streamingRatio",{defaultValue:"Streaming Ratio"}),value:Number(Ce.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.endpointCoverage",{defaultValue:"Endpoint Coverage"}),value:D.length}]},[D.length,S,y,Me,e]),ft=i.useMemo(()=>$?[{label:e("settings.metricsDashboard.skillsAndMcp.mix.coreTools",{defaultValue:"Core Tools"}),count:$.core_tool_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.skillLoads",{defaultValue:"Skill Loads"}),count:$.skill_load_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.mcpCalls",{defaultValue:"MCP Calls"}),count:$.mcp_calls}].filter(g=>g.count>0):[],[e,$]),Mt=i.useMemo(()=>(($==null?void 0:$.top_skills)??[]).map(g=>({label:g.skill_id,count:g.count})),[$]),Ct=i.useMemo(()=>(($==null?void 0:$.top_mcp_servers)??[]).map(g=>({label:g.server_id,count:g.count,meta:e("settings.metricsDashboard.skillsAndMcp.meta.uniqueTools",{defaultValue:"{{count}} tools",count:g.unique_tools})})),[e,$]),it=i.useMemo(()=>(($==null?void 0:$.top_mcp_tools)??[]).map(g=>({label:g.tool_name,count:g.count,meta:g.server_id})),[$]),lt=i.useMemo(()=>(($==null?void 0:$.top_core_tools)??[]).map(g=>({label:g.name,count:g.count})),[$]),ze=E==null?void 0:E.session,Et=P||X||de;return t.jsxs(F,{direction:"vertical",size:s.marginMD,style:{width:"100%"},children:[R?t.jsx(ke,{type:"error",showIcon:!0,message:R}):null,A?t.jsx(ke,{type:"error",showIcon:!0,message:A}):null,K?t.jsx(ke,{type:"error",showIcon:!0,message:K}):null,t.jsx(I,{size:"small",title:e("settings.metricsDashboard.filtersTitle"),extra:t.jsx(z,{icon:t.jsx(St,{}),loading:Et,onClick:()=>{B(),U(),L()},children:e("settings.metricsDashboard.refresh")}),children:t.jsxs(F,{wrap:!0,children:[t.jsx(Ks,{placeholder:e("settings.metricsDashboard.startDate"),onChange:g=>{o(g?g.format("YYYY-MM-DD"):void 0)}}),t.jsx(Ks,{placeholder:e("settings.metricsDashboard.endDate"),onChange:g=>{l(g?g.format("YYYY-MM-DD"):void 0)}}),t.jsx(re,{allowClear:!0,style:{minWidth:180},placeholder:e("settings.metricsDashboard.model"),value:m,options:Q,onChange:g=>{c(g)}}),t.jsx(re,{style:{width:120},value:p,options:[7,14,30,90].map(g=>({label:e("settings.metricsDashboard.daysOption",{value:g}),value:g})),onChange:g=>{d(g)}}),t.jsx(re,{style:{width:140},value:b,options:[{label:e("settings.metricsDashboard.granularity.daily"),value:"daily"},{label:e("settings.metricsDashboard.granularity.weekly"),value:"weekly"},{label:e("settings.metricsDashboard.granularity.monthly"),value:"monthly"}],onChange:g=>{f(g)}})]})}),t.jsx(I,{size:"small",title:e("settings.metricsDashboard.dashboardTitle"),children:t.jsx(rs,{size:"small",destroyInactiveTabPane:!0,items:[{key:"overview",label:e("settings.metricsDashboard.tabs.overview"),children:t.jsxs(F,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(on,{summary:w,sessions:u,loading:T}),t.jsx(an,{summary:y,loading:O}),t.jsx(dn,{summary:$,loading:oe}),t.jsx(rn,{summary:j,loading:T}),t.jsxs(I,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.derivedMetricsTitle"),extra:t.jsx(xt,{type:"secondary",children:e("settings.metricsDashboard.derivedMetricsSubtitle")}),children:[t.jsx(Ve,{gutter:[s.marginSM,s.marginSM],children:Pe.map(g=>t.jsx(ae,{xs:24,sm:12,md:8,xl:6,children:t.jsx("div",{style:{borderRadius:s.borderRadiusSM,padding:s.paddingXS,background:n?"rgba(255, 255, 255, 0.05)":"rgba(255, 255, 255, 0.82)",border:n?"1px solid rgba(255,255,255,0.08)":"1px solid rgba(148,163,184,0.18)"},children:t.jsx(ye,{title:g.title,value:g.value,suffix:g.suffix,valueStyle:{fontSize:s.fontSizeHeading4}})})},g.title))}),t.jsx(xt,{type:"secondary",style:{display:"block",marginTop:s.marginXS},children:e("settings.metricsDashboard.efficiencyHint",{manualTpm:un,manualToolMinutes:mn,assistedTpm:gn,assistedToolMinutes:pn,realization:Math.round(hn*100),maxLift:fn,maxMultiplier:yn})})]})]})},{key:"chat",label:e("settings.metricsDashboard.tabs.chat",{defaultValue:"Chat"}),children:t.jsxs(F,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(on,{summary:w,sessions:u,loading:T}),t.jsxs("div",{style:vs(s.marginSM,360),children:[t.jsx(So,{data:W,loading:T}),t.jsx(mo,{data:v,loading:T})]}),t.jsxs("div",{style:vs(s.marginSM,360),children:[t.jsx(jo,{breakdown:w==null?void 0:w.sync_mismatch_breakdown,loading:T}),t.jsx(I,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.activityHeatmapTitle"),children:te.points.length===0?t.jsx(xt,{type:"secondary",children:e("settings.metricsDashboard.noActivity")}):t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(72px, 1fr))",gap:s.marginXS},children:te.points.map(g=>t.jsxs("div",{style:{borderRadius:s.borderRadiusSM,padding:s.paddingXS,background:Mo(g.sessions,te.maxSessions),minHeight:64,color:g.sessions>0?"var(--lotus-metric-text-strong)":s.colorTextSecondary},children:[t.jsx("div",{style:{fontSize:12,lineHeight:1.2},children:g.label}),t.jsx("div",{style:{fontWeight:600,marginTop:4},children:e("settings.metricsDashboard.sessionsCount",{count:g.sessions})}),t.jsx("div",{style:{fontSize:12},children:e("settings.metricsDashboard.tokensAmount",{value:g.tokens.toLocaleString()})})]},g.label))})})]})]})},{key:"skills-and-mcp",label:e("settings.metricsDashboard.tabs.skillsAndMcp",{defaultValue:"Skills & MCP"}),children:t.jsxs(F,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(dn,{summary:$,loading:oe}),t.jsxs("div",{style:vs(s.marginSM,360),children:[t.jsx(Rt,{title:e("settings.metricsDashboard.skillsAndMcp.usageMixTitle",{defaultValue:"Usage Mix"}),subtitle:e("settings.metricsDashboard.skillsAndMcp.usageMixSubtitle",{defaultValue:"Compare core tools, skill loads, and MCP calls in one view."}),emptyText:e("settings.metricsDashboard.skillsAndMcp.noUsageMix",{defaultValue:"No usage data available for this range."}),data:ft,loading:oe,color:"var(--lotus-chart-primary)"}),t.jsx(Rt,{title:e("settings.metricsDashboard.skillsAndMcp.topSkillsTitle",{defaultValue:"Top Skills"}),subtitle:e("settings.metricsDashboard.skillsAndMcp.topSkillsSubtitle",{defaultValue:"Counted from load_skill calls during matching sessions."}),emptyText:e("settings.metricsDashboard.skillsAndMcp.noSkills",{defaultValue:"No skills were loaded in this range."}),data:Mt,loading:oe,color:"var(--lotus-chart-purple)"}),t.jsx(Rt,{title:e("settings.metricsDashboard.skillsAndMcp.topMcpServersTitle",{defaultValue:"Top MCP Servers"}),subtitle:e("settings.metricsDashboard.skillsAndMcp.topMcpServersSubtitle",{defaultValue:"Server-level MCP call distribution."}),emptyText:e("settings.metricsDashboard.skillsAndMcp.noMcpServers",{defaultValue:"No MCP activity recorded for this range."}),data:Ct,loading:oe,color:"var(--lotus-chart-cyan)"}),t.jsx(Rt,{title:e("settings.metricsDashboard.skillsAndMcp.topMcpToolsTitle",{defaultValue:"Top MCP Tools"}),subtitle:e("settings.metricsDashboard.skillsAndMcp.topMcpToolsSubtitle",{defaultValue:"Most frequently called MCP tool aliases."}),emptyText:e("settings.metricsDashboard.skillsAndMcp.noMcpTools",{defaultValue:"No MCP tools were called in this range."}),data:it,loading:oe,color:"var(--lotus-chart-accent)"}),t.jsx(Rt,{title:e("settings.metricsDashboard.skillsAndMcp.topCoreToolsTitle",{defaultValue:"Top Core Tools"}),subtitle:e("settings.metricsDashboard.skillsAndMcp.topCoreToolsSubtitle",{defaultValue:"Canonicalized built-in and server tool usage ranking."}),emptyText:e("settings.metricsDashboard.skillsAndMcp.noCoreTools",{defaultValue:"No core tools were called in this range."}),data:lt,loading:oe,color:"var(--lotus-chart-secondary)"})]})]})},{key:"forward",label:e("settings.metricsDashboard.tabs.forward",{defaultValue:"Forward"}),children:t.jsxs(F,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(an,{summary:y,loading:O}),t.jsx(I,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.forward.performanceTitle",{defaultValue:"Forward Performance"}),children:t.jsx(Ve,{gutter:[s.marginSM,s.marginSM],children:kt.map(g=>t.jsx(ae,{xs:24,sm:12,xl:6,children:t.jsx("div",{style:{borderRadius:s.borderRadiusSM,padding:s.paddingXS,background:n?"rgba(255, 255, 255, 0.05)":"rgba(255, 255, 255, 0.82)",border:n?"1px solid rgba(255,255,255,0.08)":"1px solid rgba(148,163,184,0.18)"},children:t.jsx(ye,{title:g.title,value:g.value,suffix:g.suffix,valueStyle:{fontSize:s.fontSizeHeading4}})})},g.title))})}),t.jsx(Zr,{data:D,loading:O})]})},{key:"memory",label:e("settings.metricsDashboard.tabs.memory",{defaultValue:"Memory"}),children:t.jsxs(F,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(rn,{summary:j,loading:T}),t.jsx(io,{data:x,loading:T}),t.jsx(I,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.memory.breakdownTitle",{defaultValue:"Memory Breakdown"}),children:t.jsxs(we,{size:"small",bordered:!0,column:1,children:[t.jsx(we.Item,{label:e("settings.metricsDashboard.memory.byType",{defaultValue:"By Type"}),children:bs(j==null?void 0:j.by_type)}),t.jsx(we.Item,{label:e("settings.metricsDashboard.memory.byStatus",{defaultValue:"By Status"}),children:bs(j==null?void 0:j.by_status)}),t.jsx(we.Item,{label:e("settings.metricsDashboard.memory.byScope",{defaultValue:"By Scope"}),children:bs(j==null?void 0:j.by_scope)}),t.jsx(we.Item,{label:e("settings.metricsDashboard.memory.lastDream",{defaultValue:"Last Dream"}),children:bn(j==null?void 0:j.last_dream_at)}),t.jsx(we.Item,{label:e("settings.metricsDashboard.memory.lastReindex",{defaultValue:"Last Reindex"}),children:bn(j==null?void 0:j.last_reindex_at)})]})})]})},{key:"records",label:e("settings.metricsDashboard.tabs.records"),children:t.jsx(rs,{size:"small",destroyInactiveTabPane:!0,items:[{key:"sessions",label:e("settings.metricsDashboard.sessionsTabLabel",{count:u.length}),children:t.jsx(I,{size:"small",extra:t.jsx(xt,{type:"secondary",children:e("settings.metricsDashboard.sessionsHint")}),children:t.jsx(xo,{sessions:u,loading:T,onSelectSession:g=>{G(g)}})})},{key:"forward-requests",label:e("settings.metricsDashboard.forwardTabLabel",{count:S.length}),children:t.jsx(I,{size:"small",children:t.jsx(no,{requests:S,loading:O})})}]})}]})}),t.jsx(ot,{title:e("settings.metricsDashboard.sessionMetricsTitle"),open:!!E,onCancel:h,onOk:h,width:960,destroyOnClose:!0,children:ee?t.jsx(xt,{children:e("settings.metricsDashboard.loadingSessionDetails")}):ze?t.jsxs(F,{direction:"vertical",style:{width:"100%"},size:s.marginMD,children:[t.jsxs(we,{size:"small",bordered:!0,column:2,children:[t.jsx(we.Item,{label:e("settings.metricsDashboard.sessionDetail.sessionId"),span:2,children:ze.session_id}),t.jsx(we.Item,{label:e("settings.metricsDashboard.sessionDetail.model"),children:ze.model}),t.jsx(we.Item,{label:e("settings.metricsDashboard.sessionDetail.status"),children:ze.status}),t.jsx(we.Item,{label:e("settings.metricsDashboard.sessionDetail.duration"),children:At(ze.duration_ms)}),t.jsx(we.Item,{label:e("settings.metricsDashboard.sessionDetail.messages"),children:ze.message_count}),t.jsx(we.Item,{label:e("settings.metricsDashboard.sessionDetail.totalTokens"),children:ze.total_token_usage.total_tokens.toLocaleString()}),t.jsx(we.Item,{label:e("settings.metricsDashboard.sessionDetail.toolCalls"),children:ze.tool_call_count})]}),t.jsx(et,{rowKey:"round_id",size:"small",columns:qe,dataSource:E.rounds,pagination:{pageSize:6,showSizeChanger:!1}})]}):t.jsx(xt,{type:"secondary",children:e("settings.metricsDashboard.noDetail")})})]})},{Text:es}=ie,{useToken:Eo}=fe,Do=e=>{const s=e==null?void 0:e.hooks,n=s==null?void 0:s.image_fallback,a=String((n==null?void 0:n.mode)||"placeholder").trim().toLowerCase();return a==="error"||a==="ocr"||a==="vision"?a:"placeholder"},Io=e=>{const s=e==null?void 0:e.hooks,n=s==null?void 0:s.image_fallback,a=n==null?void 0:n.enabled;return typeof a=="boolean"?a:!1},Po=()=>{const{t:e}=Z(),{token:s}=Eo(),[n,a]=Tt.useMessage(),[o,r]=i.useState(!1),[l,m]=i.useState(!0),[c,p]=i.useState("placeholder"),d=i.useMemo(()=>[{label:e("settings.hooksTab.mode.placeholder"),value:"placeholder"},{label:e("settings.hooksTab.mode.error"),value:"error"},{label:e("settings.hooksTab.mode.ocr"),value:"ocr"},{label:e("settings.hooksTab.mode.vision"),value:"vision"}],[e]),b=i.useCallback(async()=>{r(!0);try{const u=await Te.getBambooConfig();m(Io(u)),p(Do(u))}catch(u){n.error(u instanceof Error?u.message:e("settings.hooksTab.loadFailed"))}finally{r(!1)}},[n,e]),f=i.useCallback(async(u,C)=>{await Te.setBambooConfig({hooks:{image_fallback:{enabled:u,mode:C}}})},[]),w=i.useCallback(async u=>{r(!0);try{await f(u,c),n.success(e(u?"settings.hooksTab.enabled":"settings.hooksTab.disabled")),await b()}catch(C){n.error(C instanceof Error?C.message:e("settings.hooksTab.updateFailed"))}finally{r(!1)}},[b,c,n,f,e]),v=i.useCallback(async u=>{var C;r(!0);try{await f(l,u),n.success(e("settings.hooksTab.modeUpdated",{mode:((C=d.find(j=>j.value===u))==null?void 0:C.label)??u})),await b()}catch(j){n.error(j instanceof Error?j.message:e("settings.hooksTab.modeUpdateFailed"))}finally{r(!1)}},[l,b,d,n,f,e]);return i.useEffect(()=>{b()},[b]),t.jsxs(V,{vertical:!0,gap:s.marginLG,children:[a,t.jsx(I,{size:"small",loading:o,children:t.jsxs(V,{vertical:!0,gap:s.marginXS,children:[t.jsx(es,{strong:!0,children:e("settings.hooksTab.title")}),t.jsxs(V,{align:"center",justify:"space-between",children:[t.jsx(es,{children:e("settings.hooksTab.enableImagePreflight")}),t.jsx(ge,{checked:l,onChange:w})]}),t.jsxs(V,{align:"center",justify:"space-between",children:[t.jsx(es,{children:e("settings.hooksTab.modeLabel")}),t.jsx(re,{style:{width:180},value:c,options:d,onChange:v,disabled:!l})]}),t.jsx(es,{type:"secondary",style:{fontSize:s.fontSizeSM},children:e("settings.hooksTab.description")})]})})]})},{Text:je}=ie,Ye=Es.getInstance();function Fo(e){switch(e){case"success":return"success";case"failed":case"cancelled":return"error";case"running":return"processing";case"queued":return"gold";case"missed":case"skipped":default:return"default"}}const Ro=[{label:"Mon",value:"mon"},{label:"Tue",value:"tue"},{label:"Wed",value:"wed"},{label:"Thu",value:"thu"},{label:"Fri",value:"fri"},{label:"Sat",value:"sat"},{label:"Sun",value:"sun"}];function be(e){return String(e??"").trim()||void 0}function Ao(e){return(e==null?void 0:e.type)==="interval"?e.every_seconds:null}function zn(e){return{type:"interval",every_seconds:e}}function Lo(e){switch(e.type){case"interval":return`interval · ${e.every_seconds}s`;case"daily":return`daily · ${String(e.hour).padStart(2,"0")}:${String(e.minute).padStart(2,"0")}`;case"weekly":return`weekly · ${e.weekdays.join(", ")}`;case"monthly":return`monthly · ${e.days.join(", ")}`;case"cron":return`cron · ${e.expr}`}}function zo(e){switch(e==null?void 0:e.type){case"skip":return"skip";case"catch_up_all":return"catch up all";case"catch_up_window":return"catch up window";case"run_once":default:return"run once"}}function Oo(e){switch(e){case"allow":return"allow overlap";case"skip":return"skip overlap";case"queue_one":default:return"queue one"}}function No(e){var s;return(s=e.state)!=null&&s.next_fire_at?String(e.state.next_fire_at):"-"}function $o(e){var s,n;return(s=e.state)!=null&&s.last_success_at?String(e.state.last_success_at):(n=e.state)!=null&&n.last_finished_at?String(e.state.last_finished_at):"-"}function Vo(e){var s,n,a,o;return((s=e.state)==null?void 0:s.running_run_count)>0?{color:"processing",label:"running",detail:`${e.state.running_run_count} active`}:(((n=e.state)==null?void 0:n.queued_run_count)||0)>0?{color:"gold",label:"queued",detail:`${e.state.queued_run_count} pending`}:(((a=e.state)==null?void 0:a.consecutive_failures)||0)>0?{color:"error",label:"failing",detail:`${e.state.consecutive_failures} consecutive failures`}:e.enabled?(o=e.state)!=null&&o.last_success_at?{color:"success",label:"healthy",detail:"last run succeeded"}:{color:"default",label:"idle"}:{color:"default",label:"disabled"}}function Bo(e){const s=be(e);if(!s)return{days:[],invalid:!1};const a=s.split(/[\s,]+/).filter(Boolean).map(l=>Number(l)),o=a.some(l=>!Number.isInteger(l)||l<1||l>31);return{days:Array.from(new Set(a.filter(l=>Number.isInteger(l)&&l>=1&&l<=31))),invalid:o}}function vn(e){switch(e.trigger_type){case"interval":{const s=Number(e.interval_seconds||0);return s<=0?{errorKey:"settings.schedulesTab.validation.intervalRequired"}:{trigger:zn(s)}}case"daily":{const s=e.daily_hour,n=e.daily_minute;return s==null||n==null?{errorKey:"settings.schedulesTab.validation.triggerRequired"}:{trigger:{type:"daily",hour:s,minute:n,second:0}}}case"weekly":{const s=e.weekly_weekdays||[],n=e.weekly_hour,a=e.weekly_minute;return s.length===0?{errorKey:"settings.schedulesTab.validation.weekdaysRequired"}:n==null||a==null?{errorKey:"settings.schedulesTab.validation.triggerRequired"}:{trigger:{type:"weekly",weekdays:s,hour:n,minute:a,second:0}}}case"monthly":{const{days:s,invalid:n}=Bo(e.monthly_days);if(n)return{errorKey:"settings.schedulesTab.validation.invalidMonthDays"};if(s.length===0)return{errorKey:"settings.schedulesTab.validation.monthDaysRequired"};const a=e.monthly_hour,o=e.monthly_minute;return a==null||o==null?{errorKey:"settings.schedulesTab.validation.triggerRequired"}:{trigger:{type:"monthly",days:s,hour:a,minute:o,second:0}}}case"cron":{const s=be(e.cron_expr);return s?{trigger:{type:"cron",expr:s}}:{errorKey:"settings.schedulesTab.validation.cronRequired"}}default:return{errorKey:"settings.schedulesTab.validation.triggerRequired"}}}function jn(e){switch(e.misfire_policy){case"skip":return{type:"skip"};case"catch_up_all":return{type:"catch_up_all"};case"catch_up_window":return{type:"catch_up_window",max_catch_up_runs:Number(e.catch_up_window_max_runs||1),max_lateness_seconds:Number(e.catch_up_window_max_lateness_seconds||60)};case"run_once":default:return{type:"run_once"}}}function qo(e){var n,a,o,r,l,m,c,p;const s={name:e.name,enabled:e.enabled,trigger_type:e.trigger.type,timezone:e.timezone||"",start_at:e.start_at||"",end_at:e.end_at||"",misfire_policy:((n=e.misfire_policy)==null?void 0:n.type)||"run_once",overlap_policy:e.overlap_policy||"queue_one",system_prompt:((a=e.run_config)==null?void 0:a.system_prompt)||"",task_message:((o=e.run_config)==null?void 0:o.task_message)||"",model:((r=e.run_config)==null?void 0:r.model)||"",workspace_path:((l=e.run_config)==null?void 0:l.workspace_path)||"",enhance_prompt:((m=e.run_config)==null?void 0:m.enhance_prompt)||"",auto_execute:!!((c=e.run_config)!=null&&c.auto_execute)};switch(((p=e.misfire_policy)==null?void 0:p.type)==="catch_up_window"&&(s.catch_up_window_max_runs=e.misfire_policy.max_catch_up_runs,s.catch_up_window_max_lateness_seconds=e.misfire_policy.max_lateness_seconds),e.trigger.type){case"interval":s.interval_seconds=e.trigger.every_seconds;break;case"daily":s.daily_hour=e.trigger.hour,s.daily_minute=e.trigger.minute;break;case"weekly":s.weekly_weekdays=e.trigger.weekdays,s.weekly_hour=e.trigger.hour,s.weekly_minute=e.trigger.minute;break;case"monthly":s.monthly_days=e.trigger.days.join(", "),s.monthly_hour=e.trigger.hour,s.monthly_minute=e.trigger.minute;break;case"cron":s.cron_expr=e.trigger.expr;break}return s}function Uo(){const{t:e}=Z(),[s,n]=Tt.useMessage(),[a,o]=i.useState(!1),[r,l]=i.useState([]),[m,c]=i.useState({open:!1,scheduleId:null,sessions:[],loading:!1}),[p,d]=i.useState({open:!1,scheduleId:null,runs:[],loading:!1}),[b,f]=i.useState({open:!1,schedule:null,saving:!1}),w=_s(h=>h.close),[v]=_.useForm(),[u]=_.useForm(),C=_.useWatch("trigger_type",v),j=_.useWatch("misfire_policy",v),x=_.useWatch("trigger_type",u),E=_.useWatch("misfire_policy",u),T=i.useCallback(async()=>{o(!0);try{const h=await Ye.listSchedules();l(h.schedules||[])}catch(h){console.error("[Schedules] Failed to load schedules:",h),s.error(e("settings.schedulesTab.loadFailed"))}finally{o(!1)}},[s,e]);i.useEffect(()=>{T()},[T]);const P=[{value:"interval",label:e("settings.schedulesTab.triggerTypes.interval")},{value:"daily",label:e("settings.schedulesTab.triggerTypes.daily")},{value:"weekly",label:e("settings.schedulesTab.triggerTypes.weekly")},{value:"monthly",label:e("settings.schedulesTab.triggerTypes.monthly")},{value:"cron",label:e("settings.schedulesTab.triggerTypes.cron")}],ee=[{value:"run_once",label:e("settings.schedulesTab.misfirePolicyOptions.runOnce")},{value:"skip",label:e("settings.schedulesTab.misfirePolicyOptions.skip")},{value:"catch_up_all",label:e("settings.schedulesTab.misfirePolicyOptions.catchUpAll")},{value:"catch_up_window",label:e("settings.schedulesTab.misfirePolicyOptions.catchUpWindow")}],R=[{value:"queue_one",label:e("settings.schedulesTab.overlapPolicyOptions.queueOne")},{value:"skip",label:e("settings.schedulesTab.overlapPolicyOptions.skip")},{value:"allow",label:e("settings.schedulesTab.overlapPolicyOptions.allow")}],B=(h,y)=>t.jsxs(t.Fragment,{children:[t.jsxs(V,{gap:12,wrap:"wrap",children:[t.jsx(_.Item,{label:e("settings.schedulesTab.form.name"),name:"name",rules:[{required:!0,message:e("settings.schedulesTab.validation.nameRequired")}],style:{flex:"1 1 260px"},children:t.jsx(q,{})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.triggerType"),name:"trigger_type",rules:[{required:!0,message:e("settings.schedulesTab.validation.triggerRequired")}],style:{width:220},children:t.jsx(re,{options:P})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.enabled"),name:"enabled",valuePropName:"checked",style:{width:120},children:t.jsx(ge,{})})]}),h==="interval"?t.jsx(_.Item,{label:e("settings.schedulesTab.form.intervalSeconds"),name:"interval_seconds",rules:[{required:!0,message:e("settings.schedulesTab.validation.intervalRequired")}],style:{width:220},children:t.jsx(he,{min:1,style:{width:"100%"}})}):null,h==="daily"?t.jsxs(V,{gap:12,wrap:"wrap",children:[t.jsx(_.Item,{label:e("settings.schedulesTab.form.dailyHour"),name:"daily_hour",style:{width:180},children:t.jsx(he,{min:0,max:23,style:{width:"100%"}})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.dailyMinute"),name:"daily_minute",style:{width:180},children:t.jsx(he,{min:0,max:59,style:{width:"100%"}})})]}):null,h==="weekly"?t.jsxs(t.Fragment,{children:[t.jsx(_.Item,{label:e("settings.schedulesTab.form.weeklyWeekdays"),name:"weekly_weekdays",style:{minWidth:320},children:t.jsx(re,{mode:"multiple",options:Ro})}),t.jsxs(V,{gap:12,wrap:"wrap",children:[t.jsx(_.Item,{label:e("settings.schedulesTab.form.dailyHour"),name:"weekly_hour",style:{width:180},children:t.jsx(he,{min:0,max:23,style:{width:"100%"}})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.dailyMinute"),name:"weekly_minute",style:{width:180},children:t.jsx(he,{min:0,max:59,style:{width:"100%"}})})]})]}):null,h==="monthly"?t.jsxs(t.Fragment,{children:[t.jsx(_.Item,{label:e("settings.schedulesTab.form.monthlyDays"),name:"monthly_days",style:{minWidth:320},children:t.jsx(q,{placeholder:e("settings.schedulesTab.form.monthlyDaysPlaceholder")})}),t.jsxs(V,{gap:12,wrap:"wrap",children:[t.jsx(_.Item,{label:e("settings.schedulesTab.form.dailyHour"),name:"monthly_hour",style:{width:180},children:t.jsx(he,{min:0,max:23,style:{width:"100%"}})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.dailyMinute"),name:"monthly_minute",style:{width:180},children:t.jsx(he,{min:0,max:59,style:{width:"100%"}})})]})]}):null,h==="cron"?t.jsx(_.Item,{label:e("settings.schedulesTab.form.cronExpr"),name:"cron_expr",children:t.jsx(q,{placeholder:e("settings.schedulesTab.form.cronExprPlaceholder")})}):null,t.jsxs(V,{gap:12,wrap:"wrap",children:[t.jsx(_.Item,{label:e("settings.schedulesTab.form.timezone"),name:"timezone",style:{flex:"1 1 240px"},children:t.jsx(q,{placeholder:e("settings.schedulesTab.form.timezonePlaceholder")})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.startAt"),name:"start_at",style:{flex:"1 1 240px"},children:t.jsx(q,{placeholder:e("settings.schedulesTab.form.datetimePlaceholder")})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.endAt"),name:"end_at",style:{flex:"1 1 240px"},children:t.jsx(q,{placeholder:e("settings.schedulesTab.form.datetimePlaceholder")})})]}),t.jsxs(V,{gap:12,wrap:"wrap",children:[t.jsx(_.Item,{label:e("settings.schedulesTab.form.misfirePolicy"),name:"misfire_policy",style:{flex:"1 1 240px"},children:t.jsx(re,{options:ee})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.overlapPolicy"),name:"overlap_policy",style:{flex:"1 1 240px"},children:t.jsx(re,{options:R})})]}),y==="catch_up_window"?t.jsxs(V,{gap:12,wrap:"wrap",children:[t.jsx(_.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxRuns"),name:"catch_up_window_max_runs",style:{width:220},children:t.jsx(he,{min:1,style:{width:"100%"}})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxLatenessSeconds"),name:"catch_up_window_max_lateness_seconds",style:{width:260},children:t.jsx(he,{min:1,style:{width:"100%"}})})]}):null,t.jsx(_.Item,{label:e("settings.schedulesTab.form.taskMessage"),name:"task_message",children:t.jsx(q.TextArea,{rows:3,placeholder:e("settings.schedulesTab.form.taskMessagePlaceholder")})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.systemPrompt"),name:"system_prompt",children:t.jsx(q.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})}),t.jsxs(V,{gap:12,wrap:"wrap",children:[t.jsx(_.Item,{label:e("settings.schedulesTab.form.model"),name:"model",style:{flex:"1 1 240px"},children:t.jsx(q,{placeholder:e("settings.schedulesTab.form.modelPlaceholder")})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.workspacePath"),name:"workspace_path",style:{flex:"1 1 320px"},children:t.jsx(q,{placeholder:e("settings.schedulesTab.optional")})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.autoExecute"),name:"auto_execute",valuePropName:"checked",style:{width:160},children:t.jsx(ge,{})})]}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.enhancePrompt"),name:"enhance_prompt",children:t.jsx(q.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})})]}),G=i.useMemo(()=>[{title:e("settings.schedulesTab.columns.name"),key:"name",render:(h,y)=>t.jsxs(V,{vertical:!0,gap:6,children:[t.jsx(je,{strong:!0,children:y.name}),t.jsxs(V,{gap:6,wrap:"wrap",children:[t.jsx(ue,{children:Lo(y.trigger)}),y.timezone?t.jsx(ue,{color:"blue",children:y.timezone}):null,t.jsx(ue,{children:zo(y.misfire_policy)}),t.jsx(ue,{children:Oo(y.overlap_policy)})]})]})},{title:e("settings.schedulesTab.columns.status"),key:"status",render:(h,y)=>{const D=Vo(y);return t.jsxs(V,{vertical:!0,gap:4,children:[t.jsx(ue,{color:D.color,children:D.label}),D.detail?t.jsx(je,{type:"secondary",children:D.detail}):null]})}},{title:e("settings.schedulesTab.columns.activity"),key:"activity",render:(h,y)=>{var D,S,O,X;return t.jsxs(V,{vertical:!0,gap:2,children:[t.jsxs(je,{type:"secondary",children:["queued: ",((D=y.state)==null?void 0:D.queued_run_count)??0]}),t.jsxs(je,{type:"secondary",children:["running: ",((S=y.state)==null?void 0:S.running_run_count)??0]}),t.jsxs(je,{type:"secondary",children:["ok: ",((O=y.state)==null?void 0:O.total_success_count)??0]}),t.jsxs(je,{type:"secondary",children:["fail: ",((X=y.state)==null?void 0:X.total_failure_count)??0]})]})}},{title:e("settings.schedulesTab.columns.nextRun"),key:"next_run_at",render:(h,y)=>t.jsx(je,{type:"secondary",children:No(y)})},{title:e("settings.schedulesTab.columns.lastRun"),key:"last_run_at",render:(h,y)=>t.jsx(je,{type:"secondary",children:$o(y)})},{title:e("settings.schedulesTab.columns.autoExecute"),key:"auto_execute",render:(h,y)=>{var D,S;return t.jsx(je,{type:(D=y.run_config)!=null&&D.auto_execute?void 0:"secondary",children:(S=y.run_config)!=null&&S.auto_execute?e("settings.schedulesTab.yes"):e("settings.schedulesTab.no")})}},{title:e("settings.schedulesTab.columns.model"),key:"model",render:(h,y)=>{var D;return t.jsx(je,{type:"secondary",children:(D=y.run_config)!=null&&D.model?String(y.run_config.model):"-"})}},{title:e("settings.schedulesTab.columns.enabled"),key:"enabled",render:(h,y)=>t.jsx(ge,{checked:y.enabled,onChange:async D=>{try{await Ye.patchSchedule(y.id,{enabled:D}),await T()}catch(S){console.error("[Schedules] Failed to toggle:",S),s.error(e("settings.schedulesTab.updateFailed"))}}})},{title:e("settings.schedulesTab.columns.actions"),key:"actions",render:(h,y)=>{const D=t.jsx(he,{min:1,value:Ao(y.trigger)??void 0,disabled:y.trigger.type!=="interval",onChange:async S=>{const O=typeof S=="number"?S:null;if(!(!O||O<=0))try{await Ye.patchSchedule(y.id,{trigger:zn(O)}),await T()}catch(X){console.error("[Schedules] Failed to patch interval:",X),s.error(e("settings.schedulesTab.updateFailed"))}}});return t.jsxs(V,{vertical:!0,gap:8,children:[t.jsxs(V,{gap:8,wrap:"wrap",children:[t.jsx(z,{size:"small",onClick:()=>{f({open:!0,schedule:y,saving:!1}),u.setFieldsValue(qo(y))},children:e("settings.schedulesTab.actions.edit")}),t.jsx(z,{size:"small",onClick:async()=>{try{await Ye.runScheduleNow(y.id),s.success(e("settings.schedulesTab.enqueuedRun")),await T()}catch(S){console.error("[Schedules] Failed to run now:",S),s.error(e("settings.schedulesTab.runNowFailed"))}},children:e("settings.schedulesTab.actions.runNow")}),t.jsx(z,{size:"small",onClick:async()=>{c(S=>({...S,open:!0,scheduleId:y.id,loading:!0,sessions:[]}));try{const S=await Ye.listScheduleSessions(y.id);c(O=>({...O,open:!0,scheduleId:y.id,loading:!1,sessions:(S.sessions||[]).map(X=>({id:X.id,title:X.title,updated_at:X.updated_at}))}))}catch(S){console.error("[Schedules] Failed to list sessions:",S),s.error(e("settings.schedulesTab.loadSessionsFailed")),c(O=>({...O,loading:!1}))}},children:e("settings.schedulesTab.actions.sessions")}),t.jsx(z,{size:"small",onClick:async()=>{d(S=>({...S,open:!0,scheduleId:y.id,loading:!0,runs:[]}));try{const S=await Ye.listScheduleRuns(y.id);d(O=>({...O,open:!0,scheduleId:y.id,loading:!1,runs:S.runs||[]}))}catch(S){console.error("[Schedules] Failed to list runs:",S),s.error(e("settings.schedulesTab.loadRunsFailed")),d(O=>({...O,loading:!1}))}},children:e("settings.schedulesTab.actions.runs")}),t.jsx(z,{danger:!0,size:"small",onClick:async()=>{try{await Ye.deleteSchedule(y.id),s.success(e("settings.schedulesTab.deleted")),await T()}catch(S){console.error("[Schedules] Failed to delete:",S),s.error(e("settings.schedulesTab.deleteFailed"))}},children:e("settings.schedulesTab.actions.delete")})]}),t.jsxs(V,{gap:8,align:"center",wrap:"wrap",children:[t.jsx(je,{type:"secondary",children:e("settings.schedulesTab.columns.intervalSeconds")}),y.trigger.type==="interval"?D:t.jsx(ve,{title:e("settings.schedulesTab.nonIntervalReadOnly"),children:t.jsx("span",{children:D})})]})]})}}],[u,s,T,e]);return t.jsxs(V,{vertical:!0,gap:16,children:[n,t.jsx(I,{title:e("settings.schedulesTab.createTitle"),className:"lotus-settings-card",children:t.jsxs(_,{form:v,layout:"vertical",initialValues:{name:e("settings.schedulesTab.defaultName"),trigger_type:"interval",interval_seconds:3600,daily_hour:9,daily_minute:0,weekly_weekdays:["mon"],weekly_hour:9,weekly_minute:0,monthly_days:"1",monthly_hour:9,monthly_minute:0,cron_expr:"",timezone:"",start_at:"",end_at:"",enabled:!1,task_message:"",model:"",auto_execute:!0,misfire_policy:"run_once",overlap_policy:"queue_one",catch_up_window_max_runs:1,catch_up_window_max_lateness_seconds:60},onFinish:async h=>{try{const y=!!h.auto_execute,D=be(h.task_message),S=be(h.model);if(y&&!D){s.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:O,errorKey:X}=vn(h);if(!O){s.error(e(X||"settings.schedulesTab.validation.triggerRequired"));return}await Ye.createSchedule({name:String(h.name||"").trim(),trigger:O,timezone:be(h.timezone),start_at:be(h.start_at),end_at:be(h.end_at),misfire_policy:jn(h),overlap_policy:h.overlap_policy,enabled:!!h.enabled,run_config:{system_prompt:be(h.system_prompt),task_message:D,model:S,workspace_path:be(h.workspace_path),enhance_prompt:be(h.enhance_prompt),auto_execute:y}}),s.success(e("settings.schedulesTab.created")),v.resetFields(),await T()}catch(y){console.error("[Schedules] Failed to create schedule:",y),s.error(e("settings.schedulesTab.createFailed"))}},children:[B(C,j),t.jsx(z,{type:"primary",htmlType:"submit",children:e("settings.schedulesTab.actions.create")})]})}),t.jsx(I,{title:e("settings.schedulesTab.listTitle"),className:"lotus-settings-card",extra:t.jsx(z,{onClick:()=>void T(),loading:a,children:e("settings.schedulesTab.actions.refresh")}),children:t.jsx(et,{rowKey:"id",columns:G,dataSource:r,loading:a,pagination:{pageSize:10},scroll:{x:1500}})}),t.jsx(ot,{title:e("settings.schedulesTab.scheduleSessionsTitle"),open:m.open,onCancel:()=>c(h=>({...h,open:!1,scheduleId:null})),footer:null,children:m.loading?t.jsx(je,{type:"secondary",children:e("settings.schedulesTab.loading")}):t.jsx(V,{vertical:!0,gap:8,children:m.sessions.length===0?t.jsx(je,{type:"secondary",children:e("settings.schedulesTab.noSessionsYet")}):m.sessions.map(h=>t.jsxs(V,{justify:"space-between",align:"center",children:[t.jsxs(V,{vertical:!0,style:{minWidth:0},children:[t.jsx(je,{strong:!0,ellipsis:!0,children:h.title}),t.jsxs(je,{type:"secondary",ellipsis:!0,children:[h.id," • ",h.updated_at]})]}),t.jsx(z,{size:"small",onClick:()=>{Yn(h.id,{forceRefreshIndex:!0,forceLoadHistory:!0,subscribeIfRunning:!0,forceSubscribe:!0}),w()},children:e("settings.schedulesTab.actions.open")})]},h.id))})}),t.jsx(ot,{title:e("settings.schedulesTab.scheduleRunsTitle"),open:p.open,onCancel:()=>d(h=>({...h,open:!1,scheduleId:null})),footer:null,width:960,children:p.loading?t.jsx(je,{type:"secondary",children:e("settings.schedulesTab.loading")}):p.runs.length===0?t.jsx(je,{type:"secondary",children:e("settings.schedulesTab.noRunsYet")}):t.jsx(et,{rowKey:"run_id",pagination:{pageSize:8},dataSource:p.runs,columns:[{title:e("settings.schedulesTab.runHistory.columns.status"),key:"status",render:(h,y)=>t.jsx(ue,{color:Fo(y.status),children:y.status})},{title:e("settings.schedulesTab.runHistory.columns.scheduledFor"),dataIndex:"scheduled_for",key:"scheduled_for"},{title:e("settings.schedulesTab.runHistory.columns.startedAt"),key:"started_at",render:(h,y)=>y.started_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.completedAt"),key:"completed_at",render:(h,y)=>y.completed_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.session"),key:"session_id",render:(h,y)=>y.session_id||"-"},{title:e("settings.schedulesTab.runHistory.columns.duration"),key:"execution_duration_ms",render:(h,y)=>y.execution_duration_ms!=null?`${y.execution_duration_ms}ms`:"-"},{title:e("settings.schedulesTab.runHistory.columns.outcome"),key:"outcome_reason",render:(h,y)=>y.outcome_reason||(y.was_catch_up?"catch-up":"-")}]})}),t.jsx(ot,{title:e("settings.schedulesTab.editTitle"),open:b.open,onCancel:()=>f({open:!1,schedule:null,saving:!1}),okText:e("settings.schedulesTab.actions.save"),confirmLoading:b.saving,onOk:()=>u.submit(),forceRender:!0,children:t.jsx(_,{form:u,layout:"vertical",onFinish:async h=>{const y=b.schedule;if(!y)return;const D=!!h.auto_execute,S=be(h.task_message),O=be(h.model);if(D&&!S){s.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:X,errorKey:A}=vn(h);if(!X){s.error(e(A||"settings.schedulesTab.validation.triggerRequired"));return}f(U=>({...U,saving:!0}));try{await Ye.patchSchedule(y.id,{name:String(h.name||"").trim()||void 0,enabled:!!h.enabled,trigger:X,timezone:be(h.timezone),start_at:be(h.start_at),end_at:be(h.end_at),misfire_policy:jn(h),overlap_policy:h.overlap_policy,run_config:{system_prompt:be(h.system_prompt),task_message:S,model:O,workspace_path:be(h.workspace_path),enhance_prompt:be(h.enhance_prompt),auto_execute:D}}),s.success(e("settings.schedulesTab.updated")),f({open:!1,schedule:null,saving:!1}),await T()}catch(U){console.error("[Schedules] Failed to patch schedule:",U),s.error(e("settings.schedulesTab.updateFailed")),f($=>({...$,saving:!1}))}},children:B(x,E)})})]})}const{Text:Lt}=ie,zt=Es.getInstance();function Ho(){const{t:e}=Z(),{modal:s,message:n}=Kt.useApp(),a=Ae(v=>v.chats),o=Ae(v=>v.currentSessionId),r=Ae(v=>v.refreshChats),l=Ae(v=>v.loadChats),m=Ae(v=>v.loadChatHistory),[c,p]=i.useState(!0),[d,b]=i.useState(!1),f=i.useMemo(()=>o?a.find(v=>v.id===o)??null:null,[a,o]),w=async v=>{if(!d){b(!0);try{await v()}finally{b(!1)}}};return t.jsxs(V,{vertical:!0,gap:16,children:[t.jsx(I,{size:"small",title:e("settings.sessionsTab.currentSessionTitle"),children:f?t.jsxs(V,{vertical:!0,gap:4,children:[t.jsx(Lt,{strong:!0,ellipsis:!0,children:f.title}),t.jsxs(Lt,{type:"secondary",ellipsis:!0,children:[e("settings.sessionsTab.id"),": ",f.id," ","•"," ",e("settings.sessionsTab.kind"),": ",f.kind]}),t.jsx(V,{gap:8,wrap:"wrap",style:{marginTop:8},children:t.jsx(z,{danger:!0,loading:d,onClick:()=>{s.confirm({title:e("settings.sessionsTab.clearMessagesTitle"),content:e("settings.sessionsTab.clearMessagesContent"),okText:e("settings.sessionsTab.clear"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await w(async()=>{await zt.clearSession(f.id),await m(f.id),await r(),n.success(e("settings.sessionsTab.sessionCleared"))})}})},children:e("settings.sessionsTab.clearMessages")})})]}):t.jsx(Lt,{type:"secondary",children:e("settings.sessionsTab.noActiveSession")})}),t.jsxs(I,{size:"small",title:e("settings.sessionsTab.bulkCleanupTitle"),children:[t.jsxs(V,{align:"center",gap:8,style:{marginBottom:12},children:[t.jsx(Lt,{children:e("settings.sessionsTab.keepPinned")}),t.jsx(ge,{checked:c,onChange:p})]}),t.jsxs(V,{gap:8,wrap:"wrap",children:[t.jsx(z,{danger:!0,loading:d,onClick:()=>{s.confirm({title:e("settings.sessionsTab.deleteAllTitle"),content:e(c?"settings.sessionsTab.deleteAllKeepPinned":"settings.sessionsTab.deleteAllIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await w(async()=>{await zt.cleanupSessions("all",c),await l(),n.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteAll")}),t.jsx(z,{danger:!0,loading:d,onClick:()=>{s.confirm({title:e("settings.sessionsTab.deleteEmptyTitle"),content:e(c?"settings.sessionsTab.deleteEmptyKeepPinned":"settings.sessionsTab.deleteEmptyIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await w(async()=>{await zt.cleanupSessions("empty",c),await l(),n.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteEmpty")}),t.jsx(z,{danger:!0,loading:d,onClick:()=>{s.confirm({title:e("settings.sessionsTab.deleteChildrenTitle"),content:e(c?"settings.sessionsTab.deleteChildrenKeepPinned":"settings.sessionsTab.deleteChildrenIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await w(async()=>{await zt.cleanupSessions("children",c),await l(),n.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteChildren")})]})]}),t.jsxs(I,{size:"small",title:e("settings.sessionsTab.devResetTitle"),children:[t.jsx(Lt,{type:"secondary",children:e("settings.sessionsTab.devResetDescription")}),t.jsx(V,{style:{marginTop:12},children:t.jsx(z,{danger:!0,type:"primary",loading:d,onClick:()=>{s.confirm({title:e("settings.sessionsTab.devResetConfirmTitle"),content:e("settings.sessionsTab.devResetConfirmContent"),okText:e("settings.sessionsTab.reset"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await w(async()=>{await zt.devResetSessions(),await l(),n.success(e("settings.sessionsTab.devResetDone"))})}})},children:e("settings.sessionsTab.devResetAction")})})]})]})}const{Text:Ze}=ie,{useToken:Ko}=fe,Wo=()=>{const{t:e}=Z(),{token:s}=Ko(),[n,a]=i.useState(Ns()),o=Zn(),r=(l,m)=>{const c={...n,[l]:m};a(c),Qn({[l]:m})};return i.useEffect(()=>{a(Ns())},[]),t.jsx(I,{size:"small",className:"lotus-settings-card",children:t.jsxs(V,{vertical:!0,gap:s.marginMD,children:[!o&&t.jsx(ke,{type:"info",showIcon:!0,message:e("settings.notificationsTab.desktopOnly","Desktop notifications are only available in the Bodhi desktop app.")}),t.jsxs(V,{align:"center",gap:s.marginSM,children:[t.jsx(ba,{}),t.jsx(Ze,{strong:!0,children:e("settings.notificationsTab.title","Desktop Notifications")})]}),t.jsx(Ze,{type:"secondary",style:{fontSize:s.fontSizeSM},children:e("settings.notificationsTab.description","Receive OS-level notifications when the app is in the background and user action is required.")}),t.jsx(Ie,{style:{margin:`${s.marginXS}px 0`}}),t.jsxs(V,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(Ze,{children:e("settings.notificationsTab.enabled","Enable desktop notifications")}),t.jsx(ge,{"data-testid":"notification-enabled-toggle",checked:n.enabled,onChange:l=>r("enabled",l),disabled:!o})]}),t.jsx(Ie,{style:{margin:`${s.marginXS}px 0`}}),t.jsx(Ze,{strong:!0,style:{fontSize:s.fontSizeSM,opacity:n.enabled?1:.5},children:e("settings.notificationsTab.events","Notify when:")}),t.jsxs(V,{vertical:!0,gap:s.marginSM,style:{opacity:n.enabled?1:.5,pointerEvents:n.enabled?"auto":"none"},children:[t.jsxs(V,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(Ze,{children:e("settings.notificationsTab.onClarification","Agent needs clarification")}),t.jsx(ge,{"data-testid":"notification-clarification-toggle",checked:n.onClarification,onChange:l=>r("onClarification",l),disabled:!o})]}),t.jsxs(V,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(Ze,{children:e("settings.notificationsTab.onToolApproval","Tool execution needs approval")}),t.jsx(ge,{"data-testid":"notification-tool-approval-toggle",checked:n.onToolApproval,onChange:l=>r("onToolApproval",l),disabled:!o})]}),t.jsxs(V,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(Ze,{children:e("settings.notificationsTab.onContextPressure","Context window is critically full")}),t.jsx(ge,{"data-testid":"notification-context-pressure-toggle",checked:n.onContextPressure,onChange:l=>r("onContextPressure",l),disabled:!o})]}),t.jsxs(V,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(Ze,{children:e("settings.notificationsTab.onSubAgentComplete","Background task completes")}),t.jsx(ge,{"data-testid":"notification-subagent-complete-toggle",checked:n.onSubAgentComplete,onChange:l=>r("onSubAgentComplete",l),disabled:!o})]})]}),t.jsx(Ie,{style:{margin:`${s.marginXS}px 0`}}),t.jsxs(V,{align:"center",gap:s.marginSM,children:[t.jsx(va,{style:{color:s.colorPrimary}}),t.jsx(Ze,{type:"secondary",style:{fontSize:s.fontSizeSM},children:e("settings.notificationsTab.osNote","OS notification permissions may also be required. You can manage them in your system settings.")})]})]})})},{Text:ts,Paragraph:Go}=ie,Jo=({open:e,onCancel:s,onComplete:n,onCopyCode:a,completingAuth:o,copiedUserCode:r,deviceCodeInfo:l,timeRemaining:m,token:c})=>{const{t:p}=Z();return t.jsx(ot,{title:p("settings.providerTab.copilotAuthModalTitle"),open:e,onCancel:s,footer:[t.jsx(z,{onClick:s,children:p("settings.providerTab.cancel")},"cancel"),t.jsx(z,{type:"primary",onClick:n,loading:o,children:p("settings.providerTab.completedAuthorization")},"complete")],children:l&&t.jsxs(F,{direction:"vertical",size:"large",style:{width:"100%"},children:[t.jsx(ke,{message:p("settings.providerTab.browserOpened"),description:t.jsxs("ol",{children:[t.jsx("li",{children:p("settings.providerTab.authStep1")}),t.jsx("li",{children:p("settings.providerTab.authStep2")}),t.jsx("li",{children:p("settings.providerTab.authStep3")})]}),type:"info"}),t.jsx(I,{size:"small",className:"lotus-settings-card",children:t.jsxs(F,{direction:"vertical",style:{width:"100%"},children:[t.jsx(ts,{type:"secondary",children:p("settings.providerTab.visitUrl")}),t.jsx(F,{children:t.jsx(ts,{copyable:{text:l.verification_uri},children:l.verification_uri})})]})}),t.jsx(I,{style:{textAlign:"center",background:c.colorFillTertiary,borderColor:c.colorBorderSecondary},children:t.jsxs(F,{direction:"vertical",style:{width:"100%"},children:[t.jsx(ts,{type:"secondary",children:p("settings.providerTab.enterCode")}),t.jsxs(F,{children:[t.jsx(ts,{style:{color:c.colorText,fontSize:"32px",fontFamily:"monospace",fontWeight:"bold",letterSpacing:"4px"},children:l.user_code}),t.jsx(z,{icon:r?t.jsx(ws,{}):t.jsx(Pn,{}),onClick:a,type:r?"default":"primary",children:p(r?"settings.providerTab.copied":"settings.providerTab.copyCode")})]}),t.jsx("div",{style:{marginTop:8},children:t.jsxs(ue,{color:m<60?"error":m<180?"warning":"success",children:[t.jsx(ja,{style:{marginRight:4}}),"Expires in ",Math.floor(m/60),":",(m%60).toString().padStart(2,"0")]})})]})}),t.jsx(Go,{type:"secondary",children:p("settings.providerTab.afterContinueHint")})]})})},{Password:Tn}=q,{Text:Ke,Paragraph:js}=ie,ss=["openai","anthropic","gemini","copilot","bodhi"],ns=()=>null,Xo=e=>{var n,a;if(!e||typeof e!="object")return!1;const s=e;return!!((n=s.provider)!=null&&n.trim()&&((a=s.model)!=null&&a.trim()))},Yo=(e,s,n)=>{const a=e;a[s]={...a[s]??{},model:n}},Sn=e=>t.jsxs(F,{direction:"vertical",size:4,children:[t.jsxs(Ke,{type:"secondary",children:[e("settings.providerTab.responsesOnlyHelp1")," ",t.jsx(Ke,{code:!0,children:"/responses"}),"."]}),t.jsx(Ke,{type:"secondary",children:e("settings.providerTab.responsesOnlyHelp2")})]}),Zo=["low","medium","high","xhigh","max"],bt=(e,s)=>t.jsx(re,{placeholder:e("settings.providerTab.reasoningEffortDefault","Default"),allowClear:!0,value:s==null?void 0:s.value,onChange:s!=null&&s.onChange?n=>{var a;return(a=s.onChange)==null?void 0:a.call(s,n??void 0)}:void 0,disabled:s==null?void 0:s.disabled,size:s==null?void 0:s.size,style:s==null?void 0:s.style,"data-testid":s==null?void 0:s["data-testid"],children:Zo.map(n=>t.jsx(re.Option,{value:n,children:e(`chat.input.reasoning.${n}`)},n))}),Qo=()=>{const{t:e}=Z(),{token:s}=fe.useToken(),{message:n}=Kt.useApp(),[a]=_.useForm(),[o,r]=i.useState(!1),[l,m]=i.useState(!1),[c,p]=i.useState("copilot"),[d,b]=i.useState(!1),[f,w]=i.useState(null),[v,u]=i.useState(!1),[C,j]=i.useState(!1),[x,E]=i.useState(null),[T,P]=i.useState(!1),[ee,R]=i.useState(!1),[B,G]=i.useState(0),[h,y]=i.useState(!1),[D,S]=i.useState([]),[O,X]=i.useState(!1),[A,U]=i.useState("idle"),[$,oe]=i.useState(null);i.useEffect(()=>{if(A!=="success")return;const M=setTimeout(()=>{U("idle"),oe(null)},2e3);return()=>clearTimeout(M)},[A]),i.useEffect(()=>{if(!T||!x){G(0);return}G(x.expires_in);const M=setInterval(()=>{G(k=>k<=1?(clearInterval(M),0):k-1)},1e3);return()=>clearInterval(M)},[T,x]);const de=i.useCallback(async()=>{var M;try{r(!0);const k=await Be.getProviderConfig();let J=k.defaults;if(!((M=J==null?void 0:J.chat)!=null&&M.model)&&k.provider&&k.providers){const ce=k.provider,ne=k.providers[ce],Fe=ne==null?void 0:ne.model;Fe&&(J={chat:{provider:ce,model:Fe}})}const H={provider:k.provider,defaults:J,providers:k.providers||{},features:k.features};rt("[Provider]","Loaded provider config:",H);const Y={...H.providers||{}};ss.forEach(ce=>{const ne=Y[ce];ne&&ne.request_overrides&&typeof ne.request_overrides=="object"&&(ne.request_overrides_json=JSON.stringify(ne.request_overrides,null,2))}),p(H.provider),a.setFieldsValue({...H,providers:Y,defaults:H.defaults}),b(!0)}catch(k){n.error(e("settings.providerTab.loadConfigFailed")),console.error("Failed to load provider config:",k)}finally{r(!1)}},[a,n,e]),K=i.useCallback(async()=>{try{const M=await Be.getEnvVars();S(M.entries||[])}catch(M){console.warn("Failed to load env vars for provider overrides:",M)}},[]),L=i.useCallback(async()=>{try{u(!0);const M=await Be.getCopilotAuthStatus();w(M)}catch(M){console.error("Failed to check Copilot auth status:",M),w({authenticated:!1,message:e("settings.providerTab.checkStatusFailed")})}finally{u(!1)}},[e]);i.useEffect(()=>{de(),K(),Vt.getState().loadCatalog(),L()},[de,K,L]);const W=async()=>{try{j(!0);const M=await Be.startCopilotAuth();E(M),P(!0)}catch(M){n.error(e("settings.providerTab.startCopilotAuthFailed")),console.error("Failed to start Copilot authentication:",M)}finally{j(!1)}},Q=async()=>{if(x)try{R(!0),await Be.completeCopilotAuth({device_code:x.device_code,interval:x.interval||5,expires_in:x.expires_in}),n.success(e("settings.providerTab.copilotAuthSuccess")),P(!1),E(null),await L()}catch(M){n.error(e("settings.providerTab.completeAuthFailed")),console.error("Authentication completion failed:",M)}finally{R(!1)}},te=async()=>{if(x)try{await In(x.user_code),y(!0),n.success(e("settings.providerTab.userCodeCopied")),setTimeout(()=>y(!1),2e3)}catch{n.error(`${e("settings.providerTab.copyCodeFailedPrefix")} ${x.user_code}`)}},Me=async()=>{try{j(!0),await Be.logoutCopilot(),n.success(e("settings.providerTab.logoutSuccess")),await L()}catch(M){n.error(e("settings.providerTab.logoutFailed")),console.error("Failed to logout:",M)}finally{j(!1)}},qe=i.useCallback(async()=>{X(!0);try{const M=await Be.fetchCatalogModels();await Vt.getState().loadCatalog();const k=M.fetched.filter(H=>H.models&&H.models.length>0).length;M.fetched.filter(H=>H.error).length>0?n.warning(e("settings.providerTab.fetchModelsPartialSuccess",{success:k,total:M.fetched.length})):n.success(e("settings.providerTab.fetchModelsSuccess",{count:k}))}catch{n.error(e("settings.providerTab.fetchModelsFailed"))}finally{X(!1)}},[n,e]),Pe=M=>ea(M)||M instanceof Error?M.message:e("settings.providerTab.unknownError"),kt=M=>{a.setFields([{name:["provider"],errors:[]},{name:["providers",M,"api_key"],errors:[]},{name:["defaults","chat"],errors:[]}])},ft=M=>{const k=M.trim();return k?k.includes(".")?k.split(".").filter(Boolean):k==="provider"?["provider"]:k==="provider/providers"?["provider"]:null:null},Mt=(M,k)=>{if(!M.length)return;const J=M.map(H=>{const Y=ft(H.path);return Y?{name:Y,errors:[H.message]}:H.message.toLowerCase().includes("api key")?{name:["providers",k,"api_key"],errors:[H.message]}:{name:["provider"],errors:[H.message]}}).filter((H,Y,ce)=>ce.findIndex(ne=>JSON.stringify(ne.name)===JSON.stringify(H.name))===Y);J.length&&a.setFields(J)},Ct=async M=>{var J;const k=M.provider||c;kt(k);try{const Y=await Bt.getInstance().validateBambooConfigPatch({provider:M.provider,providers:M.providers||{},defaults:M.defaults});if(Y.valid)return{valid:!0};const ce=((J=Y.errors)==null?void 0:J.provider)||[];Mt(ce,k);const ne=ce[0];return{valid:!1,message:(ne==null?void 0:ne.message)||e("settings.providerTab.invalidConfig")}}catch(H){return console.warn("Config validation failed, falling back to save:",H),{valid:!0}}},it=async(M,k)=>{var J,H;try{r(!0);const Y={provider:M.provider,defaults:M.defaults,providers:{...M.providers||{}},features:M.features},ce=(J=Y.defaults)==null?void 0:J.chat;if(!Xo(ce)){const _e=e("settings.providerTab.selectModelRequired");if(a.setFields([{name:["defaults","chat"],errors:[_e]}]),(k==null?void 0:k.showMessage)!==!1&&n.error(_e),k!=null&&k.throwOnError)throw new Error(_e);return}const ne=Y.providers;for(const _e of ss){const Ge=ne[_e];if(!Ge)continue;const Je=Ge.request_overrides_json;if(typeof Je!="string")continue;const ct=Je.trim();if(!ct)delete Ge.request_overrides;else try{Ge.request_overrides=JSON.parse(ct)}catch(ms){const st=`Invalid request_overrides JSON for ${_e}: ${ms.message}`;if(a.setFields([{name:["providers",_e,"request_overrides_json"],errors:[st]}]),(k==null?void 0:k.showMessage)!==!1&&n.error(st),k!=null&&k.throwOnError)throw ms;return}delete Ge.request_overrides_json}const Fe={...Y.providers||{}},De=Y.provider,Se=(H=Y.defaults)==null?void 0:H.chat;Se!=null&&Se.model&&De&&Yo(Fe,De,Se.model);const Ue={provider:Y.provider,defaults:Y.defaults,providers:Fe,features:Y.features},xe=await Ct(Y);if(!xe.valid){const _e=xe.message||e("settings.providerTab.invalidConfig");if((k==null?void 0:k.showMessage)!==!1&&n.error(`${e("settings.providerTab.invalidConfigPrefix")}: ${_e}`),k!=null&&k.throwOnError)throw new Error(_e);return}rt("[Provider]","Saving provider config:",Ue),await Be.saveProviderConfig(Ue),(k==null?void 0:k.showMessage)!==!1&&n.success(e("settings.providerTab.saveConfigSuccess"))}catch(Y){const ce=Pe(Y);if((k==null?void 0:k.showMessage)!==!1&&n.error(ce?`${e("settings.providerTab.saveConfigErrorPrefix")}: ${ce}`:e("settings.providerTab.saveConfigFailed")),console.error("Failed to save configuration:",Y),k!=null&&k.throwOnError)throw Y}finally{r(!1)}},lt=async M=>{var k,J,H,Y,ce;try{m(!0);const{useProviderStore:ne}=await ks(async()=>{const{useProviderStore:st}=await import("./App-D0lPE9xB.js").then(ps=>ps.a4);return{useProviderStore:st}},__vite__mapDeps([4,1,2,3,5,6,7,8]),import.meta.url),{useAppStore:Fe}=await ks(async()=>{const{useAppStore:st}=await import("./App-D0lPE9xB.js").then(ps=>ps.a5);return{useAppStore:st}},__vite__mapDeps([4,1,2,3,5,6,7,8]),import.meta.url),De=(k=ne.getState().providerConfig.defaults)==null?void 0:k.chat;await ne.getState().loadProviderConfig();const Se=(J=ne.getState().providerConfig.defaults)==null?void 0:J.chat;ne.getState().setSelectedModelRef(null);const Ue=Fe.getState().currentSessionId,xe=Ue&&Fe.getState().chats.find(st=>st.id===Ue)||null,_e=De?`${De.provider}/${De.model}`:null,Ge=Se?`${Se.provider}/${Se.model}`:null,Je=(H=xe==null?void 0:xe.config)!=null&&H.model_ref?`${xe.config.model_ref.provider}/${xe.config.model_ref.model}`:null,ct=((ce=(Y=xe==null?void 0:xe.config)==null?void 0:Y.model)==null?void 0:ce.trim())||null;!!(Ue&&(xe!=null&&xe.config)&&Se&&Ge!==_e&&(!Je||Je===_e)&&(!ct||ct===(De==null?void 0:De.model)))&&Ue&&(xe!=null&&xe.config)&&Se&&Fe.getState().updateSession(Ue,{config:{...xe.config,model:Se.model,model_ref:Se}}),(M==null?void 0:M.showMessage)!==!1&&n.success(e("settings.providerTab.applyConfigSuccess"))}catch(ne){const Fe=Pe(ne);if((M==null?void 0:M.showMessage)!==!1&&n.error(Fe?`${e("settings.providerTab.applyConfigErrorPrefix")}: ${Fe}`:e("settings.providerTab.applyConfigFailed")),console.error("Failed to apply configuration:",ne),M!=null&&M.throwOnError)throw ne}finally{m(!1)}},ze=async M=>{try{const k=a.getFieldsValue(!0);await it(k,{throwOnError:!0}),await lt({throwOnError:!0})}catch{}},Et=async(M,k)=>{if(!(M==="chat"&&!k)&&A!=="saving"){U("saving"),oe(null);try{const J=a.getFieldsValue(!0),H=J.defaults;if(!(H!=null&&H.chat))throw new Error(e("settings.providerTab.selectModelRequired"));J.defaults={...H,[M]:k},await it(J,{showMessage:!1,throwOnError:!0}),await lt({showMessage:!1,throwOnError:!0}),U("success"),n.success(e("settings.providerTab.modelUpdated"))}catch(J){const H=Pe(J);U("error"),oe(H),n.error(H?`${e("settings.providerTab.updateModelErrorPrefix")}: ${H}`:e("settings.providerTab.updateModelFailed"))}}},g=async()=>{if(A!=="saving"){U("saving"),oe(null);try{const M=a.getFieldsValue(!0);await it(M,{showMessage:!1,throwOnError:!0}),await lt({showMessage:!1,throwOnError:!0}),U("success"),n.success(e("settings.providerTab.reasoningEffortUpdated","Reasoning effort updated"))}catch(M){const k=Pe(M);U("error"),oe(k),n.error(k?`${e("settings.providerTab.updateReasoningEffortErrorPrefix","Failed to update reasoning effort")}: ${k}`:e("settings.providerTab.updateReasoningEffortFailed","Failed to update reasoning effort"))}}},se=(M,k)=>{if(!M)return null;const J=Dt[M],H=a.getFieldValue(["providers",M,"reasoning_effort"]);return t.jsx("div",{style:{marginTop:(k==null?void 0:k.marginTop)??8},children:t.jsxs(F,{direction:"vertical",size:4,style:{width:"100%"},children:[t.jsx(Ke,{strong:!0,children:(k==null?void 0:k.label)||`${J} · ${e("settings.providerTab.reasoningEffortOptional","Reasoning Effort (Optional)")}`}),bt(e,{value:H,disabled:A==="saving",size:k==null?void 0:k.size,style:{width:"100%"},"data-testid":k==null?void 0:k.dataTestId,onChange:Y=>{a.setFieldValue(["providers",M,"reasoning_effort"],Y),k!=null&&k.autoSave&&g()}}),t.jsx(Ke,{type:"secondary",children:(k==null?void 0:k.helperText)||e("settings.providerTab.reasoningEffortHelp","Default reasoning effort for requests sent through this provider.")})]})})},le=i.useCallback(M=>{const k=a.getFieldValue(["providers",M]);return k?M==="copilot"?(f==null?void 0:f.authenticated)??!1:!!k.api_key:!1},[a,f]),Ce=()=>{const M=J=>{const H=a.getFieldValue(["defaults",J]);return t.jsx(ta,{value:H,disabled:A==="saving",onChange:Y=>{a.setFieldValue(["defaults",J],Y),Et(J,Y)}})},k=(J,H,Y)=>t.jsxs("div",{children:[t.jsx(Ke,{strong:!0,children:H}),t.jsx("div",{style:{marginTop:8},children:M(J)}),t.jsx(_.Item,{noStyle:!0,shouldUpdate:!0,children:()=>{const ce=a.getFieldValue(["defaults",J]),ne=ce==null?void 0:ce.provider;return se(ne,{autoSave:!0,dataTestId:`model-preference-${J}-reasoning-effort`,label:ne?`${Dt[ne]} · ${e("settings.providerTab.reasoningEffortOptional","Reasoning Effort (Optional)")}`:e("settings.providerTab.reasoningEffortOptional","Reasoning Effort (Optional)"),helperText:e("settings.providerTab.reasoningEffortHelp","Default reasoning effort for requests sent through this provider.")})}}),Y?t.jsx(Ke,{type:"secondary",children:Y}):null]});return t.jsxs(I,{size:"small",title:e("settings.providerTab.modelPreferences","模型偏好"),style:{marginBottom:16},children:[t.jsx(_.Item,{name:["defaults","chat"],noStyle:!0,preserve:!0,children:t.jsx(ns,{})}),t.jsx(_.Item,{name:["defaults","fast"],noStyle:!0,preserve:!0,children:t.jsx(ns,{})}),t.jsx(_.Item,{name:["defaults","sub_agent"],noStyle:!0,preserve:!0,children:t.jsx(ns,{})}),t.jsx(_.Item,{name:["defaults","vision"],noStyle:!0,preserve:!0,children:t.jsx(ns,{})}),t.jsxs(F,{direction:"vertical",size:16,style:{width:"100%"},children:[k("chat",e("settings.providerTab.defaultModel")),k("fast",e("settings.providerTab.fastModel"),e("settings.providerTab.fastModelHelp")),k("sub_agent",e("settings.providerTab.subAgentModel","Sub Agent Model (Optional)"),e("settings.providerTab.subAgentModelHelp","Default model for new Sub Agents. Uses Fast Model when not set.")),k("vision",e("settings.providerTab.visionModel"),e("settings.providerTab.visionModelHelp"))]})]})},me=M=>{const k=D.map(H=>H.name);return t.jsx(_.Item,{name:["providers",M,"request_overrides_json"],label:"Advanced Request Overrides (JSON)",extra:t.jsxs(F,{direction:"vertical",size:4,children:[t.jsx(Ke,{type:"secondary",children:"Customize provider request headers/body patch rules."}),t.jsxs(Ke,{type:"secondary",children:["Env var injection:"," ",t.jsx(Ke,{code:!0,children:'{ "type": "env_ref", "name": "YOUR_ENV_NAME" }'})]}),k.length>0&&t.jsx(F,{wrap:!0,size:[6,6],children:k.map(H=>t.jsx(ue,{children:H},H))})]}),children:t.jsx(q.TextArea,{autoSize:{minRows:8,maxRows:20},placeholder:`{
3
- "common": {
4
- "headers": {
5
- "x-request-id": { "type": "generated", "generator": "uuid" },
6
- "x-tenant": { "type": "env_ref", "name": "TENANT_ID" }
7
- }
8
- },
9
- "rules": [
10
- {
11
- "model_pattern": "gpt-5*",
12
- "scope": {
13
- "body_patch": [
14
- { "path": "metadata.trace_id", "op": "set", "value": { "type": "generated", "generator": "uuid" } }
15
- ]
16
- }
17
- }
18
- ]
19
- }`,style:{fontFamily:"SFMono-Regular, Menlo, Monaco, Consolas, monospace"}})})},Ee=M=>{switch(M){case"openai":return t.jsxs(t.Fragment,{children:[t.jsx(_.Item,{name:["providers","openai","api_key"],label:e("settings.providerTab.openaiApiKey"),rules:[{required:!0,message:e("settings.providerTab.openaiApiKeyRequired")}],children:t.jsx(q.Password,{"data-testid":"api-key-input",placeholder:"sk-...",prefix:t.jsx(Zt,{})})}),t.jsx(_.Item,{name:["providers","openai","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.openaiBaseUrlHelp"),children:t.jsx(q,{placeholder:"https://api.openai.com/v1"})}),t.jsx(_.Item,{name:["providers","openai","reasoning_effort"],label:e("settings.providerTab.reasoningEffortOptional","Reasoning Effort (Optional)"),extra:e("settings.providerTab.reasoningEffortHelp","Default reasoning effort for requests sent through this provider."),children:bt(e)}),t.jsx(_.Item,{name:["providers","openai","responses_only_models"],label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:Sn(e),children:t.jsx(re,{mode:"tags",placeholder:'e.g. "gpt-5.3-codex", "gpt-5*"',tokenSeparators:[","," ",`
20
- `," "]})}),t.jsx(Ie,{dashed:!0}),me("openai")]});case"anthropic":return t.jsxs(t.Fragment,{children:[t.jsx(_.Item,{name:["providers","anthropic","api_key"],label:e("settings.providerTab.anthropicApiKey"),rules:[{required:!0,message:e("settings.providerTab.anthropicApiKeyRequired")}],children:t.jsx(Tn,{placeholder:"sk-ant-...",prefix:t.jsx(Zt,{})})}),t.jsx(_.Item,{name:["providers","anthropic","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.anthropicBaseUrlHelp"),children:t.jsx(q,{placeholder:"https://api.anthropic.com/v1"})}),t.jsx(_.Item,{name:["providers","anthropic","max_tokens"],label:e("settings.providerTab.maxTokensOptional"),extra:e("settings.providerTab.maxTokensHelp"),children:t.jsx(q,{type:"number",placeholder:"4096",min:1,max:1e5})}),t.jsx(_.Item,{name:["providers","anthropic","reasoning_effort"],label:e("settings.providerTab.reasoningEffortOptional","Reasoning Effort (Optional)"),extra:e("settings.providerTab.reasoningEffortHelp","Default reasoning effort for requests sent through this provider."),children:bt(e)}),t.jsx(Ie,{dashed:!0}),me("anthropic")]});case"gemini":return t.jsxs(t.Fragment,{children:[t.jsx(_.Item,{name:["providers","gemini","api_key"],label:e("settings.providerTab.geminiApiKey"),rules:[{required:!0,message:e("settings.providerTab.geminiApiKeyRequired")}],children:t.jsx(Tn,{placeholder:"AIza...",prefix:t.jsx(Zt,{})})}),t.jsx(_.Item,{name:["providers","gemini","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.geminiBaseUrlHelp"),children:t.jsx(q,{placeholder:"https://generativelanguage.googleapis.com/v1beta"})}),t.jsx(_.Item,{name:["providers","gemini","reasoning_effort"],label:e("settings.providerTab.reasoningEffortOptional","Reasoning Effort (Optional)"),extra:e("settings.providerTab.reasoningEffortHelp","Default reasoning effort for requests sent through this provider."),children:bt(e)}),t.jsx(Ie,{dashed:!0}),me("gemini")]});case"copilot":return t.jsxs(t.Fragment,{children:[t.jsxs(I,{size:"small",style:{marginBottom:16},title:e("settings.providerTab.authStatusTitle"),extra:v?t.jsx(qt,{size:"small"}):f!=null&&f.authenticated?t.jsx(ue,{icon:t.jsx(ws,{}),color:"success",children:e("settings.providerTab.authenticated")}):t.jsx(ue,{icon:t.jsx(Ws,{}),color:"error",children:e("settings.providerTab.notAuthenticated")}),children:[(f==null?void 0:f.message)&&t.jsx(js,{type:"secondary",style:{marginBottom:16},children:f.message}),t.jsxs(F,{children:[f!=null&&f.authenticated?t.jsx(z,{danger:!0,icon:t.jsx(Ta,{}),onClick:Me,loading:C,children:e("settings.providerTab.logoutCopilot")}):t.jsx(z,{type:"primary",icon:t.jsx(Sa,{}),onClick:W,loading:C,children:e("settings.providerTab.authenticateCopilot")}),t.jsx(z,{onClick:L,loading:v,children:e("settings.providerTab.refreshStatus")})]})]}),t.jsx(_.Item,{name:["providers","copilot","headless_auth"],label:e("settings.providerTab.headlessAuth"),valuePropName:"checked",extra:e("settings.providerTab.headlessAuthHelp"),children:t.jsx(ge,{})}),t.jsx(_.Item,{name:["providers","copilot","reasoning_effort"],label:e("settings.providerTab.reasoningEffortOptional","Reasoning Effort (Optional)"),extra:e("settings.providerTab.reasoningEffortHelp","Default reasoning effort for requests sent through this provider."),children:bt(e)}),t.jsx(_.Item,{name:["providers","copilot","responses_only_models"],label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:Sn(e),children:t.jsx(re,{mode:"tags",placeholder:'e.g. "gpt-5.3-codex", "gpt-5*"',tokenSeparators:[","," ",`
21
- `," "]})}),t.jsx(Ie,{dashed:!0}),me("copilot"),t.jsxs(js,{type:"secondary",children:[e("settings.providerTab.copilotUsageTitle"),t.jsxs("ul",{style:{marginTop:8,marginBottom:0},children:[t.jsx("li",{children:e("settings.providerTab.copilotUsageStep1")}),t.jsx("li",{children:e("settings.providerTab.copilotUsageStep2")}),t.jsx("li",{children:e("settings.providerTab.copilotUsageStep3")})]})]})]});case"bodhi":return t.jsxs(t.Fragment,{children:[t.jsx(_.Item,{name:["providers","bodhi","api_key"],label:"Bodhi API Key",rules:[{required:!0,message:"API key is required"}],children:t.jsx(q.Password,{"data-testid":"bodhi-api-key-input",placeholder:"bhi_sk_...",prefix:t.jsx(Zt,{})})}),t.jsx(_.Item,{name:["providers","bodhi","base_url"],label:"Base URL",extra:"Your Bodhi Server endpoint address",children:t.jsx(q,{placeholder:"http://localhost:8080"})}),t.jsx(_.Item,{name:["providers","bodhi","target_provider"],label:"Target Provider",extra:"Which upstream provider to route through Bodhi",children:t.jsxs(re,{placeholder:"openai",allowClear:!0,children:[t.jsx(re.Option,{value:"openai",children:"OpenAI"}),t.jsx(re.Option,{value:"anthropic",children:"Anthropic"}),t.jsx(re.Option,{value:"gemini",children:"Gemini"})]})}),t.jsx(_.Item,{name:["providers","bodhi","reasoning_effort"],label:e("settings.providerTab.reasoningEffortOptional","Reasoning Effort (Optional)"),extra:e("settings.providerTab.reasoningEffortHelp","Default reasoning effort for requests sent through this provider."),children:bt(e)}),t.jsx(Ie,{dashed:!0}),me("bodhi")]});default:return null}},gs=M=>{const k=le(M),J=Dt[M];return t.jsxs(F,{size:"small",children:[t.jsx("span",{style:{fontWeight:500},children:J}),k?t.jsx(ue,{color:"success",style:{fontSize:11},children:e("settings.providerTab.authenticated")}):t.jsx(ue,{color:"default",style:{fontSize:11},children:e("settings.providerTab.providerNotConfigured")})]})};return t.jsxs(I,{title:e("settings.providerTab.title"),loading:o&&!d,className:"lotus-settings-card",children:[t.jsx(js,{type:"secondary",children:e("settings.providerTab.description")}),t.jsx(Ie,{}),t.jsxs(_,{form:a,layout:"vertical",onFinish:ze,disabled:o&&!d,children:[t.jsx(_.Item,{name:"provider",label:e("settings.providerTab.activeProvider"),rules:[{required:!0,message:e("settings.providerTab.selectProviderRequired")}],children:t.jsx(re,{"data-testid":"provider-select",size:"large",onChange:M=>p(M),children:Object.keys(Dt).map(M=>t.jsx(re.Option,{value:M,children:Dt[M]},M))})}),t.jsx(_.Item,{noStyle:!0,shouldUpdate:!0,children:()=>se(a.getFieldValue("provider")||c,{autoSave:!0,size:"middle",marginTop:0,dataTestId:"active-provider-reasoning-effort",label:e("settings.providerTab.activeProviderReasoningEffort","Active Provider Reasoning Effort"),helperText:e("settings.providerTab.reasoningEffortHelp","Default reasoning effort for requests sent through this provider.")})}),t.jsx(Ie,{}),t.jsxs("div",{style:{marginBottom:16},children:[t.jsx(z,{icon:t.jsx(St,{}),onClick:qe,loading:O,children:e(O?"settings.providerTab.fetchingAllModels":"settings.providerTab.fetchAllModels")}),A==="saving"&&t.jsx(qt,{size:"small",style:{marginLeft:8}}),A==="success"&&t.jsx(ws,{style:{color:"var(--lotus-chart-secondary)",marginLeft:8}}),A==="error"&&t.jsx(ve,{title:$,children:t.jsx(Ws,{style:{color:"var(--lotus-chart-danger)",marginLeft:8}})})]}),Ce(),t.jsx(Ds,{defaultActiveKey:ss.filter(M=>le(M)),ghost:!0,style:{marginBottom:16},items:ss.map(M=>({key:M,label:gs(M),children:Ee(M)}))}),t.jsx(Ie,{}),t.jsx(F,{size:"middle",children:t.jsx(z,{"data-testid":"save-api-settings",type:"primary",htmlType:"submit",icon:t.jsx(ds,{}),loading:o||l,size:"large",children:e("settings.providerTab.saveAndApply")})})]}),t.jsx(Jo,{open:T,onCancel:()=>P(!1),onComplete:Q,onCopyCode:te,completingAuth:ee,copiedUserCode:h,deviceCodeInfo:x,timeRemaining:B,token:s})]})},{Text:_n}=ie,ei=({skill:e,disabled:s=!1,busy:n=!1,onToggleDisabled:a})=>{const{t:o}=Z(),{token:r}=fe.useToken();return t.jsx(I,{title:t.jsxs(F,{size:r.marginXS,wrap:!0,style:{width:"100%",justifyContent:"space-between"},children:[t.jsxs(F,{size:r.marginXS,wrap:!0,children:[t.jsx("span",{children:e.name}),s&&t.jsx(ue,{color:"default",children:o("components.skillManager.disabledTag")}),e.license&&t.jsxs(ue,{color:"processing",children:["License: ",e.license]})]}),a&&t.jsx(ge,{checked:!s,loading:n,onChange:l=>a(e.id,!l),checkedChildren:o("components.skillManager.switchEnabled"),unCheckedChildren:o("components.skillManager.switchDisabled")})]}),styles:{body:{padding:r.paddingMD}},style:{opacity:s?.72:1},children:t.jsxs(F,{direction:"vertical",size:r.marginXS,style:{width:"100%"},children:[t.jsx(_n,{type:"secondary",children:e.description}),e.compatibility&&t.jsxs(_n,{type:"secondary",children:["Compatibility: ",e.compatibility]}),e.tool_refs.length>0&&t.jsx(F,{size:r.marginXXS,wrap:!0,children:e.tool_refs.map(l=>t.jsx(ue,{style:{background:r.colorFillSecondary,borderColor:r.colorBorderSecondary,color:r.colorText},children:l},l))})]})})},ti=3e4,si=()=>{const{t:e}=Z(),{message:s}=Kt.useApp(),n=at(R=>R.config),a=at(R=>R.loadConfig),o=at(R=>R.saveConfig),[r,l]=i.useState([]),[m,c]=i.useState(!1),[p,d]=i.useState(null),[b,f]=i.useState(null),[w,v]=i.useState(""),[u,C]=i.useState(new Date),j=i.useMemo(()=>{var R;return new Set((((R=n==null?void 0:n.skills)==null?void 0:R.disabled)??[]).map(B=>B.trim()).filter(Boolean))},[n]),x=i.useCallback(async(R=!0)=>{c(!0),d(null);try{const[B]=await Promise.all([sa.listSkills({includeDisabled:!0},R),a({force:R})]);l(B.skills),C(new Date)}catch(B){const G=B instanceof Error?B.message:e("components.skillManager.loadFailed");d(G)}finally{c(!1)}},[a,e]);i.useEffect(()=>{x(!0);const R=setInterval(()=>{x(!0)},ti);return()=>clearInterval(R)},[x]),i.useEffect(()=>{const R=()=>{x(!0)};return window.addEventListener("focus",R),()=>window.removeEventListener("focus",R)},[x]);const E=i.useCallback(async()=>{await x(!0),s.success(e("components.skillManager.skillsRefreshed"))},[x,e]);i.useEffect(()=>{p&&(s.error(p),d(null))},[p]);const T=i.useCallback(async(R,B)=>{var G;f(R);try{const h=await a({force:!0}),y=((G=h==null?void 0:h.skills)==null?void 0:G.disabled)??[],D=Array.from(new Set((B?[...y,R]:y.filter(S=>S!==R)).map(S=>S.trim()).filter(Boolean))).sort();await o({...h??{},skills:{...(h==null?void 0:h.skills)??{},disabled:D}}),s.success(e("components.skillManager.skillStateSaved"))}catch(h){s.error(h instanceof Error?h.message:e("components.skillManager.saveFailed"))}finally{f(null)}},[a,o,e]),P=r.filter(R=>{const B=w.trim().toLowerCase();return!(B&&![R.name,R.description,R.license??"",R.compatibility??"",...R.tool_refs].join(" ").toLowerCase().includes(B))}),ee=()=>{const B=new Date().getTime()-u.getTime(),G=Math.floor(B/1e3);if(G<5)return e("components.skillManager.justNow");if(G<60)return e("components.skillManager.secondsAgo",{count:G});const h=Math.floor(G/60);return h<60?e("components.skillManager.minutesAgo",{count:h}):u.toLocaleTimeString()};return t.jsx("div",{style:{padding:"24px"},children:t.jsxs(I,{className:"lotus-settings-card",title:t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[t.jsx("span",{children:e("components.skillManager.title")}),t.jsx(z,{icon:t.jsx(St,{spin:m}),onClick:E,loading:m,size:"small",children:e("components.skillManager.refresh")}),t.jsx("span",{className:"lotus-settings-note",style:{fontSize:"12px",marginLeft:"auto"},children:e("components.skillManager.lastUpdated",{value:ee()})})]}),children:[t.jsx("div",{className:"lotus-settings-note",style:{marginBottom:"16px"},children:e("components.skillManager.readOnlyHint")}),t.jsx("div",{className:"lotus-settings-note",style:{marginBottom:"16px"},children:e("components.skillManager.disabledHint")}),t.jsx(Ve,{style:{marginBottom:"24px"},children:t.jsx(q,{placeholder:e("components.skillManager.searchPlaceholder"),prefix:t.jsx(_a,{}),value:w,onChange:R=>v(R.target.value),allowClear:!0})}),t.jsx(qt,{spinning:m,children:P.length===0?t.jsx(Le,{description:e(w?"components.skillManager.noMatch":"components.skillManager.noSkillsFound")}):t.jsx(We,{grid:{gutter:16,xs:1,sm:2,md:3,lg:3,xl:4},dataSource:P,renderItem:R=>t.jsx(We.Item,{children:t.jsx(ei,{skill:R,disabled:j.has(R.id),busy:b===R.id,onToggleDisabled:T})})})})]})})},{Title:ni,Text:Ts,Paragraph:ai}=ie,wn="model_limits",Cs="modelLimitsConfigs",kn="defaultBudgetStrategy",$e=1e3;function Mn(e){return[{vendor:"OpenAI (GPT-5)",model_pattern:"gpt-5.4-thinking",max_context_tokens:1e6,max_output_tokens:128e3,safety_margin:$e,note:e("settings.modelLimits.defaults.gpt54")},{vendor:"OpenAI (GPT-5)",model_pattern:"gpt-5.3-codex",max_context_tokens:4e5,max_output_tokens:128e3,safety_margin:$e,note:e("settings.modelLimits.defaults.gpt53Codex")},{vendor:"OpenAI (GPT-5)",model_pattern:"gpt-5.2-pro",max_context_tokens:256e3,max_output_tokens:64e3,safety_margin:$e,note:e("settings.modelLimits.defaults.gpt52Pro")},{vendor:"OpenAI (GPT-5)",model_pattern:"gpt-5-mini",max_context_tokens:4e5,max_output_tokens:128e3,safety_margin:$e,note:e("settings.modelLimits.defaults.gpt5Mini")},{vendor:"OpenAI (Legacy)",model_pattern:"gpt-4.1",max_context_tokens:128e3,max_output_tokens:16384,safety_margin:$e,note:e("settings.modelLimits.defaults.gpt41")},{vendor:"OpenAI (Legacy)",model_pattern:"gpt-4o",max_context_tokens:128e3,max_output_tokens:16e3,safety_margin:$e,note:e("settings.modelLimits.defaults.gpt4o")},{vendor:"Google",model_pattern:"gemini-2.5-pro",max_context_tokens:128e3,max_output_tokens:16e3,safety_margin:$e,note:e("settings.modelLimits.defaults.gemini25Pro")},{vendor:"Moonshot",model_pattern:"kimi-k2.5",max_context_tokens:256e3,max_output_tokens:64e3,safety_margin:$e,note:e("settings.modelLimits.defaults.kimiK25")},{vendor:"Moonshot",model_pattern:"kimi-for-coding",max_context_tokens:256e3,max_output_tokens:64e3,safety_margin:$e,note:e("settings.modelLimits.defaults.kimiCoding")},{vendor:"Zhipu",model_pattern:"glm-5",max_context_tokens:2e5,max_output_tokens:128e3,safety_margin:$e,note:e("settings.modelLimits.defaults.glm5")}]}function ri(e){return Array.isArray(e)?As(e):[]}function Cn(e,s){if(typeof e!="number"||!Number.isFinite(e))return s;const n=Math.floor(e);return n>0?n:s}function oi(e,s){if(typeof e!="number"||!Number.isFinite(e))return s;const n=Math.floor(e);return n>=0?n:s}function ii(e){if(!e||typeof e!="object")return null;const s=e,n=s.model_pattern??s.model;if(typeof n!="string"||!n.trim())return null;const a=Cn(s.max_context_tokens??s.maxContextTokens,128e3),o=Cn(s.max_output_tokens??s.maxOutputTokens,Math.min(4096,Math.floor(a/4))),r=oi(s.safety_margin??s.safetyMargin,$e);return{vendor:typeof s.vendor=="string"&&s.vendor.trim()?s.vendor.trim():"",model_pattern:n.trim(),max_context_tokens:a,max_output_tokens:o,safety_margin:r,note:typeof s.note=="string"?s.note:""}}function As(e){return Array.isArray(e)?e.map(s=>ii(s)).filter(s=>!!s):[]}function li(){const e=localStorage.getItem(Cs);if(!e)return[];try{const s=JSON.parse(e);return As(s)}catch{return[]}}function ci(e){const s=Object.prototype.hasOwnProperty.call(e,wn);return s?{hasModelLimitsKey:s,modelLimits:As(e[wn])}:{hasModelLimitsKey:!1,modelLimits:[]}}function di(e,s){if(e.length===0)return s("settings.modelLimits.validation.atLeastOneRow");const n=new Set;for(const a of e){const o=a.model_pattern.trim();if(!o)return s("settings.modelLimits.validation.modelPatternEmpty");const r=o.toLowerCase();if(n.has(r))return s("settings.modelLimits.validation.duplicateModelPattern",{pattern:o});if(n.add(r),a.max_context_tokens<1e3)return s("settings.modelLimits.validation.contextWindowMin",{pattern:o});if(a.max_output_tokens<1)return s("settings.modelLimits.validation.maxOutputMin",{pattern:o});if(a.max_output_tokens>a.max_context_tokens)return s("settings.modelLimits.validation.maxOutputExceedsContext",{pattern:o});if(a.safety_margin<0)return s("settings.modelLimits.validation.safetyMarginNegative",{pattern:o});if(a.safety_margin>=a.max_context_tokens)return s("settings.modelLimits.validation.safetyMarginTooLarge",{pattern:o})}return null}const ui=()=>{const{t:e}=Z(),[s,n]=i.useState(()=>Mn(e)),[a,o]=i.useState(!1),[r,l]=Tt.useMessage(),m=i.useCallback((u,C)=>{n(j=>j.map((x,E)=>E===u?{...x,...C}:x))},[]),c=i.useCallback(()=>{n(u=>[...u,{vendor:"",model_pattern:"",max_context_tokens:128e3,max_output_tokens:4096,safety_margin:$e,note:""}])},[]),p=i.useCallback(u=>{n(C=>C.filter((j,x)=>x!==u))},[]),d=i.useCallback(async()=>{const u=Mn(e),C=await Te.getModelLimitDefaults(),j=ri(C.model_limits);return j.length>0?j:u},[e]),b=i.useCallback(async()=>{o(!0);try{const u=await Te.getBambooConfig(),{hasModelLimitsKey:C,modelLimits:j}=ci(u);if(j.length>0){n(j);return}if(C){n(await d());return}const x=li();if(x.length>0){await Te.setBambooConfig({model_limits:x}),localStorage.removeItem(Cs),localStorage.removeItem(kn),n(x),r.info(e("settings.modelLimits.migratedFromLocalStorage"));return}n(await d())}catch(u){console.error("Failed to load model limits settings:",u),r.error(e("settings.modelLimits.loadFailed")),n(await d())}finally{o(!1)}},[d,r,e]);i.useEffect(()=>{b()},[b]);const f=async()=>{const u=di(s,e);if(u){r.error(u);return}o(!0);try{await Te.setBambooConfig({model_limits:s}),r.success(e("settings.modelLimits.saveSuccess"))}catch(C){console.error("Failed to save model limits settings:",C),r.error(e("settings.modelLimits.saveFailed"))}finally{o(!1)}},w=async()=>{o(!0);try{const u=await d();await Te.setBambooConfig({model_limits:u}),n(u),localStorage.removeItem(Cs),localStorage.removeItem(kn),r.success(e("settings.modelLimits.resetSuccess"))}catch(u){console.error("Failed to reset model limits settings:",u),r.error(e("settings.modelLimits.resetFailed"))}finally{o(!1)}},v=i.useMemo(()=>[{title:e("settings.modelLimits.columns.vendor"),dataIndex:"vendor",key:"vendor",width:170,render:(u,C,j)=>t.jsx(q,{value:u,placeholder:e("settings.modelLimits.placeholders.vendor"),onChange:x=>m(j,{vendor:x.target.value})})},{title:e("settings.modelLimits.columns.model"),dataIndex:"model_pattern",key:"model_pattern",width:220,render:(u,C,j)=>t.jsx(q,{value:u,placeholder:e("settings.modelLimits.placeholders.model"),onChange:x=>m(j,{model_pattern:x.target.value})})},{title:e("settings.modelLimits.columns.contextWindow"),dataIndex:"max_context_tokens",key:"max_context_tokens",width:180,render:(u,C,j)=>t.jsx(he,{value:u,onChange:x=>m(j,{max_context_tokens:Math.max(1e3,Number(x)||128e3)}),min:1e3,max:2e6,step:1e3,style:{width:"100%"}})},{title:e("settings.modelLimits.columns.maxOutput"),dataIndex:"max_output_tokens",key:"max_output_tokens",width:160,render:(u,C,j)=>t.jsx(he,{value:u,onChange:x=>m(j,{max_output_tokens:Math.max(1,Number(x)||4096)}),min:1,max:2e6,step:256,style:{width:"100%"}})},{title:e("settings.modelLimits.columns.notes"),dataIndex:"note",key:"note",width:240,render:(u,C,j)=>t.jsx(q,{value:u,placeholder:e("settings.modelLimits.placeholders.optional"),onChange:x=>m(j,{note:x.target.value})})},{title:e("settings.modelLimits.columns.actions"),key:"actions",width:100,render:(u,C,j)=>t.jsx(z,{danger:!0,size:"small",onClick:()=>p(j),children:e("settings.modelLimits.actions.remove")})}],[p,e,m]);return t.jsxs("div",{className:"model-limits-settings",children:[l,t.jsxs(I,{children:[t.jsx(ni,{level:4,children:e("settings.modelLimits.title")}),t.jsxs(ai,{type:"secondary",children:[e("settings.modelLimits.descriptionPrefix")," ",t.jsx(Ts,{code:!0,children:"config.json"})," ",e("settings.modelLimits.descriptionSuffix")]}),t.jsx(Ie,{}),t.jsxs(F,{direction:"vertical",size:"small",style:{width:"100%"},children:[t.jsx(Ts,{strong:!0,children:e("settings.modelLimits.defaultsTitle")}),t.jsx(Ts,{type:"secondary",children:e("settings.modelLimits.defaultsDescription")})]}),t.jsx(et,{dataSource:s,columns:v,rowKey:(u,C)=>`${u.model_pattern}-${C}`,pagination:!1,size:"small",style:{margin:"16px 0"},scroll:{x:1150}}),t.jsxs(F,{children:[t.jsx(z,{onClick:c,children:e("settings.modelLimits.actions.addRow")}),t.jsx(z,{type:"primary",icon:t.jsx(ds,{}),onClick:()=>void f(),loading:a,children:e("settings.modelLimits.actions.save")}),t.jsx(z,{icon:t.jsx(St,{}),onClick:()=>void w(),loading:a,children:e("settings.modelLimits.actions.resetToDefaults")}),t.jsx(z,{onClick:()=>void b(),loading:a,children:e("settings.modelLimits.actions.reload")})]})]})]})},{Text:Ss}=ie,{useToken:gi}=fe,mi="bamboo_dark_mode",Si=({themeMode:e,onThemeModeChange:s,locale:n,onLocaleChange:a,onBack:o})=>{const{t:r}=Z(),{token:l}=gi(),{deleteAllChats:m}=Aa(),[c,p]=i.useState(!1),[d,b]=Tt.useMessage(),[f,w]=i.useState(""),[v,u]=i.useState($s()),[C,j]=i.useState(Vs()),[x,E]=i.useState(Bs()),[T,P]=i.useState(qs()),R=Vt(K=>K.currentProvider)==="copilot",B=_s(K=>K.activeTabKey),G=_s(K=>K.setActiveTabKey),h=na(K=>K.isAdvanced),y=l.paddingSM,D=(K,L)=>({key:K,label:t.jsx(Ss,{type:"secondary",style:{fontSize:11,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em",cursor:"default",userSelect:"none"},children:L}),disabled:!0,children:null}),S=(K,L)=>t.jsx("span",{"data-testid":`settings-tab-${K}`,children:L}),O=()=>{localStorage.clear(),d.success(r("settings.notifications.localStorageCleared"))},X=async()=>{p(!0);try{await m(),await Te.resetSetupStatus(),await Te.resetBambooConfig(),localStorage.clear(),d.success(r("settings.notifications.resetSuccessReloading")),setTimeout(()=>{window.location.reload()},1500)}catch(K){console.error("Failed to reset application:",K),d.error(K instanceof Error?K.message:r("settings.notifications.resetFailed")),p(!1)}},A=()=>{oa(f),d.success(r("settings.notifications.promptEnhancementSaved"))},U=K=>{u(K),ca(K)},$=K=>{j(K),la(K)},oe=K=>{E(K),ia(K)},de=K=>{P(K),da(K),window.dispatchEvent(new Event("lotus-vdi-safe-mode-change")),d.success(K?r("settings.appTab.vdiSafeModeEnabled","Graphics compatibility mode enabled"):r("settings.appTab.vdiSafeModeDisabled","Graphics compatibility mode disabled"))};return i.useEffect(()=>{w(aa()),u($s()),j(Vs()),E(Bs()),P(qs())},[]),t.jsxs(V,{vertical:!0,role:"region","aria-label":r("settings.page.title"),style:{height:"100vh",overflow:"hidden",background:l.colorBgContainer},children:[b,t.jsxs(V,{align:"center",justify:"space-between",style:{padding:l.padding,paddingTop:l.padding+y,borderBottom:`1px solid ${l.colorBorderSecondary}`},children:[t.jsxs(V,{align:"center",gap:l.marginSM,children:[t.jsx(z,{icon:t.jsx(wa,{}),onClick:o,"aria-label":r("settings.page.back"),children:r("settings.page.back")}),t.jsx(Ss,{strong:!0,"data-testid":"settings-page-title",children:r("settings.page.title")})]}),t.jsxs(Ss,{type:"secondary","data-testid":"settings-page-version",children:[r("settings.appTab.runningVersion","Running version"),": v",En]})]}),t.jsx(ka.Content,{style:{flex:1,minHeight:0,overflow:"auto",padding:l.padding},children:t.jsx(rs,{tabPosition:"left",activeKey:B,onChange:K=>G(K),items:[D("group-ai",r("settings.page.groups.ai")),{key:"provider",label:S("provider",r("settings.page.tabs.provider")),children:t.jsx(Qo,{})},{key:"model-limits",label:S("model-limits",r("settings.page.tabs.modelLimits")),children:t.jsx(ui,{})},{key:"prompts",label:S("prompts",r("settings.page.tabs.prompts")),children:t.jsx(Ja,{promptEnhancement:f,onPromptEnhancementChange:w,mermaidEnhancementEnabled:v,taskEnhancementEnabled:C,showCopilotConclusionWithOptionsEnhancement:R,copilotConclusionWithOptionsEnhancementEnabled:x,onMermaidToggle:U,onTaskToggle:$,onCopilotConclusionWithOptionsToggle:oe,onSaveEnhancement:A})},D("group-tools",r("settings.page.groups.toolsAndExtensions")),{key:"skills",label:S("skills",r("settings.page.tabs.skills")),children:t.jsx(si,{})},{key:"mcp",label:S("mcp",r("settings.page.tabs.mcp")),children:t.jsx(Or,{})},{key:"workflows",label:S("workflows",r("settings.page.tabs.workflows")),children:t.jsx(ir,{})},{key:"hooks",label:S("hooks",r("settings.page.tabs.hooks")),children:t.jsx(Po,{})},D("group-security",r("settings.page.groups.securityAndPrivacy")),{key:"masking",label:S("masking",r("settings.page.tabs.masking")),children:t.jsx(er,{})},{key:"env-vars",label:S("env-vars",r("settings.page.tabs.envVars")),children:t.jsx(nr,{})},D("group-monitoring",r("settings.page.groups.monitoring")),{key:"metrics",label:S("metrics",r("settings.page.tabs.metrics")),children:t.jsx(Co,{})},{key:"sessions",label:S("sessions",r("settings.page.tabs.sessions")),children:t.jsx(Ho,{})},D("group-system",r("settings.page.groups.system")),{key:"config",label:S("config",r("settings.page.tabs.config")),children:t.jsx(qa,{msgApi:d,locale:n,onLocaleChange:a})},{key:"schedules",label:S("schedules",r("settings.page.tabs.schedules")),children:t.jsx(Uo,{})},{key:"notifications",label:S("notifications",r("settings.page.tabs.notifications","Notifications")),children:t.jsx(Wo,{})},{key:"app",label:S("app",r("settings.page.tabs.app")),children:t.jsx(Ya,{themeMode:e,onThemeModeChange:s,vdiSafeMode:T,onVdiSafeModeToggle:de,onClearLocalStorage:O,onResetApp:X,isResetting:c,darkModeKey:mi})}].filter(K=>!(!h&&K.key&&ra.has(K.key)||!h&&(K.key==="group-security"||K.key==="group-monitoring")))})})]})};export{Si as SystemSettingsPage};