@bigduu/lotus 2026.5.18 → 2026.5.29

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 (113) hide show
  1. package/dist/assets/App-CSoVc5kq.js +245 -0
  2. package/dist/assets/{FeatureGuide-BlFyQEho.js → FeatureGuide-BEvoRR9h.js} +1 -1
  3. package/dist/assets/{MetricsService-BLd6-0qb.js → MetricsService-C3SA5O-z.js} +1 -1
  4. package/dist/assets/SubAgentsPanel-DankG8co.js +1 -0
  5. package/dist/assets/architectureDiagram-3BPJPVTR-BxRN2904.js +36 -0
  6. package/dist/assets/blockDiagram-GPEHLZMM-BUdOFKXS.js +132 -0
  7. package/dist/assets/{c4Diagram-AHTNJAMY-CBv5o-M1.js → c4Diagram-AAUBKEIU-R7VM_jb2.js} +1 -1
  8. package/dist/assets/{chunk-EDXVE4YY-KspsFgAM.js → chunk-2J33WTMH-C1T3QgQd.js} +1 -1
  9. package/dist/assets/{chunk-4BX2VUAB-CxLevY_l.js → chunk-4BX2VUAB-25Fo2TVO.js} +1 -1
  10. package/dist/assets/{chunk-55IACEB6-CyMcswjM.js → chunk-55IACEB6-BGyfC2jK.js} +1 -1
  11. package/dist/assets/chunk-727SXJPM-RKlR8ckj.js +206 -0
  12. package/dist/assets/chunk-AQP2D5EJ-C55Msx4c.js +231 -0
  13. package/dist/assets/{chunk-FMBD7UC4-BH440Lco.js → chunk-FMBD7UC4-h0twIch2.js} +1 -1
  14. package/dist/assets/{chunk-YZCP3GAM-D1Ua-1JA.js → chunk-ND2GUHAM-DyslQZ1W.js} +1 -1
  15. package/dist/assets/{chunk-QZHKN3VN-CYjk1VsY.js → chunk-QZHKN3VN-Dqthq7BH.js} +1 -1
  16. package/dist/assets/classDiagram-4FO5ZUOK-CnyHN3Oj.js +1 -0
  17. package/dist/assets/classDiagram-v2-Q7XG4LA2-CnyHN3Oj.js +1 -0
  18. package/dist/assets/{cose-bilkent-S5V4N54A-DBcT_Wx0.js → cose-bilkent-S5V4N54A-CkpcGEHo.js} +1 -1
  19. package/dist/assets/dagre-BM42HDAG-C3J21rxW.js +4 -0
  20. package/dist/assets/diagram-2AECGRRQ-C61YsAB8.js +43 -0
  21. package/dist/assets/diagram-5GNKFQAL-Caw10HFd.js +10 -0
  22. package/dist/assets/diagram-KO2AKTUF-CYt9RoUh.js +3 -0
  23. package/dist/assets/diagram-LMA3HP47-B5C2a2_L.js +24 -0
  24. package/dist/assets/diagram-OG6HWLK6-fEaxrU7x.js +24 -0
  25. package/dist/assets/en-US-DCV88PnO.js +3 -0
  26. package/dist/assets/{erDiagram-SMLLAGMA-5BQBJx-k.js → erDiagram-TEJ5UH35-GSKZF-im.js} +1 -1
  27. package/dist/assets/{flowDiagram-DWJPFMVM-CBv8eO1S.js → flowDiagram-I6XJVG4X-DuSuzMpf.js} +1 -1
  28. package/dist/assets/{ganttDiagram-T4ZO3ILL-CkWwjmoY.js → ganttDiagram-6RSMTGT7-Cu_jEY-M.js} +4 -4
  29. package/dist/assets/gitGraphDiagram-PVQCEYII-zECKggi3.js +106 -0
  30. package/dist/assets/graph-BlwPajkw.js +1 -0
  31. package/dist/assets/{index-DNsNCcgt.css → index-3qkG_le_.css} +1 -1
  32. package/dist/assets/index-4NqkovnM.js +1 -0
  33. package/dist/assets/{index-0lLJoNTX.js → index-6wyG_o5U.js} +2 -2
  34. package/dist/assets/index-BC8EjiMM.js +1 -0
  35. package/dist/assets/index-BZvX5d4s.js +1 -0
  36. package/dist/assets/{index-Bcpx4-c6.js → index-BdFrXiGe.js} +1 -1
  37. package/dist/assets/index-BfAjm2cg.js +1 -0
  38. package/dist/assets/index-CJdw34gN.js +1 -0
  39. package/dist/assets/index-CQnpSDCR.js +22 -0
  40. package/dist/assets/{index-B-6erFBV.js → index-Cej2Q9Bg.js} +1 -1
  41. package/dist/assets/index-CrnJlXzG.js +1 -0
  42. package/dist/assets/index-Czl6lcNT.js +1 -0
  43. package/dist/assets/index-DMAgXK8O.js +1 -0
  44. package/dist/assets/{index-Dhul7_lf.js → index-hdos2Xoy.js} +1 -1
  45. package/dist/assets/{index.es-usLOUMSp.js → index.es-DXC3ul5Q.js} +1 -1
  46. package/dist/assets/infoDiagram-5YYISTIA-ajMB2Qxa.js +2 -0
  47. package/dist/assets/{ishikawaDiagram-UXIWVN3A-zTI5fHSR.js → ishikawaDiagram-YF4QCWOH-DQEp0c9W.js} +1 -1
  48. package/dist/assets/{journeyDiagram-VCZTEJTY-DINdIE0t.js → journeyDiagram-JHISSGLW-D7FItFb_.js} +1 -1
  49. package/dist/assets/{kanban-definition-6JOO6SKY-BWZUu9_H.js → kanban-definition-UN3LZRKU-CgKt-G01.js} +4 -4
  50. package/dist/assets/layout-Boy8vhSP.js +1 -0
  51. package/dist/assets/{main-CEmqYfJe.js → main-DfVgHWQe.js} +3 -3
  52. package/dist/assets/mindmap-definition-RKZ34NQL-CuKXTTe2.js +96 -0
  53. package/dist/assets/{pieDiagram-DEJITSTG-wmUFaxVG.js → pieDiagram-4H26LBE5-JkCQLkjB.js} +3 -3
  54. package/dist/assets/quadrantDiagram-W4KKPZXB-C3dmbPVz.js +7 -0
  55. package/dist/assets/{requirementDiagram-MS252O5E-4eb0TnXV.js → requirementDiagram-4Y6WPE33-t3HhKU2z.js} +1 -1
  56. package/dist/assets/sankeyDiagram-5OEKKPKP-D8h7Gi4_.js +40 -0
  57. package/dist/assets/sequenceDiagram-3UESZ5HK-BYJgkHcz.js +162 -0
  58. package/dist/assets/stateDiagram-AJRCARHV-CSKaC8Rl.js +1 -0
  59. package/dist/assets/stateDiagram-v2-BHNVJYJU-BbOS1eq2.js +1 -0
  60. package/dist/assets/{timeline-definition-GMOUNBTQ-CMjl6c48.js → timeline-definition-PNZ67QCA-DLdfICX3.js} +1 -1
  61. package/dist/assets/{vendor-antd-C8lKwvI6.js → vendor-antd-rbjGKamc.js} +84 -84
  62. package/dist/assets/{vendor-charts-bhMup2Pu.js → vendor-charts-DtVw-oR1.js} +1 -1
  63. package/dist/assets/{vendor-i18n-BNURlJ23.js → vendor-i18n-Dm-c3D_C.js} +3 -3
  64. package/dist/assets/{vendor-markdown-DZuK0SxV.js → vendor-markdown-D6K7N9C9.js} +1 -1
  65. package/dist/assets/vendor-mermaid-B4BbwE4a.js +308 -0
  66. package/dist/assets/{vendor-pdf-DB-djSmA.js → vendor-pdf-iqXtbvvh.js} +4 -4
  67. package/dist/assets/{vennDiagram-DHZGUBPP-CJuHv1C-.js → vennDiagram-CIIHVFJN-I4nowEuq.js} +1 -1
  68. package/dist/assets/wardley-L42UT6IY-CvpejOzB.js +173 -0
  69. package/dist/assets/wardleyDiagram-YWT4CUSO-Bp8K5VuA.js +78 -0
  70. package/dist/assets/{xychartDiagram-5P7HB3ND-DnywOWSH.js → xychartDiagram-2RQKCTM6-BXOi8G-8.js} +1 -1
  71. package/dist/assets/zh-CN-CXhj-AJU.js +3 -0
  72. package/dist/index.html +5 -5
  73. package/package.json +3 -1
  74. package/dist/assets/App-BYqor0NW.js +0 -224
  75. package/dist/assets/SubAgentsPanel-DOzTGVWO.js +0 -1
  76. package/dist/assets/_baseUniq-Rkm-pzcz.js +0 -1
  77. package/dist/assets/architectureDiagram-Q4EWVU46-Dr89vzdU.js +0 -36
  78. package/dist/assets/blockDiagram-DXYQGD6D-TGOxvREa.js +0 -132
  79. package/dist/assets/chunk-4TB4RGXK-CZ85N7UX.js +0 -206
  80. package/dist/assets/chunk-OYMX7WX6-D5KuKqj-.js +0 -231
  81. package/dist/assets/classDiagram-6PBFFD2Q-D76pdmuK.js +0 -1
  82. package/dist/assets/classDiagram-v2-HSJHXN6E-D76pdmuK.js +0 -1
  83. package/dist/assets/clone-L6_2PEie.js +0 -1
  84. package/dist/assets/dagre-KV5264BT-DXZkFF5A.js +0 -4
  85. package/dist/assets/diagram-5BDNPKRD-BsQPI1ko.js +0 -10
  86. package/dist/assets/diagram-G4DWMVQ6-BO9UfQRh.js +0 -24
  87. package/dist/assets/diagram-MMDJMWI5-DkWy2py4.js +0 -43
  88. package/dist/assets/diagram-TYMM5635-DkuaI_3A.js +0 -24
  89. package/dist/assets/en-US-CnZu52UQ.js +0 -3
  90. package/dist/assets/gitGraphDiagram-UUTBAWPF-Cq7iSNVm.js +0 -106
  91. package/dist/assets/graph-DP71R45G.js +0 -1
  92. package/dist/assets/index-0wGcdXc1.js +0 -1
  93. package/dist/assets/index-4Mo8dj-Y.js +0 -1
  94. package/dist/assets/index-BBEDlZ5R.js +0 -1
  95. package/dist/assets/index-BJkKRJIj.js +0 -1
  96. package/dist/assets/index-CUlZM8lX.js +0 -1
  97. package/dist/assets/index-Ccxo4-w9.js +0 -21
  98. package/dist/assets/index-DbIwj11C.js +0 -1
  99. package/dist/assets/index-PfIEgx4k.js +0 -1
  100. package/dist/assets/index-ekP40-i6.js +0 -1
  101. package/dist/assets/infoDiagram-42DDH7IO-Cs719lD3.js +0 -2
  102. package/dist/assets/layout-QZEMSKRD.js +0 -1
  103. package/dist/assets/min-BB314uX0.js +0 -1
  104. package/dist/assets/mindmap-definition-QFDTVHPH-GgqTvonx.js +0 -96
  105. package/dist/assets/quadrantDiagram-34T5L4WZ-Bt7Nxjyo.js +0 -7
  106. package/dist/assets/sankeyDiagram-XADWPNL6-H6jXqw4X.js +0 -10
  107. package/dist/assets/sequenceDiagram-FGHM5R23-DgqfEZPw.js +0 -157
  108. package/dist/assets/stateDiagram-FHFEXIEX-CZrwRbTi.js +0 -1
  109. package/dist/assets/stateDiagram-v2-QKLJ7IA2-CwhUMrAy.js +0 -1
  110. package/dist/assets/vendor-mermaid-C1Gk9PtT.js +0 -309
  111. package/dist/assets/wardley-RL74JXVD-3f0MBifK.js +0 -162
  112. package/dist/assets/wardleyDiagram-NUSXRM2D-DsfJX8FP.js +0 -20
  113. package/dist/assets/zh-CN-NcKxgANL.js +0 -3
@@ -0,0 +1,22 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-Czl6lcNT.js","./vendor-markdown-D6K7N9C9.js","./vendor-i18n-Dm-c3D_C.js","./vendor-antd-rbjGKamc.js","./App-CSoVc5kq.js","./vendor-mermaid-B4BbwE4a.js","./main-DfVgHWQe.js","./main-B6snAd4S.css","./App-DNZiQHSs.css"])))=>i.map(i=>d[i]);
2
+ var la=Object.defineProperty;var ca=(e,s,n)=>s in e?la(e,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[s]=n;var an=(e,s,n)=>ca(e,typeof s!="symbol"?s+"":s,n);import{j as t}from"./vendor-markdown-D6K7N9C9.js";import{a as o,u as se,R as rn,i as ne}from"./vendor-i18n-Dm-c3D_C.js";import{D as da,u as qe,b as ua,N as ga,s as ma,O as Ys,k as Qe,w as lt,P as pa,Q as ht,R as Ee,S as ha,T as fa,U as ya,V as xa,W as Jn,X as rt,Y as Te,B as on,a as tt,Z as Xn,z as Zs,d as ba,c as Ks,o as va,_ as ln,$ as Ta,a0 as ja,a1 as ft,a2 as fs,a3 as Sa,a4 as _a,a5 as cn,a6 as dn,a7 as un,a8 as gn,f as ka,a9 as wa,A as Ca,aa as Ma,ab as Ea,ac as Da,ad as Pa,ae as Ia}from"./App-CSoVc5kq.js";import{G as R,j as F,A as Ve,l as ce,a3 as B,N as L,t as fe,Y as v,W as Qt,aD as xs,aE as Y,aF as ge,z as et,aG as Ge,aH as oe,q as Se,aI as Be,aJ as be,aK as Fa,aB as Re,F as H,aL as Ts,aM as Aa,a0 as es,a1 as ns,ak as Ra,aN as za,X as Ft,aO as js,$ as Ss,Z as It,aP as mn,o as le,aQ as dt,a2 as ct,ar as At,V as Rt,ag as Dt,aR as La,aj as Oa,aS as pn,aT as Ae,Q as Ue,aq as Yn,aU as Na,aV as ut,aW as _e,B as Va,aX as hn,aY as $a,aZ as Ba,p as Ws,I as qa,a_ as Ua,a$ as Ha,b0 as Zn,b1 as yt,b2 as fn,b3 as Ka,ab as Wa,aw as Ga,b4 as Ja}from"./vendor-antd-rbjGKamc.js";import{_ as Gs}from"./vendor-mermaid-B4BbwE4a.js";import{r as Xa}from"./onboardingStorage-BVcEpmTy.js";import"./main-DfVgHWQe.js";import{m as Zt}from"./MetricsService-C3SA5O-z.js";import{R as zt,B as Qs,C as as,X as rs,Y as is,T as Lt,L as en,a as bs,b as Qn,c as Pt,P as Ya,d as Za,e as Qa}from"./vendor-charts-DtVw-oR1.js";function er(e){return e instanceof da}function tr(){const{chats:e,currentSessionId:s,currentChat:n,addMessage:a,selectSession:r,deleteSession:i,deleteSessions:l,deleteMessage:p,updateSession:c,persistSessionTitle:d,pinSession:u,unpinSession:j,loadChats:f}=qe(ua(b=>({chats:b.chats,currentSessionId:b.currentSessionId,currentChat:ga(b),addMessage:b.addMessage,selectSession:b.selectSession,deleteSession:b.deleteSession,deleteSessions:b.deleteSessions,deleteMessage:b.deleteMessage,updateSession:b.updateSession,persistSessionTitle:b.persistSessionTitle,pinSession:b.pinSession,unpinSession:b.unpinSession,loadChats:b.loadChats}))),S=qe(ma(s)),w=o.useMemo(()=>(n==null?void 0:n.messages)||[],[n]),g=o.useMemo(()=>e.filter(b=>b.pinned),[e]),M=o.useMemo(()=>e.filter(b=>!b.pinned),[e]),_=e.length;return{chats:e,currentSessionId:s,currentChat:n,isProcessing:S,baseMessages:w,pinnedChats:g,unpinnedChats:M,chatCount:_,addMessage:a,deleteMessage:p,selectSession:r,deleteSession:i,deleteSessions:l,pinSession:u,unpinSession:j,updateSession:c,persistSessionTitle:d,loadChats:f}}function sr(e){const s=qe(f=>f.addChat),n=qe(f=>f.lastSelectedPromptId),a=qe(f=>f.systemPrompts),r=Ys.getInstance(),i=o.useCallback(async(f,S)=>{var _,b;const w=a.find(D=>D.id===n),g=(w==null?void 0:w.id)||(a.length>0?((_=a.find(D=>D.id==="general_assistant"))==null?void 0:_.id)||a[0].id:""),M={title:f||"New Session",createdAt:Date.now(),messages:[],config:{systemPromptId:g,baseSystemPrompt:(w==null?void 0:w.content)||(a.length>0?((b=a.find(D=>D.id==="general_assistant"))==null?void 0:b.content)||a[0].content:""),lastUsedEnhancedPrompt:null,...Qe.getState().isProviderModelRefEnabled()?{model_ref:Qe.getState().selectedModelRef}:{}},...S};await s(M)},[s,n,a]),l=o.useCallback(async f=>{lt("[ChatOps]","[useChatOperations] createChatWithSystemPrompt started with prompt:",f);const S={title:`New Session - ${f.name}`,createdAt:Date.now(),messages:[],config:{systemPromptId:f.id,baseSystemPrompt:f.content,lastUsedEnhancedPrompt:null}};lt("[ChatOps]","[useChatOperations] Calling addChat with newChatData.config:",S.config),await s(S)},[s]),p=o.useCallback(f=>{const S=e.chats.find(w=>w.id===f);S&&(S.pinned?e.unpinSession(f):e.pinSession(f))},[e]),c=o.useCallback((f,S)=>{e.updateSession(f,{title:S})},[e]),d=o.useCallback(async()=>{await r.cleanupSessions("empty",!0),await qe.getState().loadChats()},[r]),u=o.useCallback(async()=>{await r.cleanupSessions("all",!0),await qe.getState().loadChats()},[r]),j=o.useCallback(async()=>{await r.cleanupSessions("all",!1),await qe.getState().loadChats()},[r]);return{createNewChat:i,createChatWithSystemPrompt:l,toggleChatPin:p,updateChatTitle:c,deleteEmptyChats:d,deleteAllUnpinnedChats:u,deleteAllChats:j}}function nr(e,s){const n=o.useMemo(()=>e.baseMessages,[e.baseMessages]),a=o.useCallback(async()=>{var d;if(!e.currentSessionId||!e.currentChat)return;const r=[...e.baseMessages];if(r.length===0)return;const i=r[r.length-1];let l=r;if((i==null?void 0:i.role)==="assistant"){if(!(await e.deleteMessage(e.currentSessionId,i.id)).success)return;l=r.slice(0,-1)}const p=[...l].reverse().find(u=>u.role==="user");if(!p)return;const c="content"in p?p.content:p.displayText;typeof c=="string"&&await((d=s==null?void 0:s.onRetry)==null?void 0:d.call(s,c))},[e,s]);return{currentMessages:n,retryLastMessage:a}}const ar=()=>{const e=tr(),s=sr(e),n=pa({sessionId:e.currentSessionId,addMessage:e.addMessage,updateSession:e.updateSession}),a=nr(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:us}=ce,{useToken:rr}=fe,ir=({httpProxy:e,httpsProxy:s,onHttpProxyChange:n,onHttpsProxyChange:a,onReload:r,onSave:i,isLoading:l})=>{const{t:p}=se(),{token:c}=rr(),d=ht(k=>k.proxyAuthStatus),u=ht(k=>k.isLoadingProxyAuthStatus),j=ht(k=>k.loadProxyAuthStatus),f=ht(k=>k.applyProxyAuth),S=ht(k=>k.clearProxyAuth),[w,g]=o.useState({username:"",password:""}),[M,_]=o.useState(!1);o.useEffect(()=>{j()},[j]);const b=async()=>{const k=w.username.trim();if(k){_(!0);try{await f({username:k,password:w.password}),g({username:"",password:""})}catch(A){console.error("Failed to apply proxy auth:",A)}finally{_(!1)}}},D=async()=>{_(!0);try{await S()}catch(k){console.error("Failed to clear proxy auth:",k)}finally{_(!1)}};return t.jsx(R,{size:"small",title:t.jsx(us,{strong:!0,children:p("settings.networkCard.title")}),className:"lotus-settings-card",children:t.jsxs(F,{direction:"vertical",size:c.marginSM,style:{width:"100%"},children:[t.jsx(Ve,{message:p("settings.networkCard.guideTip"),type:"info",showIcon:!0}),t.jsxs(F,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[t.jsx(us,{type:"secondary",children:p("settings.networkCard.httpProxy")}),t.jsx(B,{"data-testid":"proxy-url",style:{width:"100%"},value:e,onChange:k=>n(k.target.value),placeholder:p("settings.networkCard.proxyPlaceholder"),disabled:l})]}),t.jsxs(F,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[t.jsx(us,{type:"secondary",children:p("settings.networkCard.httpsProxy")}),t.jsx(B,{style:{width:"100%"},value:s,onChange:k=>a(k.target.value),placeholder:p("settings.networkCard.proxyPlaceholder"),disabled:l})]}),t.jsx(R,{size:"small",title:p("settings.networkCard.proxyAuthTitle"),className:"lotus-settings-card",style:{marginTop:c.marginSM},children:d!=null&&d.configured?t.jsxs(F,{direction:"vertical",style:{width:"100%"},children:[t.jsx(Ve,{type:"success",message:p("settings.networkCard.proxyConfiguredForUser",{username:d.username??""}),showIcon:!0}),t.jsx(L,{onClick:D,loading:M||u,danger:!0,children:p("settings.networkCard.clearCredentials")})]}):t.jsxs(F,{direction:"vertical",size:c.marginXS,style:{width:"100%"},children:[t.jsx(B,{placeholder:p("settings.networkCard.username"),value:w.username,onChange:k=>g(A=>({...A,username:k.target.value}))}),t.jsx(B.Password,{placeholder:p("settings.networkCard.password"),value:w.password,onChange:k=>g(A=>({...A,password:k.target.value}))}),t.jsx(L,{type:"primary",onClick:b,loading:M||u,disabled:!w.username.trim(),children:p("settings.networkCard.apply")})]})}),t.jsx(us,{type:"secondary",style:{fontSize:c.fontSizeSM},children:p("settings.networkCard.credentialsStorageNote")}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:c.marginSM},children:[t.jsx(L,{onClick:()=>Promise.resolve(r()).finally(()=>j({force:!0})),disabled:l,children:p("settings.networkCard.reload")}),t.jsx(L,{"data-testid":"save-proxy-settings",type:"primary",onClick:()=>Promise.resolve(i()).finally(()=>j({force:!0})),disabled:l,children:p("settings.networkCard.save")})]})]})})},{Text:or}=ce,{useToken:lr}=fe,cr=({msgApi:e})=>{const{t:s}=se(),{token:n}=lr(),[a]=v.useForm(),[r,i]=o.useState(!1),[l,p]=o.useState(!1),[c,d]=o.useState(!1),[u,j]=o.useState(!1),[f,S]=o.useState(null),w=c&&!u,g=o.useMemo(()=>s(c?u?"settings.configTab.accessPassword.helperLocalBypass":"settings.configTab.accessPassword.helperRemote":"settings.configTab.accessPassword.helperNotEnabled"),[u,c,s]),M=o.useCallback(async()=>{i(!0),S(null);try{const b=await Ee.getAccessStatus();d(b.password_enabled),j(b.local_bypass)}catch(b){const D=b instanceof Error?b.message:s("settings.configTab.accessPassword.loadStatusFailed","Failed to load access status");S(D)}finally{i(!1)}},[s]);o.useEffect(()=>{M()},[M]);const _=async()=>{var b;try{const D=await a.validateFields();p(!0),await Ee.updateAccessPassword({current_password:((b=D.currentPassword)==null?void 0:b.trim())||void 0,new_password:D.newPassword.trim()}),e.success(s(c?"settings.configTab.accessPassword.updated":"settings.configTab.accessPassword.enabled")),a.resetFields(),await M()}catch(D){if(D.errorFields)return;const k=D instanceof Error?D.message:s("settings.configTab.accessPassword.updateFailed","Failed to update access password");e.error(k)}finally{p(!1)}};return t.jsx(R,{size:"small",className:"lotus-settings-card",title:t.jsx(or,{strong:!0,children:s("settings.configTab.accessPasswordTitle")}),children:t.jsxs(F,{direction:"vertical",size:n.marginMD,style:{width:"100%"},children:[t.jsx(Ve,{type:c?"info":"warning",showIcon:!0,message:s(c?"settings.configTab.accessPassword.statusEnabled":"settings.configTab.accessPassword.statusDisabled"),description:g}),f?t.jsx(Ve,{type:"error",showIcon:!0,message:f}):null,t.jsxs(v,{form:a,layout:"vertical",disabled:r||l,children:[w?t.jsx(v.Item,{label:s("settings.configTab.accessPassword.currentPasswordLabel"),name:"currentPassword",rules:[{required:!0,message:s("settings.configTab.accessPassword.validation.currentPasswordRequired")}],children:t.jsx(B.Password,{autoComplete:"current-password"})}):null,t.jsx(v.Item,{label:s(c?"settings.configTab.accessPassword.newPasswordLabel":"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")}],children:t.jsx(B.Password,{autoComplete:"new-password"})}),t.jsx(v.Item,{label:s("settings.configTab.accessPassword.confirmPasswordLabel"),name:"confirmPassword",dependencies:["newPassword"],rules:[{required:!0,message:s("settings.configTab.accessPassword.validation.confirmPasswordRequired")},({getFieldValue:b})=>({validator(D,k){return!k||b("newPassword")===k?Promise.resolve():Promise.reject(new Error(s("settings.configTab.accessPassword.validation.passwordMismatch")))}})],children:t.jsx(B.Password,{autoComplete:"new-password"})}),t.jsx(L,{type:"primary",loading:l,onClick:()=>void _(),children:s(c?"settings.configTab.accessPassword.updateAction":"settings.configTab.accessPassword.enableAction")})]})]})})},{Text:Ye}=ce,{useToken:dr}=fe,yn="http://127.0.0.1:9562/v1",Xt=e=>[...new Set(e.map(s=>s.trim()).filter(s=>s.length>0))].sort(),ur=e=>{var n;const s=(n=e.tools)==null?void 0:n.disabled;return Array.isArray(s)?Xt(s.filter(a=>typeof a=="string")):[]},gr=({msgApi:e,locale:s,onLocaleChange:n})=>{const{t:a}=se(),{token:r}=dr(),[i,l]=o.useState({http_proxy:"",https_proxy:"",memory:{auto_dream_enabled:!1}}),[p,c]=o.useState(yn),[d,u]=o.useState([]),[j,f]=o.useState([]),[S,w]=o.useState([]),[g,M]=o.useState(!1),[_,b]=o.useState(!1),D=o.useCallback(async()=>{var O;M(!0);try{const[K,Q]=await Promise.all([Ee.getBambooConfig(),Ee.getBambooTools()]);l({http_proxy:K.http_proxy||"",https_proxy:K.https_proxy||"",memory:{auto_dream_enabled:((O=K.memory)==null?void 0:O.auto_dream_enabled)??!1}});const W=ur(K);f(W),w(W),u(Xt(Q.tools||[]))}catch(K){console.error("Failed to load config:",K),e.error(a("settings.configTab.loadConfigFailed"))}finally{M(!1)}},[e,a]);o.useEffect(()=>{D()},[D]);const k=O=>{l(K=>({...K,http_proxy:O}))},A=O=>{l(K=>({...K,https_proxy:O}))},te=O=>{l(K=>({...K,memory:{...K.memory,auto_dream_enabled:O}}))},z=async()=>{var O,K;M(!0);try{const Q=await Ee.validateBambooConfigPatch(i);if(!Q.valid){const pe=((K=(O=Q.errors)==null?void 0:O.proxy)==null?void 0:K[0])??Object.values(Q.errors||{}).flat().filter(Boolean)[0];e.error((pe==null?void 0:pe.message)||a("settings.configTab.invalidConfig"));return}await Ee.setBambooConfig(i),e.success(a("settings.configTab.saveConfigSuccess"))}catch(Q){console.error("Failed to save config:",Q);const W=Q instanceof Error&&Q.message.trim()?Q.message:a("settings.configTab.saveConfigFailed");e.error(W)}finally{M(!1)}},U=async()=>{e.success(a("settings.configTab.backendSaved"))},Z=()=>{c(yn),e.success(a("settings.configTab.backendResetDefault"))},h=(O,K)=>{f(Q=>{const W=new Set(Q);return K?W.delete(O):W.add(O),Xt([...W])})},y=async()=>{b(!0);try{const O=await Ee.getBambooTools();u(Xt(O.tools||[])),e.success(a("settings.configTab.toolsReloadSuccess"))}catch(O){console.error("Failed to reload tools:",O),e.error(a("settings.configTab.toolsLoadFailed"))}finally{b(!1)}},P=async()=>{b(!0);try{const O=Xt(j);await Ee.setBambooConfig({tools:{disabled:O}}),f(O),w(O),e.success(a("settings.configTab.toolsSaveSuccess"))}catch(O){console.error("Failed to save tool settings:",O),e.error(a("settings.configTab.toolsSaveFailed"))}finally{b(!1)}},E=JSON.stringify(j)!==JSON.stringify(S),I=new Set(j);return t.jsx(Qt,{spinning:g,tip:a("settings.common.loading"),children:t.jsx(xs,{items:[{key:"general",label:a("settings.configTab.tabs.general"),children:t.jsxs(F,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[t.jsx(ir,{httpProxy:i.http_proxy,httpsProxy:i.https_proxy,onHttpProxyChange:k,onHttpsProxyChange:A,onReload:D,onSave:z,isLoading:g}),t.jsx(R,{size:"small",className:"lotus-settings-card",title:t.jsx(Ye,{strong:!0,children:a("settings.configTab.language")}),children:t.jsx(Y,{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:O=>n(O)})}),t.jsx(R,{size:"small",className:"lotus-settings-card",title:t.jsx(Ye,{strong:!0,children:a("settings.configTab.memoryTitle")}),children:t.jsxs(F,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[t.jsx(Ye,{type:"secondary",children:a("settings.configTab.memoryDescription")}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:r.marginMD,flexWrap:"wrap"},children:[t.jsxs("div",{children:[t.jsx(Ye,{strong:!0,children:a("settings.configTab.autoDreamEnabled")}),t.jsx("div",{children:t.jsx(Ye,{type:"secondary",style:{fontSize:r.fontSizeSM},children:a("settings.configTab.autoDreamEnabledHint")})})]}),t.jsx(ge,{"data-testid":"auto-dream-toggle",checked:i.memory.auto_dream_enabled,onChange:te})]}),t.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:t.jsx(L,{"data-testid":"save-memory-settings",type:"primary",onClick:z,loading:g,children:a("settings.configTab.save")})})]})}),t.jsx(R,{size:"small",title:t.jsx(Ye,{strong:!0,children:a("settings.configTab.backendApiBaseUrlTitle")}),children:t.jsxs(F,{direction:"vertical",size:r.marginSM,style:{width:"100%"},children:[t.jsx(F,{direction:"vertical",size:r.marginXXS,style:{width:"100%"},children:t.jsx(B,{style:{width:"100%"},value:p,onChange:O=>c(O.target.value),placeholder:a("settings.configTab.backendApiPlaceholder")})}),t.jsx(Ye,{type:"secondary",style:{fontSize:r.fontSizeSM},children:a("settings.configTab.backendApiHint")}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:r.marginSM},children:[t.jsx(L,{"data-testid":"reset-to-defaults",onClick:Z,children:a("settings.configTab.resetToDefault")}),t.jsx(L,{"data-testid":"save-api-settings",type:"primary",onClick:U,children:a("settings.configTab.save")})]})]})}),t.jsx(cr,{msgApi:e})]})},{key:"tools",label:a("settings.configTab.tabs.tools"),children:t.jsx(R,{size:"small",title:t.jsx(Ye,{strong:!0,children:a("settings.configTab.toolsTitle")}),children:t.jsxs(F,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[t.jsx(Ye,{type:"secondary",children:a("settings.configTab.toolsDescription")}),d.length===0?t.jsx(Ve,{type:"info",showIcon:!0,message:a("settings.configTab.toolsEmpty")}):t.jsx(et,{bordered:!0,dataSource:d,renderItem:O=>t.jsx(et.Item,{actions:[t.jsx(ge,{checked:!I.has(O),onChange:K=>h(O,K)},`${O}-switch`)],children:t.jsx(Ye,{code:!0,children:O})})}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:r.marginSM},children:[t.jsx(L,{onClick:y,loading:_,children:a("settings.configTab.reloadTools")}),t.jsx(L,{type:"primary",onClick:P,loading:_,disabled:!E,children:a("settings.configTab.save")})]})]})})}]})})},{Title:mr,Text:As}=ce,{useToken:pr}=fe,hr=()=>{const{t:e}=se(),{token:s}=pr(),n=ha(),a=fa(),r=ya(),[i]=v.useForm(),l=rn.useRef(n);rn.useEffect(()=>{l.current!==n&&(i.setFieldsValue(n),l.current=n)},[n,i]);const p=d=>{l.current={...l.current,...d},a(d)},c=()=>{r(),i.resetFields()};return t.jsxs("div",{style:{padding:"24px",maxWidth:"1200px",margin:"0 auto"},children:[t.jsx(mr,{level:3,style:{marginBottom:"8px"},children:e("settings.mermaidTab.title")}),t.jsx(As,{type:"secondary",style:{display:"block",marginBottom:"24px"},children:e("settings.mermaidTab.description")}),t.jsxs(v,{form:i,layout:"vertical",initialValues:n,onValuesChange:p,children:[t.jsxs(R,{title:e("settings.mermaidTab.themeCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:[t.jsx(Ge,{gutter:16,children:t.jsx(oe,{span:24,children:t.jsx(v.Item,{name:"theme",label:t.jsxs(F,{children:[e("settings.mermaidTab.themeLabel"),t.jsx(Se,{title:e("settings.mermaidTab.themeTooltip"),children:t.jsx(Be,{style:{color:s.colorTextSecondary}})})]}),children:t.jsxs(Y,{children:[t.jsx(Y.Option,{value:"default",children:e("settings.mermaidTab.themeOptions.default")}),t.jsx(Y.Option,{value:"neutral",children:e("settings.mermaidTab.themeOptions.neutral")}),t.jsx(Y.Option,{value:"dark",children:e("settings.mermaidTab.themeOptions.dark")}),t.jsx(Y.Option,{value:"forest",children:e("settings.mermaidTab.themeOptions.forest")}),t.jsx(Y.Option,{value:"base",children:e("settings.mermaidTab.themeOptions.base")})]})})})}),t.jsxs(As,{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(R,{title:e("settings.mermaidTab.globalCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:[t.jsxs(Ge,{gutter:16,children:[t.jsx(oe,{span:12,children:t.jsx(v.Item,{name:"fontSize",label:t.jsxs(F,{children:[e("settings.mermaidTab.fontSizeLabel"),t.jsx(Se,{title:e("settings.mermaidTab.fontSizeTooltip"),children:t.jsx(Be,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(be,{min:10,max:32,step:1,style:{width:"100%"},addonAfter:"px"})})}),t.jsx(oe,{span:12,children:t.jsx(v.Item,{name:"defaultScale",label:t.jsxs(F,{children:[e("settings.mermaidTab.defaultZoomLabel"),t.jsx(Se,{title:e("settings.mermaidTab.defaultZoomTooltip"),children:t.jsx(Be,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(be,{min:.1,max:3,step:.1,style:{width:"100%"}})})})]}),t.jsx(v.Item,{name:"useMaxWidth",label:t.jsxs(F,{children:[e("settings.mermaidTab.responsiveWidthLabel"),t.jsx(Se,{title:e("settings.mermaidTab.responsiveWidthTooltip"),children:t.jsx(Be,{style:{color:s.colorTextSecondary}})})]}),valuePropName:"checked",children:t.jsx(ge,{})})]}),t.jsx(R,{title:e("settings.mermaidTab.flowchartCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsxs(Ge,{gutter:16,children:[t.jsx(oe,{span:8,children:t.jsx(v.Item,{name:"flowchartNodeSpacing",label:t.jsxs(F,{children:[e("settings.mermaidTab.flowchartNodeSpacingLabel"),t.jsx(Se,{title:e("settings.mermaidTab.flowchartNodeSpacingTooltip"),children:t.jsx(Be,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(be,{min:20,max:200,step:10,style:{width:"100%"}})})}),t.jsx(oe,{span:8,children:t.jsx(v.Item,{name:"flowchartRankSpacing",label:t.jsxs(F,{children:[e("settings.mermaidTab.flowchartRankSpacingLabel"),t.jsx(Se,{title:e("settings.mermaidTab.flowchartRankSpacingTooltip"),children:t.jsx(Be,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(be,{min:20,max:200,step:10,style:{width:"100%"}})})}),t.jsx(oe,{span:8,children:t.jsx(v.Item,{name:"flowchartCurve",label:t.jsxs(F,{children:[e("settings.mermaidTab.flowchartCurveTypeLabel"),t.jsx(Se,{title:e("settings.mermaidTab.flowchartCurveTypeTooltip"),children:t.jsx(Be,{style:{color:s.colorTextSecondary}})})]}),children:t.jsxs(Y,{children:[t.jsx(Y.Option,{value:"basis",children:e("settings.mermaidTab.flowchartCurveOptions.basis")}),t.jsx(Y.Option,{value:"linear",children:e("settings.mermaidTab.flowchartCurveOptions.linear")}),t.jsx(Y.Option,{value:"cardinal",children:e("settings.mermaidTab.flowchartCurveOptions.cardinal")})]})})})]})}),t.jsx(R,{title:e("settings.mermaidTab.sequenceCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsxs(Ge,{gutter:16,children:[t.jsx(oe,{span:6,children:t.jsx(v.Item,{name:"sequenceActorMargin",label:t.jsxs(F,{children:[e("settings.mermaidTab.sequenceActorMarginLabel"),t.jsx(Se,{title:e("settings.mermaidTab.sequenceActorMarginTooltip"),children:t.jsx(Be,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(be,{min:20,max:200,step:10,style:{width:"100%"}})})}),t.jsx(oe,{span:6,children:t.jsx(v.Item,{name:"sequenceMessageMargin",label:t.jsxs(F,{children:[e("settings.mermaidTab.sequenceMessageMarginLabel"),t.jsx(Se,{title:e("settings.mermaidTab.sequenceMessageMarginTooltip"),children:t.jsx(Be,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(be,{min:10,max:100,step:5,style:{width:"100%"}})})}),t.jsx(oe,{span:6,children:t.jsx(v.Item,{name:"sequenceWidth",label:t.jsxs(F,{children:[e("settings.mermaidTab.sequenceActorWidthLabel"),t.jsx(Se,{title:e("settings.mermaidTab.sequenceActorWidthTooltip"),children:t.jsx(Be,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(be,{min:100,max:300,step:10,style:{width:"100%"}})})}),t.jsx(oe,{span:6,children:t.jsx(v.Item,{name:"sequenceHeight",label:t.jsxs(F,{children:[e("settings.mermaidTab.sequenceActorHeightLabel"),t.jsx(Se,{title:e("settings.mermaidTab.sequenceActorHeightTooltip"),children:t.jsx(Be,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(be,{min:40,max:150,step:5,style:{width:"100%"}})})})]})}),t.jsx(R,{title:e("settings.mermaidTab.ganttCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsxs(Ge,{gutter:16,children:[t.jsx(oe,{span:12,children:t.jsx(v.Item,{name:"ganttBarHeight",label:t.jsxs(F,{children:[e("settings.mermaidTab.ganttBarHeightLabel"),t.jsx(Se,{title:e("settings.mermaidTab.ganttBarHeightTooltip"),children:t.jsx(Be,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(be,{min:10,max:50,step:5,style:{width:"100%"},addonAfter:"px"})})}),t.jsx(oe,{span:12,children:t.jsx(v.Item,{name:"ganttTopPadding",label:t.jsxs(F,{children:[e("settings.mermaidTab.ganttTopPaddingLabel"),t.jsx(Se,{title:e("settings.mermaidTab.ganttTopPaddingTooltip"),children:t.jsx(Be,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(be,{min:20,max:100,step:10,style:{width:"100%"}})})})]})}),t.jsx(F,{children:t.jsx(L,{icon:t.jsx(Fa,{}),onClick:c,children:e("settings.mermaidTab.resetToDefaults")})}),t.jsx(Re,{}),t.jsx(R,{title:e("settings.mermaidTab.previewTitle"),styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsx(As,{type:"secondary",children:e("settings.mermaidTab.previewDescription")})})]})]})},fr=o.lazy(()=>Gs(()=>import("./index-Czl6lcNT.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8]),import.meta.url)),{Text:vt}=ce,{useToken:yr}=fe,xr=({promptEnhancement:e,onPromptEnhancementChange:s,mermaidEnhancementEnabled:n,taskEnhancementEnabled:a,showCopilotConclusionWithOptionsEnhancement:r,copilotConclusionWithOptionsEnhancementEnabled:i,onMermaidToggle:l,onTaskToggle:p,onCopilotConclusionWithOptionsToggle:c,onSaveEnhancement:d})=>{const{t:u}=se(),{token:j}=yr(),f=j.marginLG;return t.jsxs(H,{vertical:!0,gap:f,children:[t.jsx(R,{size:"small",className:"lotus-settings-card",children:t.jsx(o.Suspense,{fallback:t.jsx(Qt,{size:"small"}),children:t.jsx(fr,{})})}),t.jsx(R,{size:"small",className:"lotus-settings-card",children:t.jsxs(F,{direction:"vertical",size:j.marginXS,style:{width:"100%"},children:[t.jsx(vt,{strong:!0,children:u("settings.promptsTab.title")}),t.jsxs(H,{align:"center",gap:j.marginSM,children:[t.jsx(vt,{strong:!0,children:u("settings.promptsTab.mermaidEnhancement")}),t.jsx(ge,{checked:n,onChange:l})]}),t.jsxs(H,{align:"center",gap:j.marginSM,children:[t.jsx(vt,{strong:!0,children:u("settings.promptsTab.taskListRules")}),t.jsx(ge,{checked:a,onChange:p})]}),r&&t.jsxs(F,{direction:"vertical",size:j.marginXXS,style:{width:"100%"},children:[t.jsxs(H,{align:"center",gap:j.marginSM,children:[t.jsx(vt,{strong:!0,children:u("settings.promptsTab.copilotConclusionWithOptionsBeforeFinish")}),t.jsx(ge,{checked:i,onChange:c})]}),t.jsx(vt,{type:"secondary",style:{fontSize:j.fontSizeSM},children:u("settings.promptsTab.copilotConclusionWithOptionsBeforeFinishDescription",{defaultValue:xa()})})]}),t.jsx(B.TextArea,{rows:6,placeholder:u("settings.promptsTab.enhancementPlaceholder"),value:e,onChange:S=>s(S.target.value)}),t.jsx(H,{justify:"flex-end",children:t.jsx(L,{type:"primary",onClick:d,children:u("settings.promptsTab.saveEnhancement")})}),t.jsx(vt,{type:"secondary",style:{fontSize:j.fontSizeSM},children:u("settings.promptsTab.description")})]})}),n&&t.jsx(Ts,{size:"small",items:[{key:"mermaid",label:t.jsx(vt,{strong:!0,children:u("settings.mermaidTab.title")}),children:t.jsx(hr,{})}]})]})},{Text:mt}=ce,{useToken:br}=fe,vr=({themeMode:e,onThemeModeChange:s,vdiSafeMode:n,onVdiSafeModeToggle:a,onClearLocalStorage:r,onResetApp:i,isResetting:l,darkModeKey:p})=>{const{t:c}=se(),{token:d}=br();return t.jsx(R,{size:"small",className:"lotus-settings-card",children:t.jsxs(F,{direction:"vertical",size:d.marginSM,style:{width:"100%"},children:[t.jsxs(H,{align:"center",justify:"space-between",gap:d.marginSM,children:[t.jsx(mt,{strong:!0,children:c("settings.appTab.runningVersion","Running version")}),t.jsxs(mt,{code:!0,"data-testid":"settings-app-version",children:["v",Jn]})]}),t.jsx(mt,{type:"secondary",style:{fontSize:d.fontSizeSM},children:c("settings.appTab.runningVersionDesc","This is the currently running Lotus frontend version.")}),t.jsxs(H,{align:"center",gap:d.marginSM,children:[t.jsx(mt,{strong:!0,children:c("settings.appTab.darkMode")}),t.jsx(ge,{"data-testid":"dark-mode-toggle",checked:e==="dark",onChange:u=>{const j=u?"dark":"light";s(j),localStorage.setItem(p,j)}})]}),t.jsxs(H,{align:"center",gap:d.marginSM,children:[t.jsx(mt,{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(mt,{type:"secondary",style:{fontSize:d.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(L,{block:!0,icon:t.jsx(Aa,{}),onClick:()=>{Xa(),window.location.reload()},children:c("settings.appTab.resetStepReplayGuide")}),t.jsx(es,{title:c("settings.appTab.clearLocalStorageTitle"),description:c("settings.appTab.clearLocalStorageDescription"),onConfirm:r,okText:c("settings.appTab.confirmClear"),cancelText:c("settings.appTab.cancel"),placement:"top",children:t.jsx(L,{danger:!0,block:!0,icon:t.jsx(ns,{}),children:c("settings.appTab.clearLocalStorageButton")})}),t.jsx(Re,{style:{margin:`${d.marginSM}px 0`}}),t.jsxs(H,{align:"center",gap:d.marginSM,children:[t.jsx(Ra,{style:{color:d.colorError}}),t.jsx(mt,{strong:!0,style:{color:d.colorError},children:c("settings.appTab.dangerZone")})]}),t.jsx(mt,{type:"secondary",style:{fontSize:d.fontSizeSM},children:c("settings.appTab.dangerDescription")}),t.jsx(es,{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:i,okText:c("settings.appTab.resetConfirm"),cancelText:c("settings.appTab.cancel"),placement:"top",okButtonProps:{danger:!0},children:t.jsx(L,{"data-testid":"reset-to-defaults",danger:!0,block:!0,type:"primary",icon:t.jsx(za,{}),loading:l,children:c("settings.appTab.resetButton")})})]})})},{Text:Tt}=ce,{useToken:Tr}=fe,xn=[{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,}"}],jr=(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:ne.t("settings.keywordMaskingTab.invalidRegexPattern")}}},Sr=()=>{const{t:e}=se(),{message:s}=Ft.useApp(),{token:n}=Tr(),[a,r]=o.useState([]),[i,l]=o.useState(!1),[p,c]=o.useState(null),[d,u]=o.useState(""),[j,f]=o.useState("exact"),[S,w]=o.useState(!0),[g,M]=o.useState(),[_,b]=o.useState("My token is sk-123"),D=o.useCallback(async()=>{try{l(!0);const E=await rt.getInstance().getKeywordMaskingConfig();r(E.entries)}catch(P){s.error(e("settings.keywordMaskingTab.loadFailed")),console.error(P)}finally{l(!1)}},[e]);o.useEffect(()=>{D()},[D]);const k=async P=>{try{const E=rt.getInstance(),I=await E.validateKeywordEntries(P);if(!I.valid&&I.errors){const K=I.errors.map(Q=>`Entry ${Q.index+1}: ${Q.message}`).join("; ");return s.error(`${e("settings.keywordMaskingTab.validationFailedPrefix")}: ${K}`),!1}const O=await E.updateKeywordMaskingConfig(P);return r(O.entries),s.success(e("settings.keywordMaskingTab.saveSuccess")),!0}catch(E){return s.error(E instanceof Error?E.message:e("settings.keywordMaskingTab.saveFailed")),!1}},A=async()=>{const P={pattern:"",match_type:"exact",enabled:!0},E=[...a,P];r(E),c(E.length-1),u(""),f("exact"),w(!0),M(void 0)},te=P=>{const E=a[P];c(P),u(E.pattern),f(E.match_type),w(E.enabled),M(void 0)},z=async()=>{if(p===null)return;if(!d.trim()){s.error(e("settings.keywordMaskingTab.patternRequired"));return}const P=[...a];P[p]={pattern:d.trim(),match_type:j,enabled:S},await k(P)&&c(null)},U=()=>{var P;p!==null&&!((P=a[p])!=null&&P.pattern)&&r(a.filter((E,I)=>I!==p)),c(null)},Z=async P=>{const E=a.filter((I,O)=>O!==P);await k(E)},h=async(P,E)=>{const I=[...a];I[P]={...I[P],enabled:E},await k(I)},y=jr(_,d,j);return t.jsx(R,{className:"lotus-settings-card",title:e("settings.keywordMaskingTab.title"),extra:t.jsx(L,{"data-testid":"add-keyword",type:"primary",icon:t.jsx(It,{}),onClick:A,loading:i,children:e("settings.keywordMaskingTab.addKeyword")}),children:t.jsxs(F,{direction:"vertical",style:{width:"100%"},size:"large",children:[t.jsx(Tt,{type:"secondary",children:e("settings.keywordMaskingTab.description")}),t.jsx(et,{loading:i,dataSource:a,locale:{emptyText:e("settings.keywordMaskingTab.empty")},renderItem:(P,E)=>t.jsx(et.Item,{style:{backgroundColor:n.colorFillAlter,marginBottom:8,borderRadius:n.borderRadius,padding:12},actions:p===E?[t.jsx(L,{"data-testid":"save-keyword",type:"primary",icon:t.jsx(js,{}),onClick:z,"aria-label":e("settings.keywordMaskingTab.save")},"save"),t.jsx(L,{onClick:U,children:e("settings.keywordMaskingTab.cancel")},"cancel")]:[t.jsx(L,{icon:t.jsx(Ss,{}),onClick:()=>te(E),"aria-label":e("settings.keywordMaskingTab.edit")},"edit"),t.jsx(L,{"data-testid":`delete-keyword-${E}`,danger:!0,icon:t.jsx(ns,{}),onClick:()=>Z(E),"aria-label":e("settings.keywordMaskingTab.delete")},"delete")],children:t.jsx(H,{vertical:!0,style:{width:"100%"},gap:8,children:p===E?t.jsxs(t.Fragment,{children:[t.jsx(B,{"data-testid":"keyword-pattern-input",placeholder:e("settings.keywordMaskingTab.patternPlaceholder"),value:d,onChange:I=>u(I.target.value),autoFocus:!0}),t.jsxs(H,{gap:8,align:"center",wrap:"wrap",children:[t.jsx(Y,{"data-testid":"keyword-examples-select","aria-label":e("settings.keywordMaskingTab.examples"),placeholder:e("settings.keywordMaskingTab.examples"),value:g,onChange:I=>{M(I);const O=xn.find(K=>K.value===I);O&&(u(O.pattern),f(O.match_type))},options:xn.map(I=>({value:I.value,label:e(I.labelKey)})),style:{minWidth:220}}),t.jsx(Y,{value:j,onChange:f,options:[{value:"exact",label:e("settings.keywordMaskingTab.exactMatch")},{value:"regex",label:e("settings.keywordMaskingTab.regexPattern")}],style:{width:150}}),t.jsx(ge,{checked:S,onChange:w})]}),t.jsxs(H,{vertical:!0,gap:6,children:[t.jsx(Tt,{type:"secondary",children:e("settings.keywordMaskingTab.sampleText")}),t.jsx(B,{placeholder:e("settings.keywordMaskingTab.sampleTextPlaceholder"),value:_,onChange:I=>b(I.target.value)}),t.jsx(Tt,{type:"secondary",children:e("settings.keywordMaskingTab.maskedPreview")}),t.jsx(B,{readOnly:!0,value:y.masked,status:y.error?"error":void 0}),y.error&&t.jsx(Tt,{type:"danger",children:y.error})]})]}):t.jsxs(H,{justify:"space-between",align:"center",children:[t.jsxs(H,{vertical:!0,gap:4,children:[t.jsx(Tt,{strong:!0,children:P.pattern||e("settings.keywordMaskingTab.emptyPattern")}),t.jsxs(H,{gap:8,children:[t.jsx(Tt,{type:"secondary",style:{fontSize:12},children:P.match_type==="regex"?e("settings.keywordMaskingTab.regexPattern"):e("settings.keywordMaskingTab.exactMatch")}),!P.enabled&&t.jsx(Tt,{type:"warning",style:{fontSize:12},children:e("settings.keywordMaskingTab.disabled")})]})]}),t.jsx(ge,{checked:P.enabled,onChange:I=>h(E,I),size:"small"})]})})})})]})})},{Text:Ct,Paragraph:_r}=ce,kr=/^[A-Za-z_][A-Za-z0-9_]*$/,wr=()=>{const{t:e}=se(),{message:s}=Ft.useApp(),[n,a]=o.useState([]),[r,i]=o.useState(!1),[l,p]=o.useState(!1),[c,d]=o.useState(null),[u]=v.useForm(),j=o.useCallback(async()=>{i(!0);try{const b=await Te.getEnvVars();a(b.entries)}catch{s.error(e("settings.envVars.fetchError","Failed to load environment variables"))}finally{i(!1)}},[e]);o.useEffect(()=>{j()},[j]);const f=async b=>{var k;const D={name:b.name.trim(),value:b.value,secret:b.secret??!1,description:((k=b.description)==null?void 0:k.trim())||void 0};try{const A=await Te.upsertEnvVar(D);a(A.entries),s.success(c?e("settings.envVars.updated","Variable updated"):e("settings.envVars.created","Variable created")),M()}catch(A){s.error((A instanceof Error?A.message:void 0)||e("settings.envVars.saveError","Failed to save variable"))}},S=async b=>{try{const D=await Te.deleteEnvVar(b);a(D.entries),s.success(e("settings.envVars.deleted","Variable deleted"))}catch(D){s.error((D instanceof Error?D.message:void 0)||e("settings.envVars.deleteError","Failed to delete variable"))}},w=()=>{d(null),u.resetFields(),u.setFieldsValue({secret:!1}),p(!0)},g=b=>{d(b.name),u.setFieldsValue({name:b.name,value:"",secret:b.secret,description:b.description??""}),p(!0)},M=()=>{p(!1),d(null),u.resetFields()},_=[{title:e("settings.envVars.name","Name"),dataIndex:"name",key:"name",render:b=>t.jsx(Ct,{code:!0,children:b})},{title:e("settings.envVars.value","Value"),dataIndex:"value",key:"value",render:(b,D)=>D.secret?t.jsxs(Ct,{type:"secondary",children:[t.jsx(mn,{style:{marginRight:4}}),D.has_value?"••••••••":e("settings.envVars.notSet","(not set)")]}):t.jsx(Ct,{children:b||t.jsx(Ct,{type:"secondary",children:e("settings.envVars.empty","(empty)")})})},{title:e("settings.envVars.type","Type"),key:"secret",width:100,render:(b,D)=>D.secret?t.jsx(le,{color:"warning",icon:t.jsx(mn,{}),children:e("settings.envVars.secret","Secret")}):t.jsx(le,{color:"processing",children:e("settings.envVars.plain","Plain")})},{title:e("settings.envVars.descriptionCol","Description"),dataIndex:"description",key:"description",ellipsis:!0,render:b=>b?t.jsx(Ct,{type:"secondary",children:b}):t.jsx(Ct,{type:"secondary",italic:!0,children:"—"})},{title:e("settings.envVars.actions","Actions"),key:"actions",width:120,render:(b,D)=>t.jsxs(F,{size:"small",children:[t.jsx(L,{type:"text",size:"small",icon:t.jsx(Ss,{}),onClick:()=>g(D),"aria-label":e("settings.envVars.edit","Edit")}),t.jsx(es,{title:e("settings.envVars.deleteConfirm","Delete this variable?"),onConfirm:()=>S(D.name),okText:e("settings.envVars.yes","Yes"),cancelText:e("settings.envVars.no","No"),children:t.jsx(L,{type:"text",size:"small",danger:!0,icon:t.jsx(ns,{}),"aria-label":e("settings.envVars.delete","Delete")})})]})}];return t.jsxs("div",{style:{maxWidth:900},children:[t.jsxs(R,{className:"lotus-settings-card",title:e("settings.envVars.title","Environment Variables"),extra:t.jsx(L,{type:"primary",icon:t.jsx(It,{}),onClick:w,children:e("settings.envVars.addButton","Add Variable")}),children:[t.jsx(_r,{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(dt,{dataSource:n,columns:_,rowKey:"name",size:"small",pagination:!1,loading:r,locale:{emptyText:e("settings.envVars.noVars","No environment variables configured")}})]}),t.jsx(ct,{title:c?e("settings.envVars.editTitle","Edit Variable"):e("settings.envVars.addTitle","Add Environment Variable"),open:l,onCancel:M,onOk:()=>u.submit(),okText:e("settings.envVars.save","Save"),cancelText:e("settings.envVars.cancel","Cancel"),destroyOnClose:!0,children:t.jsxs(v,{form:u,layout:"vertical",onFinish:f,initialValues:{secret:!1},children:[t.jsx(v.Item,{name:"name",label:e("settings.envVars.name","Name"),rules:[{required:!0,message:e("settings.envVars.nameRequired","Variable name is required")},{pattern:kr,message:e("settings.envVars.nameInvalid","Must start with a letter or underscore, followed by letters, digits, or underscores")}],children:t.jsx(B,{placeholder:"GITHUB_TOKEN",disabled:c!==null,autoFocus:c===null})}),t.jsx(v.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(B.Password,{placeholder:c?e("settings.envVars.valuePlaceholderEdit","Enter new value or leave empty"):e("settings.envVars.valuePlaceholder","Enter value"),visibilityToggle:!0})}),t.jsx(v.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(v.Item,{name:"description",label:e("settings.envVars.descriptionField","Description"),children:t.jsx(B,{placeholder:e("settings.envVars.descriptionPlaceholder","Optional description")})})]})})]})},wt=class wt{constructor(){}static getInstance(){return wt.instance||(wt.instance=new wt),wt.instance}async listWorkflows(){try{lt("[WorkflowManager]","[WorkflowManagerService] Listing workflows");const s=await on.get("bamboo/workflows"),n=Array.isArray(s)?s:[];return lt("[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{lt("[WorkflowManager]","[WorkflowManagerService] Getting workflow: "+s);const n=await on.get("bamboo/workflows/"+encodeURIComponent(s)),a=n!=null&&n.name?String(n.name):s,r={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 lt("[WorkflowManager]","[WorkflowManagerService] Got workflow:",n),{name:a,content:String((n==null?void 0:n.content)||""),metadata:r}}catch(n){throw console.error("[WorkflowManagerService] Failed to get workflow "+s+":",n),er(n)&&n.status===404?new Error("Workflow '"+s+"' not found"):n instanceof Error&&n.message.includes("404")?new Error("Workflow '"+s+"' not found"):n}}};an(wt,"instance");let Js=wt;const{Text:Rs}=ce,{TextArea:Cr}=B,{useToken:Mr}=fe,Er=e=>!(!e||e.includes("/")||e.includes("\\")||e.includes("..")),Dr=()=>{const{t:e}=se(),{token:s}=Mr(),[n,a]=At.useMessage(),[r,i]=o.useState([]),[l,p]=o.useState(!1),[c,d]=o.useState(!1),[u,j]=o.useState(!1),[f,S]=o.useState(null),[w,g]=o.useState(""),[M,_]=o.useState(""),[b,D]=o.useState(!1),k=o.useMemo(()=>Js.getInstance(),[]),A=o.useCallback(async()=>{p(!0);try{const h=await k.listWorkflows();return i(h),h}catch{return n.error(e("settings.workflowsTab.loadFailed")),[]}finally{p(!1)}},[n,e,k]);o.useEffect(()=>{A()},[A]);const te=o.useCallback(async h=>{S(h),g(h.name),D(!1),d(!0);try{const y=await k.getWorkflow(h.name);_(y.content??"")}catch{n.error(e("settings.workflowsTab.loadContentFailed")),_("")}finally{d(!1)}},[n,e,k]),z=()=>{S(null),g(""),_(""),D(!1)},U=o.useCallback(async()=>{if(!Er(w)){n.error(e("settings.workflowsTab.invalidName"));return}const h=r.some(y=>y.name===w);if(!f&&h){n.error(e("settings.workflowsTab.nameAlreadyExists"));return}j(!0);try{await rt.getInstance().saveWorkflow(w,M),n.success(e("settings.workflowsTab.saved")),D(!1);const E=(await A()).find(I=>I.name===w);E&&S(E)}catch(y){n.error(y instanceof Error?y.message:e("settings.workflowsTab.saveFailed"))}finally{j(!1)}},[M,w,A,n,f,e,r]),Z=o.useCallback(async h=>{try{await rt.getInstance().deleteWorkflow(h.name),n.success(e("settings.workflowsTab.deleted")),(f==null?void 0:f.name)===h.name&&z(),await A()}catch(y){n.error(y instanceof Error?y.message:e("settings.workflowsTab.deleteFailed"))}},[A,n,f,e]);return t.jsxs("div",{style:{padding:"24px"},children:[a,t.jsxs(R,{title:e("settings.workflowsTab.title"),extra:t.jsxs(F,{children:[t.jsx(L,{icon:t.jsx(Rt,{}),onClick:A,loading:l,children:e("settings.workflowsTab.refresh")}),t.jsx(L,{"data-testid":"create-workflow",icon:t.jsx(It,{}),onClick:z,children:e("settings.workflowsTab.newWorkflow")}),t.jsx(L,{"data-testid":"save-workflow",type:"primary",icon:t.jsx(js,{}),onClick:U,loading:u,disabled:!b,children:e("settings.workflowsTab.save")})]}),children:[t.jsx(Rs,{type:"secondary",children:e("settings.workflowsTab.description")}),t.jsxs(H,{gap:s.marginLG,style:{marginTop:s.marginLG},children:[t.jsx("div",{style:{width:320,flexShrink:0},children:t.jsx(et,{loading:l,dataSource:r,locale:{emptyText:e("settings.workflowsTab.empty")},renderItem:h=>t.jsx(et.Item,{style:{cursor:"pointer",backgroundColor:(f==null?void 0:f.name)===h.name?s.colorFillSecondary:"transparent",borderRadius:s.borderRadius,padding:s.paddingSM},onClick:()=>te(h),actions:[t.jsx(L,{"data-testid":`delete-workflow-${h.name}`,type:"text",danger:!0,size:"small",icon:t.jsx(ns,{}),onClick:y=>{y.stopPropagation(),Z(h)},"aria-label":e("settings.workflowsTab.delete")},"delete")],children:t.jsxs(F,{direction:"vertical",size:0,children:[t.jsxs(Rs,{strong:!0,children:["/",h.name]}),t.jsx(Rs,{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(B,{"data-testid":"workflow-name",placeholder:e("settings.workflowsTab.namePlaceholder"),value:w,onChange:h=>{g(h.target.value),D(!0)},disabled:!!f,prefix:t.jsx(Ss,{})}),t.jsx(Cr,{"data-testid":"workflow-content",placeholder:e("settings.workflowsTab.contentPlaceholder"),value:M,onChange:h=>{_(h.target.value),D(!0)},autoSize:{minRows:12},disabled:c})]})})]})]})]})};var $=(e=>(e.Connecting="connecting",e.Ready="ready",e.Degraded="degraded",e.Stopped="stopped",e.Error="error",e))($||{});const os=6e4,ls=3e4,ts=2e4,vs=1e4,_s=e=>({id:e,enabled:!0,transport:{type:"stdio",command:"",args:[],env:{},startup_timeout_ms:ts},request_timeout_ms:os,healthcheck_interval_ms:ls,allowed_tools:[],denied_tools:[]}),Pr=()=>({status:"stopped",tool_count:0,restart_count:0}),Ir=e=>{switch(typeof e=="string"?e.trim().toLowerCase():""){case $.Connecting:return $.Connecting;case $.Ready:return $.Ready;case $.Degraded:return $.Degraded;case $.Error:return $.Error;case $.Stopped:default:return $.Stopped}},it=(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},Fr=(e,s)=>{if(!e||typeof e!="object")return s;const n=e;if(n.type==="sse"){const i=Array.isArray(n.headers)?n.headers.map(l=>{if(!l||typeof l!="object")return null;const p=l;return typeof p.name!="string"||typeof p.value!="string"?null:{name:p.name,value:p.value}}).filter(l=>!!l):[];return{type:"sse",url:typeof n.url=="string"?n.url:"",headers:i,connect_timeout_ms:it(n.connect_timeout_ms,vs)}}const a=Array.isArray(n.args)?n.args.filter(i=>typeof i=="string"):[],r=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:r.reduce((i,[l,p])=>(typeof p=="string"&&(i[l]=p),i),{}),startup_timeout_ms:it(n.startup_timeout_ms,ts)}},Ar=(e,s)=>{const n=_s(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:it(a.request_timeout_ms,os),healthcheck_interval_ms:it(a.healthcheck_interval_ms,ls),allowed_tools:Array.isArray(a.allowed_tools)?a.allowed_tools.filter(i=>typeof i=="string"):[],denied_tools:Array.isArray(a.denied_tools)?a.denied_tools.filter(i=>typeof i=="string"):[],reconnect:a.reconnect&&typeof a.reconnect=="object"?{enabled:typeof a.reconnect.enabled=="boolean"?a.reconnect.enabled:!0,initial_backoff_ms:it(a.reconnect.initial_backoff_ms,1e3),max_backoff_ms:it(a.reconnect.max_backoff_ms,3e4),max_attempts:it(a.reconnect.max_attempts,0)}:void 0,transport:Fr(a.transport,n.transport)}},Rr=e=>{const s=Pr(),a=e.runtime??{},r=a.status??e.status;return{status:Ir(r),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:it(a.tool_count??e.tool_count,s.tool_count),restart_count:it(a.restart_count??e.restart_count,s.restart_count),last_ping_at:typeof a.last_ping_at=="string"?a.last_ping_at:void 0}},zr=e=>{const s=Ar(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:Rr(e)}},Lr=(e,s)=>`mcp__${e}__${s}`,Or=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),r=s.slice(n+2);return!a||!r?null:{server_id:a,original_name:r}},Nr=(e,s,n=0)=>{if(!e||typeof e!="object")return null;const a=e,r=typeof a.alias=="string"?a.alias:typeof a.name=="string"&&a.name.startsWith("mcp__")?a.name:void 0,i=r&&typeof r=="string"?Or(r):null,l=(typeof a.server_id=="string"?a.server_id:void 0)??(typeof a.serverId=="string"?a.serverId:void 0)??(i==null?void 0:i.server_id)??s??"",p=(typeof a.original_name=="string"?a.original_name:void 0)??(typeof a.originalName=="string"?a.originalName:void 0)??(i==null?void 0:i.original_name)??(typeof a.name=="string"?a.name:void 0)??"",c=r??(l&&p?Lr(l,p):""),d=typeof a.description=="string"?a.description:"",u=a,j="parameters"in u?u.parameters:"inputSchema"in u?u.inputSchema:"input_schema"in u?u.input_schema:void 0,f=c||p||`mcp_tool_${n}`;return{alias:f,server_id:l||"unknown",original_name:p||f,description:d,parameters:j}};class Vr{async getServers(){const s=await tt.get("mcp/servers");return Array.isArray(s.servers)?s.servers.map(zr):[]}async addServer(s){return tt.post("mcp/servers",s)}async updateServer(s,n){const a={...n,id:s};return tt.put(`mcp/servers/${s}`,a)}async deleteServer(s){return tt.delete(`mcp/servers/${s}`)}async connectServer(s){return tt.post(`mcp/servers/${s}/connect`)}async disconnectServer(s){return tt.post(`mcp/servers/${s}/disconnect`)}async refreshTools(s){return tt.post(`mcp/servers/${s}/refresh`)}async getTools(s){const n=s?`mcp/servers/${s}/tools`:"mcp/tools",a=await tt.get(n);return(Array.isArray(a.tools)?a.tools:[]).map((i,l)=>Nr(i,s,l)).filter(i=>!!i)}async importServers(s){return tt.post("mcp/servers/import",s)}}const ea=new Vr,$r=5e3,st=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,bn=(e,s)=>`${e}:${s}`,Br=(e={})=>{const{service:s=ea,autoRefreshMs:n=$r,autoRefreshEnabled:a=!0}=e,[r,i]=o.useState([]),[l,p]=o.useState(null),[c,d]=o.useState({}),[u,j]=o.useState({}),[f,S]=o.useState({}),[w,g]=o.useState(!1),[M,_]=o.useState(!1),[b,D]=o.useState(!1),[k,A]=o.useState(null),te=o.useRef({}),z=o.useCallback(C=>{const G=new Set(C.map(ee=>ee.id)),X=C.map(ee=>{const Ie=te.current[ee.id]??ee.config,$e={...Ie,id:ee.id,name:Ie.name??ee.name};return te.current[ee.id]=$e,{...ee,name:ee.name||$e.name||ee.id,enabled:ee.enabled??$e.enabled,config:$e}});return Object.keys(te.current).forEach(ee=>{G.has(ee)||delete te.current[ee]}),X},[]),U=o.useCallback(async({silent:C=!1}={})=>{C||g(!0);try{const G=await s.getServers(),X=z(G);i(X),p(ee=>{var Pe;return ee&&X.some(Ie=>Ie.id===ee)?ee:((Pe=X[0])==null?void 0:Pe.id)??null}),A(null)}catch(G){throw A(st(G,"Failed to load MCP servers")),G}finally{C||g(!1)}},[z,s]),Z=o.useCallback(async(C,G=!1)=>{if(!C)return[];if(!G&&c[C])return c[C];j(X=>({...X,[C]:!0}));try{const X=await s.getTools(C);return d(ee=>({...ee,[C]:X})),A(null),X}catch(X){throw A(st(X,"Failed to load MCP tools")),X}finally{j(X=>({...X,[C]:!1}))}},[s,c]),h=o.useCallback((C,G,X)=>{const ee=bn(C,G);S(Pe=>({...Pe,[ee]:X}))},[]),y=o.useCallback(async C=>{_(!0);try{await s.addServer(C),te.current[C.id]=C,await U()}catch(G){throw A(st(G,"Failed to add MCP server")),G}finally{_(!1)}},[U,s]),P=o.useCallback(async(C,G)=>{_(!0);try{const X={...G,id:C};await s.updateServer(C,X),te.current[C]=X,await U()}catch(X){throw A(st(X,"Failed to update MCP server")),X}finally{_(!1)}},[U,s]),E=o.useCallback(async C=>{h(C,"delete",!0);try{await s.deleteServer(C),d(G=>{const X={...G};return delete X[C],X}),delete te.current[C],await U()}catch(G){throw A(st(G,"Failed to delete MCP server")),G}finally{h(C,"delete",!1)}},[U,s,h]),I=o.useCallback(async C=>{h(C,"connect",!0);try{await s.connectServer(C),await U({silent:!0})}catch(G){throw A(st(G,"Failed to connect MCP server")),G}finally{h(C,"connect",!1)}},[U,s,h]),O=o.useCallback(async C=>{h(C,"disconnect",!0);try{await s.disconnectServer(C),await U({silent:!0})}catch(G){throw A(st(G,"Failed to disconnect MCP server")),G}finally{h(C,"disconnect",!1)}},[U,s,h]),K=o.useCallback(async C=>{h(C,"refresh",!0);try{await s.refreshTools(C),await Z(C,!0),await U({silent:!0})}catch(G){throw A(st(G,"Failed to refresh MCP tools")),G}finally{h(C,"refresh",!1)}},[Z,U,s,h]),Q=o.useCallback(async()=>{D(!0);try{const C=r.map(G=>G.id);await Promise.all(C.map(async G=>{try{await s.refreshTools(G)}catch{}})),await U(),l&&await Z(l,!0)}catch(C){throw A(st(C,"Failed to refresh MCP status")),C}finally{D(!1)}},[Z,U,l,r,s]),W=o.useCallback(C=>{p(C)},[]),pe=o.useCallback((C,G)=>!!f[bn(C,G)],[f]),he=o.useMemo(()=>l?c[l]??[]:[],[l,c]),De=o.useMemo(()=>l?!!u[l]:!1,[l,u]);return o.useEffect(()=>{U().catch(()=>{})},[U]),o.useEffect(()=>{if(!a||n<=0)return;const C=window.setInterval(()=>{U({silent:!0}).catch(()=>{})},n);return()=>{window.clearInterval(C)}},[a,n,U]),o.useEffect(()=>{l&&Z(l).catch(()=>{})},[Z,l]),{servers:r,selectedServerId:l,selectedServerTools:he,isLoadingServers:w,isMutatingConfig:M,isRefreshingAll:b,isSelectedServerToolsLoading:De,error:k,setSelectedServerId:W,refreshServers:U,addServer:y,updateServer:P,deleteServer:E,connectServer:I,disconnectServer:O,refreshServerTools:K,refreshAll:Q,isServerActionLoading:pe}},qr={[$.Connecting]:"blue",[$.Ready]:"green",[$.Degraded]:"orange",[$.Stopped]:"default",[$.Error]:"red"},Ur=e=>e===$.Connecting||e===$.Ready||e===$.Degraded,Hr=e=>{if(!e)return;const s=e.replace(/\s+/g," ").trim();if(s)return s.length>180?`${s.slice(0,180)}...`:s},Kr=({servers:e,loading:s=!1,selectedServerId:n,onSelectServer:a,onEditServer:r,onDeleteServer:i,onConnectServer:l,onDisconnectServer:p,onRefreshTools:c,isServerActionLoading:d})=>{const{t:u}=se(),{token:j}=fe.useToken(),f=o.useMemo(()=>({[$.Connecting]:u("settings.mcpTab.statusHelp.connecting"),[$.Ready]:u("settings.mcpTab.statusHelp.ready"),[$.Degraded]:u("settings.mcpTab.statusHelp.degraded"),[$.Stopped]:u("settings.mcpTab.statusHelp.stopped"),[$.Error]:u("settings.mcpTab.statusHelp.error")}),[u]),S=o.useMemo(()=>[{key:"name",title:u("settings.mcpServerTable.columns.name"),render:(w,g)=>g.name||g.id},{key:"transport",title:u("settings.mcpServerTable.columns.transportType"),render:(w,g)=>g.config.transport.type==="sse"?u("settings.mcpServerTable.transportOptions.sse"):u("settings.mcpServerTable.transportOptions.stdio"),width:140},{key:"status",title:u("settings.mcpServerTable.columns.status"),render:(w,g)=>{var k,A;const M=((k=g.runtime)==null?void 0:k.status)??$.Stopped,_=Hr((A=g.runtime)==null?void 0:A.last_error),b=f[M],D={[$.Connecting]:u("settings.mcpTab.status.connecting"),[$.Ready]:u("settings.mcpTab.status.ready"),[$.Degraded]:u("settings.mcpTab.status.degraded"),[$.Stopped]:u("settings.mcpTab.status.stopped"),[$.Error]:u("settings.mcpTab.status.error")};return t.jsx(Se,{title:_?`${b} ${u("settings.mcpTab.statusLastError",{error:_})}`:b,children:t.jsx(le,{color:M===$.Stopped?void 0:qr[M],style:{marginInlineEnd:0,cursor:"help",...M===$.Stopped?{background:j.colorFillSecondary,borderColor:j.colorBorderSecondary,color:j.colorTextSecondary}:void 0},children:D[M]})})},width:120},{key:"toolCount",title:u("settings.mcpServerTable.columns.toolCount"),render:(w,g)=>{var M;return((M=g.runtime)==null?void 0:M.tool_count)??0},width:100},{key:"actions",title:u("settings.mcpServerTable.columns.actions"),width:360,render:(w,g)=>{var b;const M=((b=g.runtime)==null?void 0:b.status)??$.Stopped,_=Ur(M);return t.jsxs(F,{size:j.marginXS,children:[t.jsx(L,{size:"small",onClick:D=>{D.stopPropagation(),r==null||r(g)},children:u("settings.mcpServerTable.actions.edit")}),t.jsx(es,{title:u("settings.mcpServerTable.deleteTitle"),description:u("settings.mcpServerTable.deleteDescription",{name:g.name||g.id}),onConfirm:()=>i==null?void 0:i(g),okText:u("settings.mcpServerTable.actions.delete"),okButtonProps:{danger:!0,loading:d==null?void 0:d(g.id,"delete")},children:t.jsx(L,{size:"small",danger:!0,loading:d==null?void 0:d(g.id,"delete"),onClick:D=>D.stopPropagation(),children:u("settings.mcpServerTable.actions.delete")})}),_?t.jsx(L,{size:"small",onClick:D=>{D.stopPropagation(),p==null||p(g)},loading:d==null?void 0:d(g.id,"disconnect"),children:u("settings.mcpServerTable.actions.disconnect")}):t.jsx(L,{size:"small",type:"primary",ghost:!0,onClick:D=>{D.stopPropagation(),l==null||l(g)},loading:d==null?void 0:d(g.id,"connect"),children:u("settings.mcpServerTable.actions.connect")}),t.jsx(L,{size:"small",onClick:D=>{D.stopPropagation(),c==null||c(g)},loading:d==null?void 0:d(g.id,"refresh"),children:u("settings.mcpServerTable.actions.refreshTools")})]})}}],[d,l,i,p,r,c,f,u,j.colorBorderSecondary,j.colorFillSecondary,j.colorTextSecondary,j.marginXS]);return t.jsx(dt,{rowKey:"id",columns:S,dataSource:e,loading:s,pagination:!1,locale:{emptyText:u("settings.mcpServerTable.empty")},onRow:w=>({onClick:()=>a==null?void 0:a(w.id),style:{cursor:a?"pointer":"default",backgroundColor:n===w.id?j.colorFillSecondary:void 0}})})},{Text:vn}=ce,{TextArea:Wr}=B,Tn=e=>{const s=e??_s(""),n=s.transport,a=n.type==="stdio"?Object.entries(n.env??{}).map(([i,l])=>({key:i,value:l})):[],r=n.type==="sse"?n.headers.map(i=>({name:i.name,value:i.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:r,requestTimeoutMs:s.request_timeout_ms||os,healthcheckIntervalMs:s.healthcheck_interval_ms||ls,allowedTools:s.allowed_tools||[],deniedTools:s.denied_tools||[]}},Gr=e=>e.reduce((s,n)=>{var r;const a=(r=n.key)==null?void 0:r.trim();return a&&(s[a]=n.value??""),s},{}),Jr=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??""}}),jn=(e,s,n)=>{var u,j,f;const a=s==="edit"&&(n==null?void 0:n.id)||e.id,r=(u=e.name)==null?void 0:u.trim(),i=typeof e.requestTimeoutMs=="number"?e.requestTimeoutMs:(n==null?void 0:n.request_timeout_ms)??os,l=typeof e.healthcheckIntervalMs=="number"?e.healthcheckIntervalMs:(n==null?void 0:n.healthcheck_interval_ms)??ls,p=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)??[],d=e.transportType==="sse"?{type:"sse",url:((j=e.url)==null?void 0:j.trim())||"",headers:Jr(e.headerEntries||[]),connect_timeout_ms:(n==null?void 0:n.transport.type)==="sse"?n.transport.connect_timeout_ms??vs:vs}:{type:"stdio",command:((f=e.command)==null?void 0:f.trim())||"",args:e.args||[],env:Gr(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??ts:ts};return{id:a,name:r||void 0,enabled:e.enabled,transport:d,request_timeout_ms:i,healthcheck_interval_ms:l,allowed_tools:p,denied_tools:c,reconnect:n==null?void 0:n.reconnect}},Sn=e=>JSON.stringify(e||_s(""),null,2),zs=(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 r=typeof a.id=="string"?a.id:"";if(!r.trim())return{valid:!1,error:s("settings.mcpServerForm.missingIdField")};if(a.transport&&typeof a.transport=="object"){const j=a;return!j.transport||typeof j.transport!="object"?{valid:!1,error:s("settings.mcpServerForm.missingTransportField")}:{valid:!0,config:j}}const i=typeof a.enabled=="boolean"?a.enabled:typeof a.disabled=="boolean"?!a.disabled:!0,l=typeof a.request_timeout_ms=="number"?a.request_timeout_ms:os,p=typeof a.healthcheck_interval_ms=="number"?a.healthcheck_interval_ms:ls,c=Array.isArray(a.allowed_tools)?a.allowed_tools.filter(j=>typeof j=="string"):[],d=Array.isArray(a.denied_tools)?a.denied_tools.filter(j=>typeof j=="string"):[],u=typeof a.name=="string"?a.name:void 0;if(typeof a.url=="string"){const j=a.headers,f=Array.isArray(j)?j.map(w=>{if(!w||typeof w!="object")return null;const g=w,M=typeof g.name=="string"?g.name:"",_=typeof g.value=="string"?g.value:"";return M.trim()?{name:M,value:_}:null}).filter(w=>!!w):j&&typeof j=="object"?Object.entries(j).filter(([w])=>w.trim()).map(([w,g])=>({name:w,value:typeof g=="string"?g:""})):[],S=typeof a.connect_timeout_ms=="number"?a.connect_timeout_ms:vs;return{valid:!0,config:{id:r,name:u,enabled:i,transport:{type:"sse",url:a.url,headers:f,connect_timeout_ms:S},request_timeout_ms:l,healthcheck_interval_ms:p,allowed_tools:c,denied_tools:d,reconnect:void 0}}}if(typeof a.command=="string"){const j=Array.isArray(a.args)?a.args.filter(g=>typeof g=="string"):[],f=a.env,S=f&&typeof f=="object"?Object.entries(f).reduce((g,[M,_])=>(typeof _=="string"&&(g[M]=_),g),{}):{},w=typeof a.startup_timeout_ms=="number"?a.startup_timeout_ms:ts;return{valid:!0,config:{id:r,name:u,enabled:i,transport:{type:"stdio",command:a.command,args:j,cwd:typeof a.cwd=="string"?a.cwd:void 0,env:S,startup_timeout_ms:w},request_timeout_ms:l,healthcheck_interval_ms:p,allowed_tools:c,denied_tools:d,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")})}}},Xr=({open:e,mode:s,initialConfig:n,confirmLoading:a=!1,onCancel:r,onSubmit:i})=>{const{t:l}=se(),[p]=v.useForm(),[c,d]=o.useState("form"),[u,j]=o.useState(""),[f,S]=o.useState(null),w=o.useMemo(()=>Tn(n),[n]),g=v.useWatch("transportType",p)??"stdio";o.useEffect(()=>{e&&(p.setFieldsValue(w),j(Sn(n)),S(null),d("form"))},[p,w,n,e]);const M=()=>{p.resetFields(),j(""),S(null),r()},_=async()=>{if(c==="json"){const k=zs(u,l);if(!k.valid){S(k.error);return}S(null);try{await i(k.config),j("")}catch(A){console.error("MCP server JSON submission error:",A)}return}try{const k=await p.validateFields(),A=jn(k,s,n);await i(A),p.resetFields()}catch(k){console.error("MCP server form submission error:",k)}},b=k=>{j(k),f&&zs(k,l).valid&&S(null)},D=k=>{if(k==="json")try{const A=p.getFieldsValue(),te=jn(A,s,n);j(JSON.stringify(te,null,2))}catch{j(Sn(n))}else{const A=zs(u,l);A.valid&&p.setFieldsValue(Tn(A.config))}d(k),S(null)};return t.jsxs(ct,{title:l(s==="edit"?"settings.mcpServerForm.editTitle":"settings.mcpServerForm.addTitle"),open:e,onCancel:M,onOk:()=>{_()},okText:l("settings.mcpServerForm.save"),destroyOnClose:!0,forceRender:!0,confirmLoading:a,width:720,children:[t.jsx("div",{style:{marginBottom:16},children:t.jsxs(Dt.Group,{value:c,onChange:k=>D(k.target.value),optionType:"button",buttonStyle:"solid",children:[t.jsxs(Dt.Button,{value:"form",children:[t.jsx(La,{})," ",l("settings.mcpServerForm.modeForm")]}),t.jsxs(Dt.Button,{value:"json",children:[t.jsx(Oa,{})," ",l("settings.mcpServerForm.modeJson")]})]})}),c==="json"&&f&&t.jsx(Ve,{type:"error",message:l("settings.mcpServerForm.jsonError"),description:f,showIcon:!0,style:{marginBottom:16},closable:!0,onClose:()=>S(null)}),c==="json"?t.jsx(Wr,{value:u,onChange:k=>b(k.target.value),rows:20,style:{fontFamily:"monospace",fontSize:13},placeholder:JSON.stringify(_s("example-server"),null,2)}):t.jsxs(v,{layout:"vertical",form:p,preserve:!0,initialValues:w,children:[t.jsx(v.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(B,{placeholder:"filesystem",disabled:s==="edit",autoComplete:"off"})}),t.jsx(v.Item,{name:"name",label:l("settings.mcpServerForm.displayName"),children:t.jsx(B,{placeholder:"Filesystem MCP",autoComplete:"off"})}),t.jsx(v.Item,{name:"enabled",label:l("settings.mcpServerForm.enabled"),valuePropName:"checked",extra:l("settings.mcpServerForm.enabledHelp"),children:t.jsx(ge,{})}),t.jsx(v.Item,{name:"transportType",label:l("settings.mcpServerForm.transportType"),rules:[{required:!0,message:l("settings.mcpServerForm.transportTypeRequired")}],children:t.jsx(Y,{options:[{label:l("settings.mcpServerForm.transportOptions.stdio"),value:"stdio"},{label:l("settings.mcpServerForm.transportOptions.sse"),value:"sse"}]})}),g==="stdio"?t.jsxs(t.Fragment,{children:[t.jsx(v.Item,{name:"command",label:l("settings.mcpServerForm.command"),rules:[{required:!0,message:l("settings.mcpServerForm.commandRequired")}],children:t.jsx(B,{placeholder:"npx",autoComplete:"off"})}),t.jsx(v.Item,{name:"args",label:l("settings.mcpServerForm.arguments"),children:t.jsx(Y,{mode:"tags",tokenSeparators:[","],placeholder:l("settings.mcpServerForm.argumentsPlaceholder"),open:!1})}),t.jsx(v.List,{name:"envEntries",children:(k,{add:A,remove:te})=>t.jsxs(F,{direction:"vertical",style:{width:"100%"},children:[t.jsxs(F,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[t.jsx(vn,{strong:!0,children:l("settings.mcpServerForm.envVars")}),t.jsx(L,{icon:t.jsx(It,{}),onClick:()=>A({key:"",value:""}),type:"dashed",children:l("settings.mcpServerForm.addEnv")})]}),k.map(z=>t.jsxs(F,{align:"baseline",style:{display:"flex"},children:[t.jsx(v.Item,{...z,name:[z.name,"key"],rules:[{required:!0,message:l("settings.mcpServerForm.keyRequired")}],children:t.jsx(B,{placeholder:"MCP_ROOT",autoComplete:"off"})}),t.jsx(v.Item,{...z,name:[z.name,"value"],children:t.jsx(B,{placeholder:"/Users/me/workspace",autoComplete:"off"})}),t.jsx(L,{danger:!0,type:"text",icon:t.jsx(pn,{}),onClick:()=>te(z.name),"aria-label":l("settings.mcpServerForm.removeEnv","Remove environment variable")})]},z.key))]})})]}):t.jsxs(t.Fragment,{children:[t.jsx(v.Item,{name:"url",label:l("settings.mcpServerForm.sseUrl"),rules:[{required:!0,message:l("settings.mcpServerForm.sseUrlRequired")},{validator:async(k,A)=>{if(A)try{new URL(A)}catch{throw new Error(l("settings.mcpServerForm.validUrlRequired"))}}}],children:t.jsx(B,{placeholder:"http://localhost:4000/sse",autoComplete:"off"})}),t.jsx(v.List,{name:"headerEntries",children:(k,{add:A,remove:te})=>t.jsxs(F,{direction:"vertical",style:{width:"100%"},children:[t.jsxs(F,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[t.jsx(vn,{strong:!0,children:l("settings.mcpServerForm.headers")}),t.jsx(L,{icon:t.jsx(It,{}),onClick:()=>A({name:"",value:""}),type:"dashed",children:l("settings.mcpServerForm.addHeader")})]}),k.map(z=>t.jsxs(F,{align:"baseline",style:{display:"flex"},children:[t.jsx(v.Item,{...z,name:[z.name,"name"],rules:[{required:!0,message:l("settings.mcpServerForm.headerNameRequired")}],children:t.jsx(B,{placeholder:"Authorization",autoComplete:"off"})}),t.jsx(v.Item,{...z,name:[z.name,"value"],children:t.jsx(B,{placeholder:"Bearer token",autoComplete:"off"})}),t.jsx(L,{danger:!0,type:"text",icon:t.jsx(pn,{}),onClick:()=>te(z.name),"aria-label":l("settings.mcpServerForm.removeHeader","Remove header")})]},z.key))]})})]})]})]})},ys=e=>!!e&&typeof e=="object"&&!Array.isArray(e),jt=(e,s)=>{const n=e[s];return typeof n=="string"?n:void 0},_n=(e,s)=>{const n=e[s];return typeof n=="boolean"?n:void 0},Yr=(e,s)=>{const n=e[s];return Array.isArray(n)?n:void 0},Yt=e=>{if(!ys(e))return"any";const s=e.type;if(typeof s=="string"){if(s==="array"){const i=e.items;return`array<${Yt(i)}>`}return s==="object"?"object":s}if(Array.isArray(s)){const i=s.filter(l=>typeof l=="string").map(l=>l==="array"?"array<any>":l);return i.length>0?i.join(" | "):"any"}const n=Array.isArray(e.oneOf)?e.oneOf:null;if(n)return n.map(Yt).join(" | ")||"any";const a=Array.isArray(e.anyOf)?e.anyOf:null;if(a)return a.map(Yt).join(" | ")||"any";const r=Array.isArray(e.allOf)?e.allOf:null;return r&&r.map(Yt).join(" & ")||"any"},Zr=e=>{if(!ys(e))return null;const s=e.properties;if(!ys(s))return{schemaUri:jt(e,"$schema"),title:jt(e,"title"),description:jt(e,"description"),additionalProperties:_n(e,"additionalProperties"),fields:[]};const n=new Set((Yr(e,"required")??[]).filter(r=>typeof r=="string").map(r=>r)),a=Object.entries(s).map(([r,i])=>{const l=ys(i)?i:void 0;return{name:r,type:Yt(i),required:n.has(r),description:l?jt(l,"description"):void 0,defaultValue:l?l.default:void 0,enumValues:l&&Array.isArray(l.enum)?l.enum:void 0}});return a.sort((r,i)=>r.required!==i.required?r.required?-1:1:r.name.localeCompare(i.name)),{schemaUri:jt(e,"$schema"),title:jt(e,"title"),description:jt(e,"description"),additionalProperties:_n(e,"additionalProperties"),fields:a}},{Text:Ze}=ce,Qr=e=>e===void 0?"":e===null?"null":typeof e=="string"?e:Xn(e,0),ei=({schema:e})=>{const{token:s}=fe.useToken(),{t:n}=se(),a=o.useMemo(()=>Zr(e),[e]);if(!a)return t.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:Xn(e,2)});const r=[{title:n("components.jsonSchema.field"),dataIndex:"name",key:"name",width:180,render:l=>t.jsx(Ze,{code:!0,children:l})},{title:n("components.jsonSchema.type"),dataIndex:"type",key:"type",width:140,render:l=>t.jsx(Ze,{children:l})},{title:n("components.jsonSchema.required"),dataIndex:"required",key:"required",width:110,render:l=>l?t.jsx(Ze,{strong:!0,style:{color:s.colorError},children:n("components.jsonSchema.yes")}):t.jsx(Ze,{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(Ze,{type:"secondary",children:"-"}):t.jsx(Ze,{children:Qr(l)})},{title:n("components.jsonSchema.description"),dataIndex:"description",key:"description",render:l=>l?t.jsx(Ze,{style:{whiteSpace:"pre-wrap"},children:l}):t.jsx(Ze,{type:"secondary",children:"-"})}],i=(a.fields??[]).map(l=>({...l,key:l.name}));return t.jsxs("div",{style:{width:"100%"},children:[t.jsx(Ae,{size:"small",column:1,items:[a.schemaUri?{key:"schema",label:"$schema",children:t.jsx(Ze,{code:!0,children:a.schemaUri})}:null,typeof a.additionalProperties=="boolean"?{key:"additionalProperties",label:"additionalProperties",children:t.jsx(Ze,{children:a.additionalProperties?"true":"false"})}:null].filter(Boolean)}),t.jsx(dt,{size:"small",pagination:!1,columns:r,dataSource:i,locale:{emptyText:n("components.jsonSchema.noProperties")},style:{marginTop:s.marginSM}})]})},{Text:qt}=ce,ti=(e,s)=>`mcp__${e}__${s}`,si=({server:e,tools:s,loading:n=!1})=>{const{t:a}=se();return t.jsx(R,{title:a("settings.mcpToolList.title"),size:"small",children:e?t.jsx(et,{loading:n,dataSource:s,locale:{emptyText:a("settings.mcpToolList.empty")},renderItem:r=>{const i=ti(r.server_id,r.original_name);return t.jsx(et.Item,{children:t.jsxs(F,{direction:"vertical",size:2,style:{width:"100%"},children:[t.jsx(qt,{strong:!0,children:r.original_name}),t.jsx(qt,{type:"secondary",children:r.description||a("settings.mcpToolList.noDescription")}),t.jsx(qt,{code:!0,children:r.alias}),t.jsxs(qt,{type:"secondary",children:[a("settings.mcpToolList.aliasMapping"),": ",t.jsx(qt,{code:!0,children:i})]}),r.parameters!==void 0&&t.jsx(Ts,{size:"small",items:[{key:"schema",label:a("settings.mcpToolList.parametersSchema"),children:t.jsx(ei,{schema:r.parameters})}]})]})})}}):t.jsx(Ue,{image:Ue.PRESENTED_IMAGE_SIMPLE,description:a("settings.mcpToolList.selectServerHint")})})},{Text:Ut}=ce,{useToken:ni}=fe,{TextArea:ai}=B,kn={[$.Connecting]:"processing",[$.Ready]:"success",[$.Degraded]:"warning",[$.Stopped]:"default",[$.Error]:"error"},ri=()=>({[$.Connecting]:0,[$.Ready]:0,[$.Degraded]:0,[$.Stopped]:0,[$.Error]:0}),St=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,ii=e=>{var n,a,r;const s={};for(const i of e){const l=(n=i.id)==null?void 0:n.trim();if(!l)continue;const c=!(i.enabled??i.config.enabled),d=i.config.transport;if(d.type==="sse"){const j={};for(const S of d.headers??[]){const w=(a=S.name)==null?void 0:a.trim();w&&(j[w]=S.value??"")}const f={url:d.url};c&&(f.disabled=!0),Object.keys(j).length&&(f.headers=j),s[l]=f;continue}const u={command:d.command};c&&(u.disabled=!0),(r=d.args)!=null&&r.length&&(u.args=d.args),d.cwd&&(u.cwd=d.cwd),d.env&&Object.keys(d.env).length&&(u.env=d.env),s[l]=u}return{mcpServers:s}},oi=()=>{const{t:e}=se(),{token:s}=ni(),[n,a]=At.useMessage(),{servers:r,selectedServerId:i,selectedServerTools:l,isLoadingServers:p,isMutatingConfig:c,isRefreshingAll:d,isSelectedServerToolsLoading:u,error:j,setSelectedServerId:f,addServer:S,updateServer:w,deleteServer:g,connectServer:M,disconnectServer:_,refreshServerTools:b,refreshAll:D,isServerActionLoading:k}=Br(),A=o.useMemo(()=>({[$.Connecting]:e("settings.mcpTab.status.connecting"),[$.Ready]:e("settings.mcpTab.status.ready"),[$.Degraded]:e("settings.mcpTab.status.degraded"),[$.Stopped]:e("settings.mcpTab.status.stopped"),[$.Error]:e("settings.mcpTab.status.error")}),[e]),te=o.useMemo(()=>({[$.Connecting]:e("settings.mcpTab.statusHelp.connecting"),[$.Ready]:e("settings.mcpTab.statusHelp.ready"),[$.Degraded]:e("settings.mcpTab.statusHelp.degraded"),[$.Stopped]:e("settings.mcpTab.statusHelp.stopped"),[$.Error]:e("settings.mcpTab.statusHelp.error")}),[e]),[z,U]=o.useState(!1),[Z,h]=o.useState("create"),[y,P]=o.useState(null),[E,I]=o.useState(!1),[O,K]=o.useState("merge"),[Q,W]=o.useState(""),[pe,he]=o.useState(null),[De,C]=o.useState(!1),G=o.useMemo(()=>i?r.find(m=>m.id===i)??null:null,[i,r]),X=o.useMemo(()=>{const m=ri();let re=0;return r.forEach(me=>{var ye,Oe;const Le=((ye=me.runtime)==null?void 0:ye.status)??$.Stopped;m[Le]+=1,re+=((Oe=me.runtime)==null?void 0:Oe.tool_count)??0}),{byStatus:m,totalServers:r.length,totalTools:re}},[r]),ee={background:s.colorFillSecondary,borderColor:s.colorBorderSecondary,color:s.colorTextSecondary},Pe=async m=>{try{await g(m.id),n.success(e("settings.mcpTab.serverDeleted"))}catch(re){n.error(St(re,e("settings.mcpTab.deleteServerFailed")))}},Ie=async m=>{try{await M(m.id),n.success(e("settings.mcpTab.connectedTo",{name:m.name||m.id}))}catch(re){n.error(St(re,e("settings.mcpTab.connectServerFailed")))}},$e=async m=>{try{await _(m.id),n.success(e("settings.mcpTab.disconnected",{name:m.name||m.id}))}catch(re){n.error(St(re,e("settings.mcpTab.disconnectServerFailed")))}},Xe=async m=>{try{await b(m.id),n.success(e("settings.mcpTab.toolsRefreshedFor",{name:m.name||m.id}))}catch(re){n.error(St(re,e("settings.mcpTab.refreshToolsFailed")))}},V=async()=>{try{await D(),n.success(e("settings.mcpTab.statusRefreshed"))}catch(m){n.error(St(m,e("settings.mcpTab.refreshStatusFailed")))}},ve=()=>{P(null),h("create"),U(!0)},He=m=>{P(m),h("edit"),U(!0)},Ce=async m=>{try{if(Z==="edit"){if(!y){n.error(e("settings.mcpTab.noServerForEditing"));return}await w(y.id,m),n.success(e("settings.mcpTab.savedServer",{name:y.name||y.id}))}else await S(m),n.success(e("settings.mcpTab.addedServer",{name:m.name||m.id}));U(!1),P(null)}catch(re){n.error(St(re,e("settings.mcpTab.saveServerFailed")))}},ze=()=>{I(!0),he(null),K("merge"),W("")},ke=async()=>{const m=ii(r),re=JSON.stringify(m,null,2);try{await Zs(re),n.success(e("settings.mcpTab.copiedConfig"))}catch{I(!0),he(null),K("merge"),W(re),n.warning(e("settings.mcpTab.clipboardUnavailable"))}},Ke=async()=>{var Le;he(null);let m;try{m=JSON.parse(Q)}catch(ye){he(`${e("settings.mcpTab.invalidJsonPrefix")}: ${ye instanceof Error?ye.message:e("settings.mcpTab.unknownError")}`);return}if(!m||typeof m!="object"){he(e("settings.mcpTab.jsonMustBeObject"));return}const me=m.mcpServers;if(!me||typeof me!="object"){he(e("settings.mcpTab.missingMcpServers"));return}C(!0);try{const ye=await ea.importServers({mcpServers:me,mode:O}),Oe=((Le=ye.start_errors)==null?void 0:Le.length)??0;n.success(e("settings.mcpTab.importSummary",{count:ye.server_ids.length,added:ye.added,updated:ye.updated,removed:ye.removed,failed:Oe})),Oe&&n.warning(e("settings.mcpTab.importStartFailures")),I(!1),W(""),await V()}catch(ye){he(St(ye,e("settings.mcpTab.importFailed")))}finally{C(!1)}};return t.jsxs(F,{direction:"vertical",size:s.marginMD,style:{width:"100%"},children:[a,j?t.jsx(Ve,{type:"error",showIcon:!0,message:j}):null,t.jsx(R,{size:"small",title:e("settings.mcpTab.overviewTitle"),children:t.jsxs(F,{direction:"vertical",size:s.marginXS,style:{width:"100%"},children:[t.jsx(Ut,{type:"secondary",children:e("settings.mcpTab.overviewDescription")}),t.jsxs(F,{wrap:!0,children:[t.jsx(le,{style:ee,children:e("settings.mcpTab.totalServers",{count:X.totalServers})}),t.jsx(le,{style:ee,children:e("settings.mcpTab.totalTools",{count:X.totalTools})}),Object.values($).map(m=>t.jsx(Se,{title:te[m],children:t.jsxs(le,{color:m===$.Stopped?void 0:kn[m],style:{cursor:"help",...m===$.Stopped?ee:void 0},children:[A[m],": ",X.byStatus[m]]})},m))]}),t.jsx(Ut,{type:"secondary",children:e("settings.mcpTab.statusGuideTitle")}),t.jsx(F,{direction:"vertical",size:2,style:{width:"100%"},children:Object.values($).map(m=>t.jsxs(Ut,{type:"secondary",children:[t.jsx(le,{color:m===$.Stopped?void 0:kn[m],style:{marginInlineEnd:8,...m===$.Stopped?ee:void 0},children:A[m]}),te[m]]},`guide-${m}`))})]})}),t.jsx(R,{size:"small",title:e("settings.mcpTab.serversTitle"),extra:t.jsxs(F,{children:[t.jsx(L,{type:"primary",onClick:ve,children:e("settings.mcpTab.addServer")}),t.jsx(L,{icon:t.jsx(Rt,{}),loading:d,onClick:()=>{V()},children:e("settings.mcpTab.refreshAll")}),t.jsx(L,{icon:t.jsx(Yn,{}),onClick:()=>void ke(),children:e("settings.mcpTab.export")}),t.jsx(L,{icon:t.jsx(Na,{}),onClick:ze,children:e("settings.mcpTab.import")})]}),children:t.jsx(Kr,{servers:r,loading:p,selectedServerId:i,onSelectServer:f,onEditServer:He,onDeleteServer:Pe,onConnectServer:Ie,onDisconnectServer:$e,onRefreshTools:Xe,isServerActionLoading:k})}),t.jsx(si,{server:G,tools:l,loading:u}),t.jsx(Xr,{open:z,mode:Z,initialConfig:(y==null?void 0:y.config)??null,confirmLoading:c,onCancel:()=>{c||(U(!1),P(null))},onSubmit:m=>void Ce(m)}),t.jsx(ct,{open:E,title:e("settings.mcpTab.importModalTitle"),okText:e("settings.mcpTab.import"),onOk:()=>void Ke(),okButtonProps:{loading:De},onCancel:()=>{De||(I(!1),he(null))},width:800,destroyOnClose:!1,children:t.jsxs(F,{direction:"vertical",style:{width:"100%"},size:"middle",children:[t.jsxs(Ut,{type:"secondary",children:[e("settings.mcpTab.importHint"),t.jsx("br",{}),t.jsx(Ut,{code:!0,children:'{ "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "..."] } } }'})]}),t.jsxs(Dt.Group,{value:O,onChange:m=>K(m.target.value),optionType:"button",buttonStyle:"solid",children:[t.jsx(Dt.Button,{value:"merge",children:e("settings.mcpTab.importModeMerge")}),t.jsx(Dt.Button,{value:"replace",children:e("settings.mcpTab.importModeReplace")})]}),O==="replace"?t.jsx(Ve,{type:"warning",showIcon:!0,message:e("settings.mcpTab.replaceWarning")}):null,pe?t.jsx(Ve,{type:"error",showIcon:!0,message:pe}):null,t.jsx(ai,{value:Q,onChange:m=>W(m.target.value),rows:14,placeholder:'{"mcpServers": { "filesystem": { "command": "...", "args": [], "env": {} } }}',spellCheck:!1})]})})]})},ta=1,li=365,sa=e=>Number.isFinite(e)?Math.min(li,Math.max(ta,Math.floor(e??30))):30,Ls=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]),r=Number(s[3]),i=new Date(Date.UTC(n,a-1,r));return i.getUTCFullYear()!==n||i.getUTCMonth()!==a-1||i.getUTCDate()!==r?null:i},Ht=e=>e.toISOString().slice(0,10),ci=(e,s)=>{const n=new Date(e.getTime());return n.setUTCDate(n.getUTCDate()+s),n},di=(e,s)=>{const n=s.getTime()-e.getTime(),a=Math.floor(n/864e5)+1;return sa(a)},tn=(e,s=new Date)=>{const n=sa(e.days),a=Ht(s),r=Ls(e.endDate)??Ls(a);if(!r)return{startDate:a,endDate:a,days:ta};const i=Ls(e.startDate);if(i){const p=r<i?i:r;return{startDate:Ht(i),endDate:Ht(p),days:di(i,p)}}const l=ci(r,-(n-1));return{startDate:Ht(l),endDate:Ht(r),days:n}},ui=15e3,gi=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,mi=(e={})=>{const{filters:s,autoRefreshMs:n=ui}=e,a=o.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]),r=o.useMemo(()=>tn({startDate:a.startDate,endDate:a.endDate,days:a.days}),[a.days,a.endDate,a.startDate]),[i,l]=o.useState(null),[p,c]=o.useState([]),[d,u]=o.useState([]),[j,f]=o.useState(!1),[S,w]=o.useState(!1),[g,M]=o.useState(null),_=o.useCallback(async D=>{D?f(!0):w(!0);try{const k={startDate:r.startDate,endDate:r.endDate,endpoint:a.endpoint,model:a.model,limit:a.limit},[A,te,z]=await Promise.all([Zt.getForwardSummary(k),Zt.getForwardByEndpoint(k),Zt.getForwardRequests(k)]);l(A),c(te),u(z),M(null)}catch(k){M(gi(k,"Failed to load forward metrics"))}finally{D?f(!1):w(!1)}},[a.endpoint,a.model,a.limit,r.endDate,r.startDate]),b=o.useCallback(async()=>{await _(!1)},[_]);return o.useEffect(()=>{_(!0)},[_]),o.useEffect(()=>{if(n<=0)return;const D=window.setInterval(()=>{_(!1)},n);return()=>{window.clearInterval(D)}},[n,_]),{summary:i,endpointMetrics:p,requests:d,isLoading:j,isRefreshing:S,error:g,refresh:b}},pi=15e3,wn=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,hi=(e={})=>{const{filters:s,autoRefreshMs:n=pi,service:a=Zt}=e,r=o.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]),i=o.useMemo(()=>tn({startDate:r.startDate,endDate:r.endDate,days:r.days}),[r.days,r.endDate,r.startDate]),[l,p]=o.useState(null),[c,d]=o.useState([]),[u,j]=o.useState([]),[f,S]=o.useState([]),[w,g]=o.useState(null),[M,_]=o.useState([]),[b,D]=o.useState(null),[k,A]=o.useState(!1),[te,z]=o.useState(!1),[U,Z]=o.useState(!1),[h,y]=o.useState(null),P=o.useCallback(async K=>{K?z(!0):Z(!0);try{const Q=a.getMemorySummary?a.getMemorySummary().catch(()=>null):Promise.resolve(null),W=a.getMemoryTimeline?a.getMemoryTimeline({days:i.days,endDate:i.endDate,granularity:r.granularity}).catch(()=>[]):Promise.resolve([]),[pe,he,De,C,G,X]=await Promise.all([a.getSummary({startDate:i.startDate,endDate:i.endDate}),a.getByModel({startDate:i.startDate,endDate:i.endDate}),a.getSessions({startDate:i.startDate,endDate:i.endDate,model:r.model,limit:r.sessionLimit}),a.getDaily({days:i.days,endDate:i.endDate,granularity:r.granularity}),Q,W]);p(pe),d(he),j(De),S(C),g(G),_(X),y(null)}catch(Q){y(wn(Q,"Failed to load metrics"))}finally{K?z(!1):Z(!1)}},[r.granularity,r.model,r.sessionLimit,i.days,i.endDate,i.startDate,a]),E=o.useCallback(async()=>{await P(!1)},[P]),I=o.useCallback(async K=>{A(!0);try{const Q=await a.getSessionDetail(K);D(Q)}catch(Q){y(wn(Q,"Failed to load session detail"))}finally{A(!1)}},[a]),O=o.useCallback(()=>{D(null)},[]);return o.useEffect(()=>{P(!0)},[P]),o.useEffect(()=>{if(n<=0)return;const K=window.setInterval(()=>{P(!1)},n);return()=>{window.clearInterval(K)}},[n,P]),{summary:l,modelMetrics:c,sessions:u,timeline:f,memorySummary:w,memoryTimeline:M,sessionDetail:b,isLoading:te,isRefreshing:U,isSessionDetailLoading:k,error:h,refresh:E,loadSessionDetail:I,clearSessionDetail:O}},fi=15e3,yi=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,xi=(e={})=>{const{filters:s,autoRefreshMs:n=fi}=e,a=o.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]),r=o.useMemo(()=>tn({startDate:a.startDate,endDate:a.endDate,days:a.days}),[a.days,a.endDate,a.startDate]),[i,l]=o.useState(null),[p,c]=o.useState(!1),[d,u]=o.useState(!1),[j,f]=o.useState(null),S=o.useCallback(async g=>{g?c(!0):u(!0);try{const M=await Zt.getUsageBreakdown({startDate:r.startDate,endDate:r.endDate,model:a.model});l(M),f(null)}catch(M){f(yi(M,"Failed to load usage breakdown"))}finally{g?c(!1):u(!1)}},[a.model,r.endDate,r.startDate]),w=o.useCallback(async()=>{await S(!1)},[S]);return o.useEffect(()=>{S(!0)},[S]),o.useEffect(()=>{if(n<=0)return;const g=window.setInterval(()=>{S(!1)},n);return()=>{window.clearInterval(g)}},[n,S]),{data:i,isLoading:p,isRefreshing:d,error:j,refresh:w}},{useToken:bi}=fe,vi=({data:e,loading:s})=>{const{t:n}=se(),{token:a}=bi();if(s)return t.jsx(R,{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(R,{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 r=e.map(i=>({endpoint:i.endpoint.split(".").pop()||i.endpoint,requests:i.requests,successful:i.successful,failed:i.failed}));return t.jsx(R,{size:"small",className:"lotus-metric-card",title:n("settings.charts.endpointDistribution"),children:t.jsx("div",{style:{width:"100%",height:240},children:t.jsx(zt,{children:t.jsxs(Qs,{data:r,children:[t.jsx(as,{strokeDasharray:"3 3"}),t.jsx(rs,{dataKey:"endpoint"}),t.jsx(is,{}),t.jsx(Lt,{formatter:(i,l)=>[`${i}`,l.charAt(0).toUpperCase()+l.slice(1)]}),t.jsx(en,{}),t.jsx(bs,{dataKey:"successful",fill:"var(--lotus-chart-secondary)",name:n("settings.common.successful"),fillOpacity:.9,radius:[4,4,0,0]}),t.jsx(bs,{dataKey:"failed",fill:"var(--lotus-chart-danger)",name:n("settings.common.failed"),fillOpacity:.9,radius:[4,4,0,0]})]})})})})},Os=e=>e.replace(/\.0$/,""),na=e=>e.toLocaleString(),aa=e=>Number.isFinite(e)?e.toLocaleString(void 0,{maximumFractionDigits:20}):String(e),sn=e=>{if(!Number.isFinite(e))return String(e);const s=Math.abs(e);if(s>=1e9){const n=s>=1e10?0:1;return`${Os((e/1e9).toFixed(n))}B`}if(s>=1e6){const n=s>=1e7?0:1;return`${Os((e/1e6).toFixed(n))}M`}if(s>=1e3){const n=s>=1e4?0:1;return`${Os((e/1e3).toFixed(n))}K`}return na(e)},Ti=e=>Number.isFinite(e)&&Math.abs(e)>=1e3,ra=e=>aa(e),ss=e=>{if(!Number.isFinite(e))return String(e);const s=sn(e);return Ti(e)?t.jsx(Se,{title:t.jsx("div",{children:aa(e)}),children:t.jsx("span",{children:s})}):s},ot=e=>{const s=Number(e??0);return Number.isFinite(s)?ss(s):e==null?"-":String(e)},{useToken:ji}=fe,Si=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),n=Math.floor(s/60),a=s%60;if(n>=60){const r=Math.floor(n/60),i=n%60;return`${r}h ${i}m`}return n>0?`${n}m ${a}s`:`${a}s`},Cn=({summary:e,loading:s})=>{const{t:n}=se(),{token:a}=ji();if(s)return t.jsx(ut,{active:!0,paragraph:{rows:1}});const r=e&&e.total_requests>0?(e.successful_requests/e.total_requests*100).toFixed(1):"0.0";return t.jsxs(Ge,{gutter:[a.marginSM,a.marginSM],children:[t.jsx(oe,{xs:24,sm:12,xl:6,children:t.jsx(R,{size:"small",className:"lotus-metric-card",children:t.jsx(_e,{title:n("settings.forwardMetricsCards.totalForwardRequests"),value:(e==null?void 0:e.total_requests)??0,precision:0,formatter:ot,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),t.jsx(oe,{xs:24,sm:12,xl:6,children:t.jsx(R,{size:"small",className:"lotus-metric-card",children:t.jsx(_e,{title:n("settings.forwardMetricsCards.successRate"),value:r,suffix:"%",valueStyle:{color:Number(r)>=95?"var(--lotus-chart-secondary)":Number(r)>=80?"var(--lotus-chart-accent)":"var(--lotus-chart-danger)"}})})}),t.jsx(oe,{xs:24,sm:12,xl:6,children:t.jsx(R,{size:"small",className:"lotus-metric-card",children:t.jsx(_e,{title:n("settings.forwardMetricsCards.forwardTokens"),value:(e==null?void 0:e.total_tokens.total_tokens)??0,precision:0,formatter:ot,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})}),t.jsx(oe,{xs:24,sm:12,xl:6,children:t.jsx(R,{size:"small",className:"lotus-metric-card",children:t.jsx(_e,{title:n("settings.forwardMetricsCards.avgResponseTime"),value:Si(e==null?void 0:e.avg_duration_ms),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:_t}=ce,_i=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`},ki=e=>new Date(e).toLocaleString(),wi=({requests:e,loading:s})=>{const{t:n}=se(),a=[{title:n("settings.metricsTable.forward.columns.id"),dataIndex:"forward_id",key:"forward_id",width:120,render:r=>t.jsxs(_t,{style:{fontSize:12},copyable:!0,children:[r.slice(0,8),"..."]})},{title:n("settings.metricsTable.forward.columns.endpoint"),dataIndex:"endpoint",key:"endpoint",width:150,render:r=>t.jsx(le,{color:"processing",children:r.split(".").pop()||r})},{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:r=>t.jsx(le,{color:r?"purple":"processing",children:n(r?"settings.metricsTable.forward.typeStream":"settings.metricsTable.forward.typeSync")})},{title:n("settings.metricsTable.forward.columns.status"),key:"status",width:100,render:(r,i)=>{const l=i.status==="success"?"success":i.status==="error"?"error":"default";return t.jsx(Va,{status:l,text:i.status_code?t.jsxs("span",{children:[i.status,t.jsxs(_t,{type:"secondary",style:{marginLeft:4},children:["(",i.status_code,")"]})]}):i.status||"-"})}},{title:n("settings.metricsTable.forward.columns.tokens"),key:"tokens",width:100,render:(r,i)=>i.token_usage?t.jsx(_t,{children:ss(i.token_usage.total_tokens)}):t.jsx(_t,{type:"secondary",children:"-"})},{title:n("settings.metricsTable.forward.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",width:100,render:r=>_i(r)},{title:n("settings.metricsTable.forward.columns.started"),dataIndex:"started_at",key:"started_at",width:160,render:r=>t.jsx(_t,{type:"secondary",style:{fontSize:12},children:ki(r)})},{title:n("settings.metricsTable.forward.columns.error"),dataIndex:"error",key:"error",width:200,render:r=>r?t.jsx(_t,{type:"danger",ellipsis:!0,style:{maxWidth:180},children:r}):t.jsx(_t,{type:"secondary",children:"-"})}];return t.jsx(dt,{rowKey:"forward_id",className:"lotus-metric-table",columns:a,dataSource:e,loading:s,size:"small",pagination:{pageSize:10,showSizeChanger:!0,showTotal:r=>n("settings.metricsTable.forward.totalRequests",{total:r}),pageSizeOptions:["10","20","50","100"]},scroll:{x:1200},locale:{emptyText:n("settings.metricsTable.forward.empty")}})},{useToken:Ci}=fe,Mi=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString()},Mn=({summary:e,loading:s})=>{const{t:n}=se(),{token:a}=Ci();return s?t.jsx(ut,{active:!0,paragraph:{rows:1}}):t.jsxs(Ge,{gutter:[a.marginSM,a.marginSM],children:[t.jsx(oe,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(R,{size:"small",className:"lotus-metric-card",children:t.jsx(_e,{title:n("settings.unifiedMetricsCards.totalMemories"),value:(e==null?void 0:e.total_memories)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),t.jsx(oe,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(R,{size:"small",className:"lotus-metric-card",children:t.jsx(_e,{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(oe,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(R,{size:"small",className:"lotus-metric-card",children:t.jsx(_e,{title:n("settings.unifiedMetricsCards.memoryProjects"),value:(e==null?void 0:e.project_count)??0,precision:0,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),t.jsx(oe,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(R,{size:"small",className:"lotus-metric-card",children:t.jsx(_e,{title:n("settings.unifiedMetricsCards.lastReindex"),value:Mi(e==null?void 0:e.last_reindex_at),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:Ei}=ce,Di=({data:e,loading:s})=>{const{t:n}=se();return s?t.jsx(R,{size:"small",className:"lotus-metric-card",title:n("settings.charts.memoryTrendTitle"),children:t.jsx(ut,{active:!0,paragraph:{rows:5}})}):t.jsx(R,{size:"small",className:"lotus-metric-card",title:n("settings.charts.memoryTrendTitle"),children:e.length===0?t.jsx(Ue,{image:Ue.PRESENTED_IMAGE_SIMPLE,description:n("settings.charts.noMemoryTrend")}):t.jsxs(t.Fragment,{children:[t.jsx(Ei,{type:"secondary",children:n("settings.charts.memoryTrendDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(zt,{children:t.jsxs(Qn,{data:e,children:[t.jsx(as,{strokeDasharray:"3 3"}),t.jsx(rs,{dataKey:"label",minTickGap:24}),t.jsx(is,{allowDecimals:!1}),t.jsx(Lt,{}),t.jsx(en,{}),t.jsx(Pt,{type:"monotone",dataKey:"total_memories",name:n("settings.charts.totalMemories"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),t.jsx(Pt,{type:"monotone",dataKey:"created_memories",name:n("settings.charts.createdMemories"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),t.jsx(Pt,{type:"monotone",dataKey:"updated_memories",name:n("settings.charts.updatedMemories"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{useToken:Pi}=fe,Ii=e=>{const s=Math.floor(e/1e3),n=Math.floor(s/60),a=s%60;return n>0?`${n}m ${a}s`:`${a}s`},Fi=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,r)=>a+(r.duration_ms??0),0);return Math.floor(n/s.length)},En=({summary:e,sessions:s,loading:n})=>{const{t:a}=se(),{token:r}=Pi();if(n)return t.jsx(ut,{active:!0,paragraph:{rows:1}});const i=Fi(s);return t.jsxs(Ge,{gutter:[r.marginSM,r.marginSM],children:[t.jsx(oe,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(R,{size:"small",className:"lotus-metric-card",children:t.jsx(_e,{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(oe,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(R,{size:"small",className:"lotus-metric-card",children:t.jsx(_e,{title:a("settings.metricsCards.totalSessions"),value:(e==null?void 0:e.total_sessions)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),t.jsx(oe,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(R,{size:"small",className:"lotus-metric-card",children:t.jsx(_e,{title:a("settings.metricsCards.chatTokens"),value:(e==null?void 0:e.total_tokens.total_tokens)??0,precision:0,formatter:ot,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})}),t.jsx(oe,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(R,{size:"small",className:"lotus-metric-card",children:t.jsx(_e,{title:a("settings.metricsCards.totalToolCalls"),value:(e==null?void 0:e.total_tool_calls)??0,precision:0,formatter:ot,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),t.jsx(oe,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(R,{size:"small",className:"lotus-metric-card",children:t.jsx(_e,{title:a("settings.metricsCards.tokensSaved",{defaultValue:"Saved Tokens"}),value:(e==null?void 0:e.total_tokens_saved)??0,precision:0,formatter:ot,valueStyle:{color:"var(--lotus-chart-cyan)"}})})}),t.jsx(oe,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(R,{size:"small",className:"lotus-metric-card",children:t.jsx(_e,{title:a("settings.metricsCards.toolContextSavedTokens",{defaultValue:"Tool Context Saved Tokens"}),value:(e==null?void 0:e.tool_context_tokens_saved)??0,precision:0,formatter:ot,valueStyle:{color:"var(--lotus-chart-accent)"}})})}),t.jsx(oe,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(R,{size:"small",className:"lotus-metric-card",children:t.jsx(_e,{title:a("settings.metricsCards.compressionEvents",{defaultValue:"Compression Events"}),value:(e==null?void 0:e.total_compression_events)??0,precision:0,formatter:ot,valueStyle:{color:"var(--lotus-chart-secondary)"}})})}),t.jsx(oe,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(R,{size:"small",className:"lotus-metric-card",children:t.jsx(_e,{title:a("settings.metricsCards.avgSessionDuration"),value:i>0?Ii(i):"-",valueStyle:{color:"var(--lotus-chart-accent)"}})})})]})},{Text:Ai}=ce,Dn=["var(--lotus-chart-primary)","var(--lotus-chart-secondary)","var(--lotus-chart-accent)","var(--lotus-chart-purple)","var(--lotus-chart-cyan)"],Ri=({data:e,loading:s})=>{const{t:n}=se();if(s)return t.jsx(R,{size:"small",className:"lotus-metric-card",title:n("settings.charts.modelDistribution"),children:t.jsx(ut,{active:!0,paragraph:{rows:5}})});const a=e.map(r=>({name:r.model,value:r.tokens.total_tokens}));return t.jsx(R,{size:"small",className:"lotus-metric-card",title:n("settings.charts.modelDistribution"),children:a.length===0?t.jsx(Ue,{image:Ue.PRESENTED_IMAGE_SIMPLE,description:n("settings.charts.noModelMetrics")}):t.jsxs(t.Fragment,{children:[t.jsx(Ai,{type:"secondary",children:n("settings.charts.modelDistributionDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(zt,{children:t.jsxs(Ya,{children:[t.jsx(Za,{data:a,cx:"50%",cy:"50%",outerRadius:90,fill:"var(--lotus-chart-primary)",dataKey:"value",nameKey:"name",label:!0,children:a.map((r,i)=>t.jsx(Qa,{fill:Dn[i%Dn.length]},`${r.name}-${i}`))}),t.jsx(Lt,{formatter:r=>ra(r)})]})})})]})})},zi=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?"-":s.toLocaleString()},Li=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),n=Math.floor(s/60),a=s%60;if(n>=60){const r=Math.floor(n/60),i=n%60;return`${r}h ${i}m`}return n>0?`${n}m ${a}s`:`${a}s`},Oi=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"}},Ni=(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}},Vi=({sessions:e,loading:s,onSelectSession:n})=>{const{t:a}=se(),r=[{title:a("settings.metricsTable.session.columns.session"),dataIndex:"session_id",key:"session_id",render:i=>t.jsx(Se,{title:i,children:t.jsxs("span",{children:[i.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:i=>t.jsx(le,{color:Oi(i),children:Ni(i,a)})},{title:a("settings.metricsTable.session.columns.started"),dataIndex:"started_at",key:"started_at",render:i=>zi(i),width:200,sorter:(i,l)=>new Date(i.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:i=>Li(i),width:120},{title:a("settings.metricsTable.session.columns.tokens"),key:"tokens",render:(i,l)=>ss(l.total_token_usage.total_tokens),width:120,sorter:(i,l)=>i.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:(i,l)=>i.tool_call_count-l.tool_call_count},{title:a("settings.metricsTable.session.columns.messages"),dataIndex:"message_count",key:"message_count",width:120,sorter:(i,l)=>i.message_count-l.message_count},{title:a("settings.metricsTable.session.columns.action"),key:"action",fixed:"right",width:120,render:(i,l)=>t.jsx(L,{type:"link",onClick:()=>{n(l.session_id)},children:a("settings.metricsTable.session.view")})}];return t.jsx(dt,{rowKey:"session_id",size:"small",className:"lotus-metric-table",columns:r,loading:s,dataSource:e,pagination:{pageSize:10,showSizeChanger:!1},scroll:{x:1100}})},{Text:$i}=ce,Pn={message_count:"Message Count",last_message_id:"Last Message",pending_question:"Pending Question"},Bi=e=>Pn[e]?Pn[e]:e.split("_").map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "),qi=({breakdown:e,loading:s})=>{const{t:n}=se();if(s)return t.jsx(R,{size:"small",className:"lotus-metric-card",title:n("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),children:t.jsx(ut,{active:!0,paragraph:{rows:5}})});const a=Object.entries(e??{}).map(([r,i])=>({reason:r,label:n(`settings.syncMismatchReasons.${r}`,{defaultValue:Bi(r)}),count:i})).sort((r,i)=>i.count-r.count);return t.jsx(R,{size:"small",className:"lotus-metric-card",title:n("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),extra:t.jsx($i,{type:"secondary",children:n("settings.metricsDashboard.syncMismatchBreakdownSubtitle",{defaultValue:"Grouped by execute sync mismatch reason"})}),children:a.length===0?t.jsx(Ue,{image:Ue.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(zt,{children:t.jsxs(Qs,{data:a,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[t.jsx(as,{strokeDasharray:"3 3"}),t.jsx(rs,{type:"number",allowDecimals:!1}),t.jsx(is,{dataKey:"label",type:"category",width:110}),t.jsx(Lt,{formatter:r=>[r.toLocaleString(),n("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})],labelFormatter:r=>n("settings.metricsDashboard.syncMismatchReasonLabel",{defaultValue:"Reason: {{label}}",label:r})}),t.jsx(bs,{dataKey:"count",fill:"var(--lotus-chart-danger)",radius:[0,6,6,0],name:n("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})})]})})})})},{Text:Ui}=ce,Hi=({data:e,loading:s})=>{const{t:n}=se();return s?t.jsx(R,{size:"small",className:"lotus-metric-card",title:n("settings.charts.tokenUsageOverTime"),children:t.jsx(ut,{active:!0,paragraph:{rows:5}})}):t.jsx(R,{size:"small",className:"lotus-metric-card",title:n("settings.charts.tokenUsageOverTime"),children:e.length===0?t.jsx(Ue,{image:Ue.PRESENTED_IMAGE_SIMPLE,description:n("settings.charts.noTokenUsage")}):t.jsxs(t.Fragment,{children:[t.jsx(Ui,{type:"secondary",children:n("settings.charts.tokenUsageDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(zt,{children:t.jsxs(Qn,{data:e,children:[t.jsx(as,{strokeDasharray:"3 3"}),t.jsx(rs,{dataKey:"label",minTickGap:24}),t.jsx(is,{allowDecimals:!1,tickFormatter:sn}),t.jsx(Lt,{formatter:a=>ra(a)}),t.jsx(en,{}),t.jsx(Pt,{type:"monotone",dataKey:"totalTokens",name:n("settings.charts.total"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),t.jsx(Pt,{type:"monotone",dataKey:"promptTokens",name:n("settings.charts.prompt"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),t.jsx(Pt,{type:"monotone",dataKey:"completionTokens",name:n("settings.charts.completion"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{Text:Ki}=ce,Kt=({title:e,subtitle:s,emptyText:n,color:a="var(--lotus-chart-primary)",data:r,loading:i,countLabel:l})=>{const{t:p}=se();return i?t.jsx(R,{size:"small",className:"lotus-metric-card",title:e,children:t.jsx(ut,{active:!0,paragraph:{rows:5}})}):t.jsx(R,{size:"small",className:"lotus-metric-card",title:e,children:r.length===0?t.jsx(Ue,{image:Ue.PRESENTED_IMAGE_SIMPLE,description:n}):t.jsxs(t.Fragment,{children:[s?t.jsx(Ki,{type:"secondary",children:s}):null,t.jsx("div",{style:{width:"100%",minWidth:0,height:280,marginTop:s?12:0},children:t.jsx(zt,{children:t.jsxs(Qs,{data:r,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[t.jsx(as,{strokeDasharray:"3 3"}),t.jsx(rs,{type:"number",allowDecimals:!1}),t.jsx(is,{dataKey:"label",type:"category",width:110}),t.jsx(Lt,{formatter:c=>[c.toLocaleString(),l??p("settings.metricsDashboard.calls",{defaultValue:"Calls"})],labelFormatter:(c,d)=>{var j,f;const u=(f=(j=d==null?void 0:d[0])==null?void 0:j.payload)==null?void 0:f.meta;return u?`${c} · ${u}`:String(c)}}),t.jsx(bs,{dataKey:"count",fill:a,radius:[0,6,6,0],name:l??p("settings.metricsDashboard.calls",{defaultValue:"Calls"})})]})})})]})})},{useToken:Wi}=fe,In=({summary:e,loading:s})=>{const{t:n}=se(),{token:a}=Wi();if(s)return t.jsx(ut,{active:!0,paragraph:{rows:1}});const r=[{key:"skill-load-calls",title:n("settings.metricsDashboard.skillsAndMcp.cards.skillLoadCalls",{defaultValue:"Skill Loads"}),value:(e==null?void 0:e.skill_load_calls)??0,color:"var(--lotus-chart-primary)"},{key:"unique-skills",title:n("settings.metricsDashboard.skillsAndMcp.cards.uniqueSkills",{defaultValue:"Unique Skills"}),value:(e==null?void 0:e.unique_skills)??0,color:"var(--lotus-chart-purple)"},{key:"mcp-calls",title:n("settings.metricsDashboard.skillsAndMcp.cards.mcpCalls",{defaultValue:"MCP Calls"}),value:(e==null?void 0:e.mcp_calls)??0,color:"var(--lotus-chart-accent)"},{key:"unique-mcp-servers",title:n("settings.metricsDashboard.skillsAndMcp.cards.uniqueMcpServers",{defaultValue:"MCP Servers"}),value:(e==null?void 0:e.unique_mcp_servers)??0,color:"var(--lotus-chart-cyan)"},{key:"unique-mcp-tools",title:n("settings.metricsDashboard.skillsAndMcp.cards.uniqueMcpTools",{defaultValue:"MCP Tools"}),value:(e==null?void 0:e.unique_mcp_tools)??0,color:"var(--lotus-chart-secondary)"},{key:"core-tool-calls",title:n("settings.metricsDashboard.skillsAndMcp.cards.coreToolCalls",{defaultValue:"Core Tool Calls"}),value:(e==null?void 0:e.core_tool_calls)??0,color:"var(--lotus-metric-text-strong)"}].filter(i=>i.value>0);return r.length===0?null:t.jsx(Ge,{gutter:[a.marginSM,a.marginSM],children:r.map(i=>t.jsx(oe,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(R,{size:"small",className:"lotus-metric-card",children:t.jsx(_e,{title:i.title,value:i.value,precision:0,formatter:ot,valueStyle:{color:i.color}})})},i.key))})},{Text:kt}=ce,{useToken:Gi}=fe,Fn=e=>"date"in e?e.date:e.label,Ji=(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)"},gs=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),n=Math.floor(s/60),a=s%60;if(n>=60){const r=Math.floor(n/60),i=n%60;return`${r}h ${i}m`}return n>0?`${n}m ${a}s`:`${a}s`},An=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString()},Ns=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}: ${na(a)}`).join(" • ")},Vs=(e,s=320)=>({width:"100%",display:"grid",gridTemplateColumns:`repeat(auto-fit, minmax(${s}px, 1fr))`,gap:e}),Xi=()=>{const{t:e}=se(),{token:s}=Gi(),n=ba(m=>m.themeMode)==="dark",[a,r]=o.useState(void 0),[i,l]=o.useState(void 0),[p,c]=o.useState(void 0),[d,u]=o.useState(30),[j,f]=o.useState("daily"),{summary:S,modelMetrics:w,sessions:g,timeline:M,memorySummary:_,memoryTimeline:b,sessionDetail:D,isLoading:k,isRefreshing:A,isSessionDetailLoading:te,error:z,refresh:U,loadSessionDetail:Z,clearSessionDetail:h}=hi({filters:{startDate:a,endDate:i,model:p,days:d,granularity:j}}),{summary:y,endpointMetrics:P,requests:E,isLoading:I,isRefreshing:O,error:K,refresh:Q}=mi({filters:{startDate:a,endDate:i,days:d,model:p}}),{data:W,isLoading:pe,isRefreshing:he,error:De,refresh:C}=xi({filters:{startDate:a,endDate:i,days:d,model:p}}),G=o.useMemo(()=>M.map(m=>({label:Fn(m),promptTokens:m.total_token_usage.prompt_tokens,completionTokens:m.total_token_usage.completion_tokens,totalTokens:m.total_token_usage.total_tokens})),[M]),X=o.useMemo(()=>w.map(m=>({label:m.model,value:m.model})),[w]),ee=o.useMemo(()=>{const m=M.map(me=>({label:Fn(me),sessions:me.total_sessions,tokens:me.total_token_usage.total_tokens})),re=m.reduce((me,Le)=>Math.max(me,Le.sessions),0);return{points:m,maxSessions:re}},[M]),Pe=o.useMemo(()=>{const m=E.map(me=>me.duration_ms).filter(me=>typeof me=="number"&&me>0).sort((me,Le)=>me-Le);if(m.length===0)return null;const re=Math.ceil(m.length*.95)-1;return m[Math.max(0,Math.min(re,m.length-1))]},[E]),Ie=o.useMemo(()=>[{title:e("settings.metricsDashboard.roundColumns.round"),dataIndex:"round_id",key:"round_id",render:m=>`${m.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:m=>gs(m)},{title:e("settings.metricsDashboard.roundColumns.tokens"),key:"tokens",render:(m,re)=>ss(re.token_usage.total_tokens)},{title:e("settings.metricsDashboard.roundColumns.toolCalls"),key:"tool_calls",render:(m,re)=>re.tool_calls.length}],[e]),$e=o.useMemo(()=>{const m=(S==null?void 0:S.total_sessions)??0,re=(S==null?void 0:S.total_tokens.total_tokens)??0,me=(S==null?void 0:S.total_tool_calls)??0,Le=(S==null?void 0:S.active_sessions)??0,ye=g.reduce((Nt,x)=>Nt+x.total_rounds,0),Oe=(S==null?void 0:S.total_tokens_saved)??0,cs=(S==null?void 0:S.tool_context_tokens_saved)??0,ks=(S==null?void 0:S.non_tool_compression_tokens_saved)??0,ws=(S==null?void 0:S.prompt_cached_tool_outputs)??0,Ot=(S==null?void 0:S.total_compression_events)??0,gt=(y==null?void 0:y.total_requests)??0,Cs=(y==null?void 0:y.total_tokens.total_tokens)??0,Ms=(y==null?void 0:y.failed_requests)??0,Es=E.filter(Nt=>Nt.is_stream).length,ds=m>0?Le/m*100:0,Ds=gt>0?Ms/gt*100:0,Ps=E.length>0?Es/E.length*100:0,xt=re>0?Number((Oe/re*100).toFixed(1)):0,Is=Oe>0?Number((cs/Oe*100).toFixed(1)):0;return[{title:e("settings.metricsDashboard.compactStats.avgTokensPerSession"),value:m>0?Math.round(re/m):0},{title:e("settings.metricsDashboard.compactStats.savedTokens",{defaultValue:"Saved Tokens"}),value:Oe},{title:e("settings.metricsDashboard.compactStats.toolContextSavedTokens",{defaultValue:"Tool Context Saved Tokens"}),value:cs},{title:e("settings.metricsDashboard.compactStats.nonToolCompressionSavedTokens",{defaultValue:"Non-Tool Compression Saved Tokens"}),value:ks},{title:e("settings.metricsDashboard.compactStats.savedTokenRatio",{defaultValue:"Saved / Chat Tokens"}),value:xt,suffix:"%"},{title:e("settings.metricsDashboard.compactStats.toolSavedShare",{defaultValue:"Tool Share of Saved Tokens"}),value:Is,suffix:"%"},{title:e("settings.metricsDashboard.compactStats.promptCachedToolOutputs",{defaultValue:"Prompt-Cached Tool Outputs"}),value:ws},{title:e("settings.metricsDashboard.compactStats.compressionEvents",{defaultValue:"Compression Events"}),value:Ot},{title:e("settings.metricsDashboard.compactStats.avgRoundsPerSession"),value:m>0?Number((ye/m).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.toolCallsPerSession"),value:m>0?Number((me/m).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.activeSessionRate"),value:Number(ds.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.avgTokensPerForward"),value:gt>0?Math.round(Cs/gt):0},{title:e("settings.metricsDashboard.compactStats.forwardErrorRate"),value:Number(Ds.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.streamingRatio"),value:Number(Ps.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.p95ForwardLatency"),value:gs(Pe)},{title:e("settings.metricsDashboard.compactStats.modelCoverage"),value:w.length},{title:e("settings.metricsDashboard.compactStats.endpointCoverage"),value:P.length}]},[P.length,E,y,w.length,Pe,g,S,e]),Xe=o.useMemo(()=>{const m=(y==null?void 0:y.total_requests)??0,re=(y==null?void 0:y.failed_requests)??0,me=E.filter(Oe=>Oe.is_stream).length,Le=E.length>0?me/E.length*100:0,ye=m>0?re/m*100:0;return[{title:e("settings.metricsDashboard.forward.performance.p95Latency",{defaultValue:"P95 Latency"}),value:gs(Pe)},{title:e("settings.metricsDashboard.forward.performance.errorRate",{defaultValue:"Error Rate"}),value:Number(ye.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.streamingRatio",{defaultValue:"Streaming Ratio"}),value:Number(Le.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.endpointCoverage",{defaultValue:"Endpoint Coverage"}),value:P.length}]},[P.length,E,y,Pe,e]),V=o.useMemo(()=>W?[{label:e("settings.metricsDashboard.skillsAndMcp.mix.coreTools",{defaultValue:"Core Tools"}),count:W.core_tool_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.skillLoads",{defaultValue:"Skill Loads"}),count:W.skill_load_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.mcpCalls",{defaultValue:"MCP Calls"}),count:W.mcp_calls}].filter(m=>m.count>0):[],[e,W]),ve=o.useMemo(()=>((W==null?void 0:W.top_skills)??[]).map(m=>({label:m.skill_id,count:m.count})),[W]),He=o.useMemo(()=>((W==null?void 0:W.top_mcp_servers)??[]).map(m=>({label:m.server_id,count:m.count,meta:e("settings.metricsDashboard.skillsAndMcp.meta.uniqueTools",{defaultValue:"{{count}} tools",count:m.unique_tools})})),[e,W]),Ce=o.useMemo(()=>((W==null?void 0:W.top_mcp_tools)??[]).map(m=>({label:m.tool_name,count:m.count,meta:m.server_id})),[W]),ze=o.useMemo(()=>((W==null?void 0:W.top_core_tools)??[]).map(m=>({label:m.name,count:m.count})),[W]),ke=D==null?void 0:D.session,Ke=A||O||he;return t.jsxs(F,{direction:"vertical",size:s.marginMD,style:{width:"100%"},children:[z?t.jsx(Ve,{type:"error",showIcon:!0,message:z}):null,K?t.jsx(Ve,{type:"error",showIcon:!0,message:K}):null,De?t.jsx(Ve,{type:"error",showIcon:!0,message:De}):null,t.jsx(R,{size:"small",title:e("settings.metricsDashboard.filtersTitle"),extra:t.jsx(L,{icon:t.jsx(Rt,{}),loading:Ke,onClick:()=>{U(),Q(),C()},children:e("settings.metricsDashboard.refresh")}),children:t.jsxs(F,{wrap:!0,children:[t.jsx(hn,{placeholder:e("settings.metricsDashboard.startDate"),onChange:m=>{r(m?m.format("YYYY-MM-DD"):void 0)}}),t.jsx(hn,{placeholder:e("settings.metricsDashboard.endDate"),onChange:m=>{l(m?m.format("YYYY-MM-DD"):void 0)}}),t.jsx(Y,{allowClear:!0,style:{minWidth:180},placeholder:e("settings.metricsDashboard.model"),value:p,options:X,onChange:m=>{c(m)}}),t.jsx(Y,{style:{width:120},value:d,options:[7,14,30,90].map(m=>({label:e("settings.metricsDashboard.daysOption",{value:m}),value:m})),onChange:m=>{u(m)}}),t.jsx(Y,{style:{width:140},value:j,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:m=>{f(m)}})]})}),t.jsx(R,{size:"small",title:e("settings.metricsDashboard.dashboardTitle"),children:t.jsx(xs,{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(R,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.overviewSections.scaleTitle",{defaultValue:"Scale & Activity"}),extra:t.jsx(kt,{type:"secondary",children:e("settings.metricsDashboard.overviewSections.scaleSubtitle",{defaultValue:"Current usage volume across chat, forward, skills, and memory."})}),children:t.jsxs(F,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(En,{summary:S,sessions:g,loading:k}),t.jsx(Cn,{summary:y,loading:I}),t.jsx(In,{summary:W,loading:pe}),t.jsx(Mn,{summary:_,loading:k})]})}),t.jsxs(R,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.overviewSections.efficiencyTitle",{defaultValue:"Compression & Efficiency Advantage"}),extra:t.jsx(kt,{type:"secondary",children:e("settings.metricsDashboard.overviewSections.efficiencySubtitle",{defaultValue:"Real savings from context compression, especially around tool-heavy workflows."})}),children:[t.jsx(Ge,{gutter:[s.marginSM,s.marginSM],children:$e.map(m=>t.jsx(oe,{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(_e,{title:m.title,value:m.value,suffix:m.suffix,formatter:typeof m.value=="number"?ot:void 0,valueStyle:{fontSize:s.fontSizeHeading4}})})},m.title))}),t.jsx(kt,{type:"secondary",style:{display:"block",marginTop:s.marginXS},children:e("settings.metricsDashboard.efficiencyHint",{defaultValue:"这些指标优先使用真实运行统计:总节约 Tokens、工具上下文压缩节约、非工具压缩节约、压缩事件数,以及会话 / Forward 的平均负载与质量指标。"})})]})]})},{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(En,{summary:S,sessions:g,loading:k}),t.jsxs("div",{style:Vs(s.marginSM,360),children:[t.jsx(Hi,{data:G,loading:k}),t.jsx(Ri,{data:w,loading:k})]}),t.jsxs("div",{style:Vs(s.marginSM,360),children:[t.jsx(qi,{breakdown:S==null?void 0:S.sync_mismatch_breakdown,loading:k}),t.jsx(R,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.activityHeatmapTitle"),children:ee.points.length===0?t.jsx(kt,{type:"secondary",children:e("settings.metricsDashboard.noActivity")}):t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(72px, 1fr))",gap:s.marginXS},children:ee.points.map(m=>t.jsxs("div",{style:{borderRadius:s.borderRadiusSM,padding:s.paddingXS,background:Ji(m.sessions,ee.maxSessions),minHeight:64,color:m.sessions>0?"var(--lotus-metric-text-strong)":s.colorTextSecondary},children:[t.jsx("div",{style:{fontSize:12,lineHeight:1.2},children:m.label}),t.jsx("div",{style:{fontWeight:600,marginTop:4},children:e("settings.metricsDashboard.sessionsCount",{count:m.sessions})}),t.jsx("div",{style:{fontSize:12},children:e("settings.metricsDashboard.tokensAmount",{value:sn(m.tokens)})})]},m.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(In,{summary:W,loading:pe}),t.jsxs("div",{style:Vs(s.marginSM,360),children:[t.jsx(Kt,{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:V,loading:pe,color:"var(--lotus-chart-primary)"}),t.jsx(Kt,{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:ve,loading:pe,color:"var(--lotus-chart-purple)"}),t.jsx(Kt,{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:He,loading:pe,color:"var(--lotus-chart-cyan)"}),t.jsx(Kt,{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:Ce,loading:pe,color:"var(--lotus-chart-accent)"}),t.jsx(Kt,{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:ze,loading:pe,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(Cn,{summary:y,loading:I}),t.jsx(R,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.forward.performanceTitle",{defaultValue:"Forward Performance"}),children:t.jsx(Ge,{gutter:[s.marginSM,s.marginSM],children:Xe.map(m=>t.jsx(oe,{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(_e,{title:m.title,value:m.value,suffix:m.suffix,valueStyle:{fontSize:s.fontSizeHeading4}})})},m.title))})}),t.jsx(vi,{data:P,loading:I})]})},{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(Mn,{summary:_,loading:k}),t.jsx(Di,{data:b,loading:k}),t.jsx(R,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.memory.breakdownTitle",{defaultValue:"Memory Breakdown"}),children:t.jsxs(Ae,{size:"small",bordered:!0,column:1,children:[t.jsx(Ae.Item,{label:e("settings.metricsDashboard.memory.byType",{defaultValue:"By Type"}),children:Ns(_==null?void 0:_.by_type)}),t.jsx(Ae.Item,{label:e("settings.metricsDashboard.memory.byStatus",{defaultValue:"By Status"}),children:Ns(_==null?void 0:_.by_status)}),t.jsx(Ae.Item,{label:e("settings.metricsDashboard.memory.byScope",{defaultValue:"By Scope"}),children:Ns(_==null?void 0:_.by_scope)}),t.jsx(Ae.Item,{label:e("settings.metricsDashboard.memory.lastDream",{defaultValue:"Last Dream"}),children:An(_==null?void 0:_.last_dream_at)}),t.jsx(Ae.Item,{label:e("settings.metricsDashboard.memory.lastReindex",{defaultValue:"Last Reindex"}),children:An(_==null?void 0:_.last_reindex_at)})]})})]})},{key:"records",label:e("settings.metricsDashboard.tabs.records"),children:t.jsx(xs,{size:"small",destroyInactiveTabPane:!0,items:[{key:"sessions",label:e("settings.metricsDashboard.sessionsTabLabel",{count:g.length}),children:t.jsx(R,{size:"small",extra:t.jsx(kt,{type:"secondary",children:e("settings.metricsDashboard.sessionsHint")}),children:t.jsx(Vi,{sessions:g,loading:k,onSelectSession:m=>{Z(m)}})})},{key:"forward-requests",label:e("settings.metricsDashboard.forwardTabLabel",{count:E.length}),children:t.jsx(R,{size:"small",children:t.jsx(wi,{requests:E,loading:I})})}]})}]})}),t.jsx(ct,{title:e("settings.metricsDashboard.sessionMetricsTitle"),open:!!D,onCancel:h,onOk:h,width:960,destroyOnClose:!0,children:te?t.jsx(kt,{children:e("settings.metricsDashboard.loadingSessionDetails")}):ke?t.jsxs(F,{direction:"vertical",style:{width:"100%"},size:s.marginMD,children:[t.jsxs(Ae,{size:"small",bordered:!0,column:2,children:[t.jsx(Ae.Item,{label:e("settings.metricsDashboard.sessionDetail.sessionId"),span:2,children:ke.session_id}),t.jsx(Ae.Item,{label:e("settings.metricsDashboard.sessionDetail.model"),children:ke.model}),t.jsx(Ae.Item,{label:e("settings.metricsDashboard.sessionDetail.status"),children:ke.status}),t.jsx(Ae.Item,{label:e("settings.metricsDashboard.sessionDetail.duration"),children:gs(ke.duration_ms)}),t.jsx(Ae.Item,{label:e("settings.metricsDashboard.sessionDetail.messages"),children:ke.message_count}),t.jsx(Ae.Item,{label:e("settings.metricsDashboard.sessionDetail.totalTokens"),children:ss(ke.total_token_usage.total_tokens)}),t.jsx(Ae.Item,{label:e("settings.metricsDashboard.sessionDetail.toolCalls"),children:ke.tool_call_count})]}),t.jsx(dt,{rowKey:"round_id",size:"small",columns:Ie,dataSource:D.rounds,pagination:{pageSize:6,showSizeChanger:!1}})]}):t.jsx(kt,{type:"secondary",children:e("settings.metricsDashboard.noDetail")})})]})},{Text:ms}=ce,{useToken:Yi}=fe,Zi=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"},Qi=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},eo=()=>{const{t:e}=se(),{token:s}=Yi(),[n,a]=At.useMessage(),[r,i]=o.useState(!1),[l,p]=o.useState(!0),[c,d]=o.useState("placeholder"),u=o.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]),j=o.useCallback(async()=>{i(!0);try{const g=await Ee.getBambooConfig();p(Qi(g)),d(Zi(g))}catch(g){n.error(g instanceof Error?g.message:e("settings.hooksTab.loadFailed"))}finally{i(!1)}},[n,e]),f=o.useCallback(async(g,M)=>{await Ee.setBambooConfig({hooks:{image_fallback:{enabled:g,mode:M}}})},[]),S=o.useCallback(async g=>{i(!0);try{await f(g,c),n.success(e(g?"settings.hooksTab.enabled":"settings.hooksTab.disabled")),await j()}catch(M){n.error(M instanceof Error?M.message:e("settings.hooksTab.updateFailed"))}finally{i(!1)}},[j,c,n,f,e]),w=o.useCallback(async g=>{var M;i(!0);try{await f(l,g),n.success(e("settings.hooksTab.modeUpdated",{mode:((M=u.find(_=>_.value===g))==null?void 0:M.label)??g})),await j()}catch(_){n.error(_ instanceof Error?_.message:e("settings.hooksTab.modeUpdateFailed"))}finally{i(!1)}},[l,j,u,n,f,e]);return o.useEffect(()=>{j()},[j]),t.jsxs(H,{vertical:!0,gap:s.marginLG,children:[a,t.jsx(R,{size:"small",loading:r,children:t.jsxs(H,{vertical:!0,gap:s.marginXS,children:[t.jsx(ms,{strong:!0,children:e("settings.hooksTab.title")}),t.jsxs(H,{align:"center",justify:"space-between",children:[t.jsx(ms,{children:e("settings.hooksTab.enableImagePreflight")}),t.jsx(ge,{checked:l,onChange:S})]}),t.jsxs(H,{align:"center",justify:"space-between",children:[t.jsx(ms,{children:e("settings.hooksTab.modeLabel")}),t.jsx(Y,{style:{width:180},value:c,options:u,onChange:w,disabled:!l})]}),t.jsx(ms,{type:"secondary",style:{fontSize:s.fontSizeSM},children:e("settings.hooksTab.description")})]})})]})},{Text:Me}=ce,nt=Ys.getInstance();function to(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 so=[{label:ne.t("settings.schedulesTab.weekdays.mon"),value:"mon"},{label:ne.t("settings.schedulesTab.weekdays.tue"),value:"tue"},{label:ne.t("settings.schedulesTab.weekdays.wed"),value:"wed"},{label:ne.t("settings.schedulesTab.weekdays.thu"),value:"thu"},{label:ne.t("settings.schedulesTab.weekdays.fri"),value:"fri"},{label:ne.t("settings.schedulesTab.weekdays.sat"),value:"sat"},{label:ne.t("settings.schedulesTab.weekdays.sun"),value:"sun"}];function we(e){return String(e??"").trim()||void 0}function no(e){return(e==null?void 0:e.type)==="interval"?e.every_seconds:null}function ia(e){return{type:"interval",every_seconds:e}}function ao(e){switch(e.type){case"interval":return ne.t("settings.schedulesTab.triggerLabels.interval",{type:ne.t("settings.schedulesTab.triggerTypes.interval"),seconds:e.every_seconds});case"daily":return ne.t("settings.schedulesTab.triggerLabels.daily",{type:ne.t("settings.schedulesTab.triggerTypes.daily"),time:`${String(e.hour).padStart(2,"0")}:${String(e.minute).padStart(2,"0")}`});case"weekly":return ne.t("settings.schedulesTab.triggerLabels.weekly",{type:ne.t("settings.schedulesTab.triggerTypes.weekly"),weekdays:e.weekdays.join(", ")});case"monthly":return ne.t("settings.schedulesTab.triggerLabels.monthly",{type:ne.t("settings.schedulesTab.triggerTypes.monthly"),days:e.days.join(", ")});case"cron":return ne.t("settings.schedulesTab.triggerLabels.cron",{type:ne.t("settings.schedulesTab.triggerTypes.cron"),expr:e.expr})}}function ro(e){switch(e==null?void 0:e.type){case"skip":return ne.t("settings.schedulesTab.misfirePolicyOptions.skip");case"catch_up_all":return ne.t("settings.schedulesTab.misfirePolicyOptions.catchUpAll");case"catch_up_window":return ne.t("settings.schedulesTab.misfirePolicyOptions.catchUpWindow");case"run_once":default:return ne.t("settings.schedulesTab.misfirePolicyOptions.runOnce")}}function io(e){switch(e){case"allow":return ne.t("settings.schedulesTab.overlapPolicyOptions.allow");case"skip":return ne.t("settings.schedulesTab.overlapPolicyOptions.skip");case"queue_one":default:return ne.t("settings.schedulesTab.overlapPolicyOptions.queueOne")}}function oo(e){var s;return(s=e.state)!=null&&s.next_fire_at?String(e.state.next_fire_at):"-"}function lo(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 co(e){var s,n,a,r;return((s=e.state)==null?void 0:s.running_run_count)>0?{color:"processing",label:ne.t("settings.schedulesTab.statusLabels.running"),detail:ne.t("settings.schedulesTab.statusDetails.active",{count:e.state.running_run_count})}:(((n=e.state)==null?void 0:n.queued_run_count)||0)>0?{color:"gold",label:ne.t("settings.schedulesTab.statusLabels.queued"),detail:ne.t("settings.schedulesTab.statusDetails.pending",{count:e.state.queued_run_count})}:(((a=e.state)==null?void 0:a.consecutive_failures)||0)>0?{color:"error",label:ne.t("settings.schedulesTab.statusLabels.failing"),detail:ne.t("settings.schedulesTab.statusDetails.consecutiveFailures",{count:e.state.consecutive_failures})}:e.enabled?(r=e.state)!=null&&r.last_success_at?{color:"success",label:ne.t("settings.schedulesTab.statusLabels.healthy"),detail:ne.t("settings.schedulesTab.statusDetails.lastRunSucceeded")}:{color:"default",label:ne.t("settings.schedulesTab.statusLabels.idle")}:{color:"default",label:ne.t("settings.schedulesTab.statusLabels.disabled")}}function uo(e){const s=we(e);if(!s)return{days:[],invalid:!1};const a=s.split(/[\s,]+/).filter(Boolean).map(l=>Number(l)),r=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:r}}function Rn(e){switch(e.trigger_type){case"interval":{const s=Number(e.interval_seconds||0);return s<=0?{errorKey:"settings.schedulesTab.validation.intervalRequired"}:{trigger:ia(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}=uo(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,r=e.monthly_minute;return a==null||r==null?{errorKey:"settings.schedulesTab.validation.triggerRequired"}:{trigger:{type:"monthly",days:s,hour:a,minute:r,second:0}}}case"cron":{const s=we(e.cron_expr);return s?{trigger:{type:"cron",expr:s}}:{errorKey:"settings.schedulesTab.validation.cronRequired"}}default:return{errorKey:"settings.schedulesTab.validation.triggerRequired"}}}function zn(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 go(e){var n,a,r,i,l,p,c,d;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:((r=e.run_config)==null?void 0:r.task_message)||"",model:((i=e.run_config)==null?void 0:i.model)||"",workspace_path:((l=e.run_config)==null?void 0:l.workspace_path)||"",enhance_prompt:((p=e.run_config)==null?void 0:p.enhance_prompt)||"",auto_execute:!!((c=e.run_config)!=null&&c.auto_execute)};switch(((d=e.misfire_policy)==null?void 0:d.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 mo(){const{t:e}=se(),[s,n]=At.useMessage(),[a,r]=o.useState(!1),[i,l]=o.useState([]),[p,c]=o.useState({open:!1,scheduleId:null,sessions:[],loading:!1}),[d,u]=o.useState({open:!1,scheduleId:null,runs:[],loading:!1}),[j,f]=o.useState({open:!1,schedule:null,saving:!1}),S=Ks(h=>h.close),[w]=v.useForm(),[g]=v.useForm(),M=v.useWatch("trigger_type",w),_=v.useWatch("misfire_policy",w),b=v.useWatch("trigger_type",g),D=v.useWatch("misfire_policy",g),k=o.useCallback(async()=>{r(!0);try{const h=await nt.listSchedules();l(h.schedules||[])}catch(h){console.error("[Schedules] Failed to load schedules:",h),s.error(e("settings.schedulesTab.loadFailed"))}finally{r(!1)}},[s,e]);o.useEffect(()=>{k()},[k]);const A=[{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")}],te=[{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")}],z=[{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")}],U=(h,y)=>t.jsxs(t.Fragment,{children:[t.jsxs(H,{gap:12,wrap:"wrap",children:[t.jsx(v.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(B,{})}),t.jsx(v.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(Y,{options:A})}),t.jsx(v.Item,{label:e("settings.schedulesTab.form.enabled"),name:"enabled",valuePropName:"checked",style:{width:120},children:t.jsx(ge,{})})]}),h==="interval"?t.jsx(v.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(be,{min:1,style:{width:"100%"}})}):null,h==="daily"?t.jsxs(H,{gap:12,wrap:"wrap",children:[t.jsx(v.Item,{label:e("settings.schedulesTab.form.dailyHour"),name:"daily_hour",style:{width:180},children:t.jsx(be,{min:0,max:23,style:{width:"100%"}})}),t.jsx(v.Item,{label:e("settings.schedulesTab.form.dailyMinute"),name:"daily_minute",style:{width:180},children:t.jsx(be,{min:0,max:59,style:{width:"100%"}})})]}):null,h==="weekly"?t.jsxs(t.Fragment,{children:[t.jsx(v.Item,{label:e("settings.schedulesTab.form.weeklyWeekdays"),name:"weekly_weekdays",style:{minWidth:320},children:t.jsx(Y,{mode:"multiple",options:so})}),t.jsxs(H,{gap:12,wrap:"wrap",children:[t.jsx(v.Item,{label:e("settings.schedulesTab.form.dailyHour"),name:"weekly_hour",style:{width:180},children:t.jsx(be,{min:0,max:23,style:{width:"100%"}})}),t.jsx(v.Item,{label:e("settings.schedulesTab.form.dailyMinute"),name:"weekly_minute",style:{width:180},children:t.jsx(be,{min:0,max:59,style:{width:"100%"}})})]})]}):null,h==="monthly"?t.jsxs(t.Fragment,{children:[t.jsx(v.Item,{label:e("settings.schedulesTab.form.monthlyDays"),name:"monthly_days",style:{minWidth:320},children:t.jsx(B,{placeholder:e("settings.schedulesTab.form.monthlyDaysPlaceholder")})}),t.jsxs(H,{gap:12,wrap:"wrap",children:[t.jsx(v.Item,{label:e("settings.schedulesTab.form.dailyHour"),name:"monthly_hour",style:{width:180},children:t.jsx(be,{min:0,max:23,style:{width:"100%"}})}),t.jsx(v.Item,{label:e("settings.schedulesTab.form.dailyMinute"),name:"monthly_minute",style:{width:180},children:t.jsx(be,{min:0,max:59,style:{width:"100%"}})})]})]}):null,h==="cron"?t.jsx(v.Item,{label:e("settings.schedulesTab.form.cronExpr"),name:"cron_expr",children:t.jsx(B,{placeholder:e("settings.schedulesTab.form.cronExprPlaceholder")})}):null,t.jsxs(H,{gap:12,wrap:"wrap",children:[t.jsx(v.Item,{label:e("settings.schedulesTab.form.timezone"),name:"timezone",style:{flex:"1 1 240px"},children:t.jsx(B,{placeholder:e("settings.schedulesTab.form.timezonePlaceholder")})}),t.jsx(v.Item,{label:e("settings.schedulesTab.form.startAt"),name:"start_at",style:{flex:"1 1 240px"},children:t.jsx(B,{placeholder:e("settings.schedulesTab.form.datetimePlaceholder")})}),t.jsx(v.Item,{label:e("settings.schedulesTab.form.endAt"),name:"end_at",style:{flex:"1 1 240px"},children:t.jsx(B,{placeholder:e("settings.schedulesTab.form.datetimePlaceholder")})})]}),t.jsxs(H,{gap:12,wrap:"wrap",children:[t.jsx(v.Item,{label:e("settings.schedulesTab.form.misfirePolicy"),name:"misfire_policy",style:{flex:"1 1 240px"},children:t.jsx(Y,{options:te})}),t.jsx(v.Item,{label:e("settings.schedulesTab.form.overlapPolicy"),name:"overlap_policy",style:{flex:"1 1 240px"},children:t.jsx(Y,{options:z})})]}),y==="catch_up_window"?t.jsxs(H,{gap:12,wrap:"wrap",children:[t.jsx(v.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxRuns"),name:"catch_up_window_max_runs",style:{width:220},children:t.jsx(be,{min:1,style:{width:"100%"}})}),t.jsx(v.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxLatenessSeconds"),name:"catch_up_window_max_lateness_seconds",style:{width:260},children:t.jsx(be,{min:1,style:{width:"100%"}})})]}):null,t.jsx(v.Item,{label:e("settings.schedulesTab.form.taskMessage"),name:"task_message",children:t.jsx(B.TextArea,{rows:3,placeholder:e("settings.schedulesTab.form.taskMessagePlaceholder")})}),t.jsx(v.Item,{label:e("settings.schedulesTab.form.systemPrompt"),name:"system_prompt",children:t.jsx(B.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})}),t.jsxs(H,{gap:12,wrap:"wrap",children:[t.jsx(v.Item,{label:e("settings.schedulesTab.form.model"),name:"model",style:{flex:"1 1 240px"},children:t.jsx(B,{placeholder:e("settings.schedulesTab.form.modelPlaceholder")})}),t.jsx(v.Item,{label:e("settings.schedulesTab.form.workspacePath"),name:"workspace_path",style:{flex:"1 1 320px"},children:t.jsx(B,{placeholder:e("settings.schedulesTab.optional")})}),t.jsx(v.Item,{label:e("settings.schedulesTab.form.autoExecute"),name:"auto_execute",valuePropName:"checked",style:{width:160},children:t.jsx(ge,{})})]}),t.jsx(v.Item,{label:e("settings.schedulesTab.form.enhancePrompt"),name:"enhance_prompt",children:t.jsx(B.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})})]}),Z=o.useMemo(()=>[{title:e("settings.schedulesTab.columns.name"),key:"name",render:(h,y)=>t.jsxs(H,{vertical:!0,gap:6,children:[t.jsx(Me,{strong:!0,children:y.name}),t.jsxs(H,{gap:6,wrap:"wrap",children:[t.jsx(le,{children:ao(y.trigger)}),y.timezone?t.jsx(le,{color:"blue",children:y.timezone}):null,t.jsx(le,{children:ro(y.misfire_policy)}),t.jsx(le,{children:io(y.overlap_policy)})]})]})},{title:e("settings.schedulesTab.columns.status"),key:"status",render:(h,y)=>{const P=co(y);return t.jsxs(H,{vertical:!0,gap:4,children:[t.jsx(le,{color:P.color,children:P.label}),P.detail?t.jsx(Me,{type:"secondary",children:P.detail}):null]})}},{title:e("settings.schedulesTab.columns.activity"),key:"activity",render:(h,y)=>{var P,E,I,O;return t.jsxs(H,{vertical:!0,gap:2,children:[t.jsx(Me,{type:"secondary",children:e("settings.schedulesTab.activityLabels.queued",{count:((P=y.state)==null?void 0:P.queued_run_count)??0})}),t.jsx(Me,{type:"secondary",children:e("settings.schedulesTab.activityLabels.running",{count:((E=y.state)==null?void 0:E.running_run_count)??0})}),t.jsx(Me,{type:"secondary",children:e("settings.schedulesTab.activityLabels.ok",{count:((I=y.state)==null?void 0:I.total_success_count)??0})}),t.jsx(Me,{type:"secondary",children:e("settings.schedulesTab.activityLabels.fail",{count:((O=y.state)==null?void 0:O.total_failure_count)??0})})]})}},{title:e("settings.schedulesTab.columns.nextRun"),key:"next_run_at",render:(h,y)=>t.jsx(Me,{type:"secondary",children:oo(y)})},{title:e("settings.schedulesTab.columns.lastRun"),key:"last_run_at",render:(h,y)=>t.jsx(Me,{type:"secondary",children:lo(y)})},{title:e("settings.schedulesTab.columns.autoExecute"),key:"auto_execute",render:(h,y)=>{var P,E;return t.jsx(Me,{type:(P=y.run_config)!=null&&P.auto_execute?void 0:"secondary",children:(E=y.run_config)!=null&&E.auto_execute?e("settings.schedulesTab.yes"):e("settings.schedulesTab.no")})}},{title:e("settings.schedulesTab.columns.model"),key:"model",render:(h,y)=>{var P;return t.jsx(Me,{type:"secondary",children:(P=y.run_config)!=null&&P.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 P=>{try{await nt.patchSchedule(y.id,{enabled:P}),await k()}catch(E){console.error("[Schedules] Failed to toggle:",E),s.error(e("settings.schedulesTab.updateFailed"))}}})},{title:e("settings.schedulesTab.columns.actions"),key:"actions",render:(h,y)=>{const P=t.jsx(be,{min:1,value:no(y.trigger)??void 0,disabled:y.trigger.type!=="interval",onChange:async E=>{const I=typeof E=="number"?E:null;if(!(!I||I<=0))try{await nt.patchSchedule(y.id,{trigger:ia(I)}),await k()}catch(O){console.error("[Schedules] Failed to patch interval:",O),s.error(e("settings.schedulesTab.updateFailed"))}}});return t.jsxs(H,{vertical:!0,gap:8,children:[t.jsxs(H,{gap:8,wrap:"wrap",children:[t.jsx(L,{size:"small",onClick:()=>{f({open:!0,schedule:y,saving:!1}),g.setFieldsValue(go(y))},children:e("settings.schedulesTab.actions.edit")}),t.jsx(L,{size:"small",onClick:async()=>{try{await nt.runScheduleNow(y.id),s.success(e("settings.schedulesTab.enqueuedRun")),await k()}catch(E){console.error("[Schedules] Failed to run now:",E),s.error(e("settings.schedulesTab.runNowFailed"))}},children:e("settings.schedulesTab.actions.runNow")}),t.jsx(L,{size:"small",onClick:async()=>{c(E=>({...E,open:!0,scheduleId:y.id,loading:!0,sessions:[]}));try{const E=await nt.listScheduleSessions(y.id);c(I=>({...I,open:!0,scheduleId:y.id,loading:!1,sessions:(E.sessions||[]).map(O=>({id:O.id,title:O.title,updated_at:O.updated_at}))}))}catch(E){console.error("[Schedules] Failed to list sessions:",E),s.error(e("settings.schedulesTab.loadSessionsFailed")),c(I=>({...I,loading:!1}))}},children:e("settings.schedulesTab.actions.sessions")}),t.jsx(L,{size:"small",onClick:async()=>{u(E=>({...E,open:!0,scheduleId:y.id,loading:!0,runs:[]}));try{const E=await nt.listScheduleRuns(y.id);u(I=>({...I,open:!0,scheduleId:y.id,loading:!1,runs:E.runs||[]}))}catch(E){console.error("[Schedules] Failed to list runs:",E),s.error(e("settings.schedulesTab.loadRunsFailed")),u(I=>({...I,loading:!1}))}},children:e("settings.schedulesTab.actions.runs")}),t.jsx(L,{danger:!0,size:"small",onClick:async()=>{try{await nt.deleteSchedule(y.id),s.success(e("settings.schedulesTab.deleted")),await k()}catch(E){console.error("[Schedules] Failed to delete:",E),s.error(e("settings.schedulesTab.deleteFailed"))}},children:e("settings.schedulesTab.actions.delete")})]}),t.jsxs(H,{gap:8,align:"center",wrap:"wrap",children:[t.jsx(Me,{type:"secondary",children:e("settings.schedulesTab.columns.intervalSeconds")}),y.trigger.type==="interval"?P:t.jsx(Se,{title:e("settings.schedulesTab.nonIntervalReadOnly"),children:t.jsx("span",{children:P})})]})]})}}],[g,s,k,e]);return t.jsxs(H,{vertical:!0,gap:16,children:[n,t.jsx(R,{title:e("settings.schedulesTab.createTitle"),className:"lotus-settings-card",children:t.jsxs(v,{form:w,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,P=we(h.task_message),E=we(h.model);if(y&&!P){s.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:I,errorKey:O}=Rn(h);if(!I){s.error(e(O||"settings.schedulesTab.validation.triggerRequired"));return}await nt.createSchedule({name:String(h.name||"").trim(),trigger:I,timezone:we(h.timezone),start_at:we(h.start_at),end_at:we(h.end_at),misfire_policy:zn(h),overlap_policy:h.overlap_policy,enabled:!!h.enabled,run_config:{system_prompt:we(h.system_prompt),task_message:P,model:E,workspace_path:we(h.workspace_path),enhance_prompt:we(h.enhance_prompt),auto_execute:y}}),s.success(e("settings.schedulesTab.created")),w.resetFields(),await k()}catch(y){console.error("[Schedules] Failed to create schedule:",y),s.error(e("settings.schedulesTab.createFailed"))}},children:[U(M,_),t.jsx(L,{type:"primary",htmlType:"submit",children:e("settings.schedulesTab.actions.create")})]})}),t.jsx(R,{title:e("settings.schedulesTab.listTitle"),className:"lotus-settings-card",extra:t.jsx(L,{onClick:()=>void k(),loading:a,children:e("settings.schedulesTab.actions.refresh")}),children:t.jsx(dt,{rowKey:"id",columns:Z,dataSource:i,loading:a,pagination:{pageSize:10},scroll:{x:1500}})}),t.jsx(ct,{title:e("settings.schedulesTab.scheduleSessionsTitle"),open:p.open,onCancel:()=>c(h=>({...h,open:!1,scheduleId:null})),footer:null,children:p.loading?t.jsx(Me,{type:"secondary",children:e("settings.schedulesTab.loading")}):t.jsx(H,{vertical:!0,gap:8,children:p.sessions.length===0?t.jsx(Me,{type:"secondary",children:e("settings.schedulesTab.noSessionsYet")}):p.sessions.map(h=>t.jsxs(H,{justify:"space-between",align:"center",children:[t.jsxs(H,{vertical:!0,style:{minWidth:0},children:[t.jsx(Me,{strong:!0,ellipsis:!0,children:h.title}),t.jsxs(Me,{type:"secondary",ellipsis:!0,children:[h.id," • ",h.updated_at]})]}),t.jsx(L,{size:"small",onClick:()=>{va(h.id,{forceRefreshIndex:!0,forceLoadHistory:!0,subscribeIfRunning:!0,forceSubscribe:!0}),S()},children:e("settings.schedulesTab.actions.open")})]},h.id))})}),t.jsx(ct,{title:e("settings.schedulesTab.scheduleRunsTitle"),open:d.open,onCancel:()=>u(h=>({...h,open:!1,scheduleId:null})),footer:null,width:960,children:d.loading?t.jsx(Me,{type:"secondary",children:e("settings.schedulesTab.loading")}):d.runs.length===0?t.jsx(Me,{type:"secondary",children:e("settings.schedulesTab.noRunsYet")}):t.jsx(dt,{rowKey:"run_id",pagination:{pageSize:8},dataSource:d.runs,columns:[{title:e("settings.schedulesTab.runHistory.columns.status"),key:"status",render:(h,y)=>t.jsx(le,{color:to(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(ct,{title:e("settings.schedulesTab.editTitle"),open:j.open,onCancel:()=>f({open:!1,schedule:null,saving:!1}),okText:e("settings.schedulesTab.actions.save"),confirmLoading:j.saving,onOk:()=>g.submit(),forceRender:!0,children:t.jsx(v,{form:g,layout:"vertical",onFinish:async h=>{const y=j.schedule;if(!y)return;const P=!!h.auto_execute,E=we(h.task_message),I=we(h.model);if(P&&!E){s.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:O,errorKey:K}=Rn(h);if(!O){s.error(e(K||"settings.schedulesTab.validation.triggerRequired"));return}f(Q=>({...Q,saving:!0}));try{await nt.patchSchedule(y.id,{name:String(h.name||"").trim()||void 0,enabled:!!h.enabled,trigger:O,timezone:we(h.timezone),start_at:we(h.start_at),end_at:we(h.end_at),misfire_policy:zn(h),overlap_policy:h.overlap_policy,run_config:{system_prompt:we(h.system_prompt),task_message:E,model:I,workspace_path:we(h.workspace_path),enhance_prompt:we(h.enhance_prompt),auto_execute:P}}),s.success(e("settings.schedulesTab.updated")),f({open:!1,schedule:null,saving:!1}),await k()}catch(Q){console.error("[Schedules] Failed to patch schedule:",Q),s.error(e("settings.schedulesTab.updateFailed")),f(W=>({...W,saving:!1}))}},children:U(b,D)})})]})}const{Text:Wt}=ce,Gt=Ys.getInstance();function po(){const{t:e}=se(),{modal:s,message:n}=Ft.useApp(),a=qe(w=>w.chats),r=qe(w=>w.currentSessionId),i=qe(w=>w.refreshChats),l=qe(w=>w.loadChats),p=qe(w=>w.loadChatHistory),[c,d]=o.useState(!0),[u,j]=o.useState(!1),f=o.useMemo(()=>r?a.find(w=>w.id===r)??null:null,[a,r]),S=async w=>{if(!u){j(!0);try{await w()}finally{j(!1)}}};return t.jsxs(H,{vertical:!0,gap:16,children:[t.jsx(R,{size:"small",title:e("settings.sessionsTab.currentSessionTitle"),children:f?t.jsxs(H,{vertical:!0,gap:4,children:[t.jsx(Wt,{strong:!0,ellipsis:!0,children:f.title}),t.jsxs(Wt,{type:"secondary",ellipsis:!0,children:[e("settings.sessionsTab.id"),": ",f.id," ","•"," ",e("settings.sessionsTab.kind"),": ",f.kind]}),t.jsx(H,{gap:8,wrap:"wrap",style:{marginTop:8},children:t.jsx(L,{danger:!0,loading:u,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 S(async()=>{await Gt.clearSession(f.id),await p(f.id),await i(),n.success(e("settings.sessionsTab.sessionCleared"))})}})},children:e("settings.sessionsTab.clearMessages")})})]}):t.jsx(Wt,{type:"secondary",children:e("settings.sessionsTab.noActiveSession")})}),t.jsxs(R,{size:"small",title:e("settings.sessionsTab.bulkCleanupTitle"),children:[t.jsxs(H,{align:"center",gap:8,style:{marginBottom:12},children:[t.jsx(Wt,{children:e("settings.sessionsTab.keepPinned")}),t.jsx(ge,{checked:c,onChange:d})]}),t.jsxs(H,{gap:8,wrap:"wrap",children:[t.jsx(L,{danger:!0,loading:u,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 S(async()=>{await Gt.cleanupSessions("all",c),await l(),n.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteAll")}),t.jsx(L,{danger:!0,loading:u,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 S(async()=>{await Gt.cleanupSessions("empty",c),await l(),n.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteEmpty")}),t.jsx(L,{danger:!0,loading:u,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 S(async()=>{await Gt.cleanupSessions("children",c),await l(),n.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteChildren")})]})]}),t.jsxs(R,{size:"small",title:e("settings.sessionsTab.devResetTitle"),children:[t.jsx(Wt,{type:"secondary",children:e("settings.sessionsTab.devResetDescription")}),t.jsx(H,{style:{marginTop:12},children:t.jsx(L,{danger:!0,type:"primary",loading:u,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 S(async()=>{await Gt.devResetSessions(),await l(),n.success(e("settings.sessionsTab.devResetDone"))})}})},children:e("settings.sessionsTab.devResetAction")})})]})]})}const{Text:at}=ce,{useToken:ho}=fe,fo=()=>{const{t:e}=se(),{token:s}=ho(),[n,a]=o.useState(ln()),r=Ta(),i=(l,p)=>{const c={...n,[l]:p};a(c),ja({[l]:p})};return o.useEffect(()=>{a(ln())},[]),t.jsx(R,{size:"small",className:"lotus-settings-card",children:t.jsxs(H,{vertical:!0,gap:s.marginMD,children:[!r&&t.jsx(Ve,{type:"info",showIcon:!0,message:e("settings.notificationsTab.desktopOnly","Desktop notifications are only available in the Bodhi desktop app.")}),t.jsxs(H,{align:"center",gap:s.marginSM,children:[t.jsx($a,{}),t.jsx(at,{strong:!0,children:e("settings.notificationsTab.title","Desktop Notifications")})]}),t.jsx(at,{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(Re,{style:{margin:`${s.marginXS}px 0`}}),t.jsxs(H,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(at,{children:e("settings.notificationsTab.enabled","Enable desktop notifications")}),t.jsx(ge,{"data-testid":"notification-enabled-toggle",checked:n.enabled,onChange:l=>i("enabled",l),disabled:!r})]}),t.jsx(Re,{style:{margin:`${s.marginXS}px 0`}}),t.jsx(at,{strong:!0,style:{fontSize:s.fontSizeSM,opacity:n.enabled?1:.5},children:e("settings.notificationsTab.events","Notify when:")}),t.jsxs(H,{vertical:!0,gap:s.marginSM,style:{opacity:n.enabled?1:.5,pointerEvents:n.enabled?"auto":"none"},children:[t.jsxs(H,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(at,{children:e("settings.notificationsTab.onClarification","Agent needs clarification")}),t.jsx(ge,{"data-testid":"notification-clarification-toggle",checked:n.onClarification,onChange:l=>i("onClarification",l),disabled:!r})]}),t.jsxs(H,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(at,{children:e("settings.notificationsTab.onToolApproval","Tool execution needs approval")}),t.jsx(ge,{"data-testid":"notification-tool-approval-toggle",checked:n.onToolApproval,onChange:l=>i("onToolApproval",l),disabled:!r})]}),t.jsxs(H,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(at,{children:e("settings.notificationsTab.onContextPressure","Context window is critically full")}),t.jsx(ge,{"data-testid":"notification-context-pressure-toggle",checked:n.onContextPressure,onChange:l=>i("onContextPressure",l),disabled:!r})]}),t.jsxs(H,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(at,{children:e("settings.notificationsTab.onSubAgentComplete","Background task completes")}),t.jsx(ge,{"data-testid":"notification-subagent-complete-toggle",checked:n.onSubAgentComplete,onChange:l=>i("onSubAgentComplete",l),disabled:!r})]})]}),t.jsx(Re,{style:{margin:`${s.marginXS}px 0`}}),t.jsxs(H,{align:"center",gap:s.marginSM,children:[t.jsx(Ba,{style:{color:s.colorPrimary}}),t.jsx(at,{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:ps,Paragraph:yo}=ce,oa=({open:e,onCancel:s,onComplete:n,onCopyCode:a,completingAuth:r,copiedUserCode:i,deviceCodeInfo:l,timeRemaining:p,token:c})=>{const{t:d}=se();return t.jsx(ct,{title:d("settings.providerTab.copilotAuthModalTitle"),open:e,onCancel:s,footer:[t.jsx(L,{onClick:s,children:d("settings.providerTab.cancel")},"cancel"),t.jsx(L,{type:"primary",onClick:n,loading:r,children:d("settings.providerTab.completedAuthorization")},"complete")],children:l&&t.jsxs(F,{direction:"vertical",size:"large",style:{width:"100%"},children:[t.jsx(Ve,{message:d("settings.providerTab.browserOpened"),description:t.jsxs("ol",{children:[t.jsx("li",{children:d("settings.providerTab.authStep1")}),t.jsx("li",{children:d("settings.providerTab.authStep2")}),t.jsx("li",{children:d("settings.providerTab.authStep3")})]}),type:"info"}),t.jsx(R,{size:"small",className:"lotus-settings-card",children:t.jsxs(F,{direction:"vertical",style:{width:"100%"},children:[t.jsx(ps,{type:"secondary",children:d("settings.providerTab.visitUrl")}),t.jsx(F,{children:t.jsx(ps,{copyable:{text:l.verification_uri},children:l.verification_uri})})]})}),t.jsx(R,{style:{textAlign:"center",background:c.colorFillTertiary,borderColor:c.colorBorderSecondary},children:t.jsxs(F,{direction:"vertical",style:{width:"100%"},children:[t.jsx(ps,{type:"secondary",children:d("settings.providerTab.enterCode")}),t.jsxs(F,{children:[t.jsx(ps,{style:{color:c.colorText,fontSize:"32px",fontFamily:"monospace",fontWeight:"bold",letterSpacing:"4px"},children:l.user_code}),t.jsx(L,{icon:i?t.jsx(Ws,{}):t.jsx(Yn,{}),onClick:a,type:i?"default":"primary",children:d(i?"settings.providerTab.copied":"settings.providerTab.copyCode")})]}),t.jsx("div",{style:{marginTop:8},children:t.jsxs(le,{color:p<60?"error":p<180?"warning":"success",children:[t.jsx(qa,{style:{marginRight:4}}),"Expires in ",Math.floor(p/60),":",(p%60).toString().padStart(2,"0")]})})]})}),t.jsx(yo,{type:"secondary",children:d("settings.providerTab.afterContinueHint")})]})})},xo=new Set(["id","type","provider_type","label","enabled","api_key_encrypted"]),Ln=e=>e?Object.fromEntries(Object.entries(e).filter(([s])=>!xo.has(s))):{},{Password:On}=B,{Text:pt,Paragraph:$s}=ce,bo=["low","medium","high","xhigh","max"],Jt=(e,s)=>t.jsx(Y,{placeholder:e("settings.providerTab.reasoningEffortDefault"),allowClear:!0,value:s==null?void 0:s.value,onChange:void 0,disabled:s==null?void 0:s.disabled,size:s==null?void 0:s.size,style:s==null?void 0:s.style,children:bo.map(n=>t.jsx(Y.Option,{value:n,children:e(`chat.input.reasoning.${n}`)},n))}),Nn=e=>t.jsx(v.Item,{name:"responses_only_models",label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:t.jsxs(t.Fragment,{children:[t.jsx("div",{children:e("settings.providerTab.responsesOnlyHelp1")}),t.jsx("div",{children:e("settings.providerTab.responsesOnlyHelp2")})]}),children:t.jsx(Y,{mode:"tags",tokenSeparators:[","," ",`
3
+ `," "],placeholder:e("settings.providerTab.responsesOnlyModelsPlaceholder"),allowClear:!0})}),vo=e=>Array.isArray(e)?e.map(s=>typeof s=="string"?s.trim():"").filter(s=>!!s):[],To=({type:e})=>{const{t:s}=se();if(!e)return null;switch(e){case"openai":return t.jsxs(t.Fragment,{children:[t.jsx(v.Item,{name:"api_key",label:s("settings.providerTab.openaiApiKey"),rules:[{required:!0,message:s("settings.providerTab.openaiApiKeyRequired")}],children:t.jsx(B.Password,{placeholder:s("settings.providerTab.openaiApiKeyPlaceholder","sk-..."),prefix:t.jsx(yt,{})})}),t.jsx(v.Item,{name:"base_url",label:s("settings.providerTab.baseUrlOptional"),extra:s("settings.providerTab.openaiBaseUrlHelp"),children:t.jsx(B,{placeholder:s("settings.providerTab.openaiBaseUrlPlaceholder","https://api.openai.com/v1")})}),t.jsx(v.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Jt(s)}),Nn(s)]});case"anthropic":return t.jsxs(t.Fragment,{children:[t.jsx(v.Item,{name:"api_key",label:s("settings.providerTab.anthropicApiKey"),rules:[{required:!0,message:s("settings.providerTab.anthropicApiKeyRequired")}],children:t.jsx(On,{placeholder:s("settings.providerTab.anthropicApiKeyPlaceholder","sk-ant-..."),prefix:t.jsx(yt,{})})}),t.jsx(v.Item,{name:"base_url",label:s("settings.providerTab.baseUrlOptional"),extra:s("settings.providerTab.anthropicBaseUrlHelp"),children:t.jsx(B,{placeholder:s("settings.providerTab.anthropicBaseUrlPlaceholder","https://api.anthropic.com/v1")})}),t.jsx(v.Item,{name:"max_tokens",label:s("settings.providerTab.maxTokensOptional"),extra:s("settings.providerTab.maxTokensHelp"),children:t.jsx(B,{type:"number",placeholder:s("settings.providerTab.maxTokensPlaceholder","4096"),min:1,max:1e5})}),t.jsx(v.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Jt(s)})]});case"gemini":return t.jsxs(t.Fragment,{children:[t.jsx(v.Item,{name:"api_key",label:s("settings.providerTab.geminiApiKey"),rules:[{required:!0,message:s("settings.providerTab.geminiApiKeyRequired")}],children:t.jsx(On,{placeholder:s("settings.providerTab.geminiApiKeyPlaceholder","AIza..."),prefix:t.jsx(yt,{})})}),t.jsx(v.Item,{name:"base_url",label:s("settings.providerTab.baseUrlOptional"),extra:s("settings.providerTab.geminiBaseUrlHelp"),children:t.jsx(B,{placeholder:s("settings.providerTab.geminiBaseUrlPlaceholder","https://generativelanguage.googleapis.com/v1beta")})}),t.jsx(v.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Jt(s)})]});case"copilot":return t.jsxs(t.Fragment,{children:[t.jsx(v.Item,{name:"headless_auth",label:s("settings.providerTab.headlessAuth"),valuePropName:"checked",extra:s("settings.providerTab.headlessAuthHelp"),children:t.jsx(ge,{})}),t.jsx(v.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Jt(s)}),Nn(s)]});case"bodhi":return t.jsxs(t.Fragment,{children:[t.jsx(v.Item,{name:"api_key",label:s("settings.providerTab.bodhiApiKey"),rules:[{required:!0,message:s("settings.providerTab.apiKeyRequired")}],children:t.jsx(B.Password,{placeholder:s("settings.providerTab.bodhiApiKeyPlaceholder","bhi_sk_..."),prefix:t.jsx(yt,{})})}),t.jsx(v.Item,{name:"base_url",label:s("settings.providerTab.bodhiBaseUrl"),extra:s("settings.providerTab.bodhiBaseUrlExtra"),children:t.jsx(B,{placeholder:s("settings.providerTab.bodhiBaseUrlPlaceholder","http://localhost:8080")})}),t.jsx(v.Item,{name:"target_provider",label:s("settings.providerTab.targetProvider"),extra:s("settings.providerTab.targetProviderExtra"),children:t.jsxs(Y,{placeholder:s("settings.providerTab.targetProviderPlaceholder","openai"),allowClear:!0,children:[t.jsx(Y.Option,{value:"openai",children:"OpenAI"}),t.jsx(Y.Option,{value:"anthropic",children:"Anthropic"}),t.jsx(Y.Option,{value:"gemini",children:"Gemini"})]})}),t.jsx(v.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Jt(s)})]});default:return null}},jo=({instances:e,defaultInstanceId:s,onInstancesChanged:n})=>{const{t:a}=se(),{message:r}=Ft.useApp(),{token:i}=fe.useToken(),[l]=v.useForm(),[p,c]=o.useState(!1),[d,u]=o.useState(null),[j,f]=o.useState(!1),[S,w]=o.useState(null),[g,M]=o.useState(void 0),[_,b]=o.useState(null),[D,k]=o.useState(!1),[A,te]=o.useState(!1),[z,U]=o.useState(0),[Z,h]=o.useState(!1),[y,P]=o.useState(!1),[E,I]=o.useState("unknown"),[O,K]=o.useState(!1),Q=o.useCallback(V=>({type:V.type,label:V.label,enabled:V.enabled,...Ln(V.config)}),[]),W=o.useCallback(()=>{u(null),M(void 0),c(!0)},[]),pe=async()=>{try{P(!0);const V=await Te.startCopilotAuth();b(V),k(!0),U(V.expires_in)}catch(V){r.error(a("settings.providerTab.startCopilotAuthFailed","Failed to start Copilot authentication")),console.error("Failed to start Copilot authentication:",V)}finally{P(!1)}},he=async()=>{if(_)try{te(!0),await Te.completeCopilotAuth({device_code:_.device_code,interval:_.interval||5,expires_in:_.expires_in}),r.success(a("settings.providerTab.copilotAuthSuccess","Copilot authentication successful!")),k(!1),b(null),await C()}catch(V){r.error(a("settings.providerTab.completeAuthFailed","Authentication completion failed")),console.error("Authentication completion failed:",V)}finally{te(!1)}},De=async()=>{if(_)try{await Zs(_.user_code),h(!0),r.success(a("settings.providerTab.userCodeCopied","User code copied!")),setTimeout(()=>h(!1),2e3)}catch{r.error(a("settings.providerTab.copyCodeFailed","Failed to copy code"))}},C=o.useCallback(async()=>{try{K(!0);const V=await Te.getCopilotAuthStatus();I(V.authenticated?"authenticated":"not_authenticated")}catch(V){console.error("Failed to check Copilot auth status:",V),I("unknown")}finally{K(!1)}},[]);o.useEffect(()=>{p&&g==="copilot"&&C()},[C,p,g]);const G=o.useCallback(V=>{if(!V){l.resetFields();return}if(d){l.setFieldsValue(Q(d)),M(d.type);return}l.setFieldsValue({enabled:!0})},[Q,d,l]),X=(V="small")=>t.jsx(R,{size:"small",title:a("settings.providerTab.copilotAuth","GitHub Copilot Authentication"),style:{marginTop:8},children:t.jsxs(F,{direction:"vertical",style:{width:"100%"},children:[t.jsxs(F,{children:[t.jsx(pt,{strong:!0,children:a("settings.providerTab.authStatus","Status:")}),E==="authenticated"?t.jsx(le,{color:"success",children:a("settings.providerTab.authenticated","Authenticated")}):E==="not_authenticated"?t.jsx(le,{color:"warning",children:a("settings.providerTab.notAuthenticated","Not Authenticated")}):t.jsx(le,{children:a("settings.providerTab.unknown","Unknown")}),t.jsx(L,{type:"text",size:"small",onClick:()=>void C(),loading:O,children:a("settings.providerTab.refreshStatus","Refresh")})]}),t.jsx($s,{type:"secondary",style:{marginBottom:8},children:a("settings.providerTab.copilotAuthHelp","Copilot requires OAuth authentication. Click the button below to start the Device Code Flow.")}),t.jsx(L,{type:"primary",icon:t.jsx(Zn,{}),onClick:()=>void pe(),loading:y,size:V,children:a("settings.providerTab.authenticateCopilot","Authenticate Copilot")})]})}),ee=o.useCallback(V=>{u(V),M(V.type),c(!0)},[]),Pe=o.useCallback(async()=>{try{const V=await l.validateFields();f(!0);const{type:ve,label:He,enabled:Ce,request_overrides_json:ze,...ke}=V,Ke=Ln(ke);if("responses_only_models"in Ke&&(Ke.responses_only_models=vo(Ke.responses_only_models)),typeof ze=="string"&&ze.trim()&&(Ke.request_overrides=JSON.parse(ze)),d){const m={label:He,enabled:Ce,config:Ke};await Te.updateProviderInstance(d.id,m),r.success(a("settings.providerTab.instanceUpdated","Provider instance updated"))}else{const m={type:ve,label:He||ft[ve]||ve,enabled:Ce??!0,config:Ke};await Te.createProviderInstance(m),r.success(a("settings.providerTab.instanceCreated","Provider instance created"))}c(!1),await n(),await Qe.getState().loadProviderInstances()}catch(V){(fs(V)||V instanceof Error&&!V.errorFields)&&r.error(V.message)}finally{f(!1)}},[d,l,r,n,a]),Ie=o.useCallback(async V=>{try{w(V),await Te.deleteProviderInstance(V),r.success(a("settings.providerTab.instanceDeleted","Provider instance deleted")),await n(),await Qe.getState().loadProviderInstances()}catch(ve){r.error(fs(ve)?ve.message:a("settings.providerTab.instanceDeleteFailed","Failed to delete instance"))}finally{w(null)}},[n,r,a]),$e=o.useCallback(async V=>{try{await Te.setDefaultProviderInstance(V),r.success(a("settings.providerTab.defaultInstanceSet","Default provider updated")),await n(),await Qe.getState().loadProviderInstances()}catch(ve){r.error(fs(ve)?ve.message:a("settings.providerTab.defaultInstanceFailed","Failed to set default"))}},[n,r,a]),Xe=o.useCallback(async()=>{await n()},[n]);return o.useEffect(()=>{Xe()},[]),t.jsxs("div",{style:{marginBottom:16},children:[t.jsxs("div",{style:{marginBottom:12,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[t.jsx(pt,{strong:!0,children:a("settings.providerTab.providerInstances","Provider Instances")}),t.jsx(L,{type:"dashed",icon:t.jsx(It,{}),onClick:W,"data-testid":"add-provider-instance",children:a("settings.providerTab.addInstance","Add Provider")})]}),e.length===0&&t.jsx($s,{type:"secondary",children:a("settings.providerTab.noInstances",'No provider instances configured. Click "Add Provider" to create one.')}),t.jsx(Ts,{ghost:!0,items:e.map(V=>{const ve=V.id===s,He=ft[V.type]||V.type;return{key:V.id,label:t.jsxs(F,{size:"small",children:[t.jsx("span",{style:{fontWeight:500},children:V.label||He}),t.jsx(le,{color:"processing",style:{fontSize:11},children:He}),ve&&t.jsxs(le,{color:"gold",style:{fontSize:11},children:[t.jsx(Ha,{})," ",a("settings.providerTab.default","Default")]}),!V.enabled&&t.jsx(le,{color:"default",style:{fontSize:11},children:a("settings.providerTab.disabled","Disabled")})]}),extra:t.jsxs(F,{size:4,onClick:Ce=>Ce.stopPropagation(),children:[!ve&&t.jsx(Se,{title:a("settings.providerTab.setDefault","Set as default"),children:t.jsx(L,{type:"text",size:"small",icon:t.jsx(Ua,{}),onClick:()=>void $e(V.id)})}),t.jsx(L,{type:"text",size:"small",icon:t.jsx(Ss,{}),onClick:()=>ee(V)}),t.jsx(es,{title:a("settings.providerTab.confirmDeleteInstance","Delete this provider instance?"),onConfirm:()=>void Ie(V.id),okText:a("settings.providerTab.delete","Delete"),cancelText:a("settings.providerTab.cancel","Cancel"),children:t.jsx(L,{type:"text",size:"small",danger:!0,icon:t.jsx(ns,{}),loading:S===V.id})})]}),children:t.jsxs("div",{children:[t.jsxs($s,{type:"secondary",style:{marginBottom:8},children:["ID: ",t.jsx(pt,{code:!0,children:V.id})," · Type: ",t.jsx(pt,{code:!0,children:V.type})]}),V.config&&Object.keys(V.config).length>0&&t.jsx(R,{size:"small",style:{marginBottom:8},children:Object.entries(V.config).map(([Ce,ze])=>Ce==="api_key"?t.jsxs("div",{style:{marginBottom:4},children:[t.jsxs(pt,{type:"secondary",children:[Ce,": "]}),t.jsx(pt,{children:"••••••••"})]},Ce):t.jsxs("div",{style:{marginBottom:4},children:[t.jsxs(pt,{type:"secondary",children:[Ce,": "]}),t.jsx(pt,{children:typeof ze=="object"?JSON.stringify(ze):String(ze)})]},Ce))}),V.type==="copilot"&&X("small")]})}})}),t.jsx(ct,{open:p,title:d?a("settings.providerTab.editInstance","Edit Provider Instance"):a("settings.providerTab.createInstance","Create Provider Instance"),onCancel:()=>c(!1),onOk:()=>void Pe(),afterOpenChange:G,confirmLoading:j,width:560,forceRender:!0,destroyOnClose:!0,children:t.jsxs(v,{form:l,layout:"vertical",preserve:!1,children:[t.jsx(v.Item,{name:"type",label:a("settings.providerTab.providerType","Provider Type"),rules:[{required:!0,message:a("settings.providerTab.typeRequired","Please select a provider type")}],children:t.jsx(Y,{disabled:!!d,placeholder:a("settings.providerTab.selectType","Select provider type"),onChange:V=>M(V),children:Object.entries(ft).map(([V,ve])=>t.jsx(Y.Option,{value:V,children:ve},V))})}),t.jsx(v.Item,{name:"label",label:a("settings.providerTab.instanceLabel","Label"),extra:a("settings.providerTab.labelHelp","A display name for this provider instance"),children:t.jsx(B,{placeholder:a("settings.providerTab.labelPlaceholder","My OpenAI Instance")})}),t.jsx(v.Item,{name:"enabled",label:a("settings.providerTab.enabled","Enabled"),valuePropName:"checked",initialValue:!0,children:t.jsx(ge,{})}),t.jsx(Re,{children:a("settings.providerTab.instanceConfig","Configuration")}),t.jsx(v.Item,{noStyle:!0,shouldUpdate:!0,children:()=>t.jsx(To,{form:l,type:g})}),g==="copilot"&&X("middle")]})}),t.jsx(oa,{open:D,onCancel:()=>k(!1),onComplete:()=>void he(),onCopyCode:()=>void De(),completingAuth:A,copiedUserCode:Z,deviceCodeInfo:_,timeRemaining:z,token:i})]})},{Password:Vn}=B,{Text:Je,Paragraph:Bs}=ce,hs=["openai","anthropic","gemini","copilot","bodhi"],Mt=()=>null,qs=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()))},So=(e,s,n)=>{const a=e;a[s]={...a[s]??{},model:n}},$n=e=>{var n,a;const s=(a=(n=e.memory)==null?void 0:n.background_model)==null?void 0:a.trim();return s||void 0},Bn=(e,s)=>{var n,a,r;return s||((n=e==null?void 0:e.chat)==null?void 0:n.provider)||((a=e==null?void 0:e.fast)==null?void 0:a.provider)||((r=e==null?void 0:e.memory_background)==null?void 0:r.provider)||void 0},qn=e=>t.jsxs(F,{direction:"vertical",size:4,children:[t.jsxs(Je,{type:"secondary",children:[e("settings.providerTab.responsesOnlyHelp1")," ",t.jsx(Je,{code:!0,children:"/responses"}),"."]}),t.jsx(Je,{type:"secondary",children:e("settings.providerTab.responsesOnlyHelp2")})]}),_o=["low","medium","high","xhigh","max"],Et=(e,s)=>t.jsx(Y,{placeholder:e("settings.providerTab.reasoningEffortDefault"),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:_o.map(n=>t.jsx(Y.Option,{value:n,children:e(`chat.input.reasoning.${n}`)},n))}),ko=()=>{const{t:e}=se(),{token:s}=fe.useToken(),{message:n}=Ft.useApp(),[a]=v.useForm(),[r,i]=o.useState(!1),[l,p]=o.useState(!1),[c,d]=o.useState("copilot"),[u,j]=o.useState(!1),[f,S]=o.useState(null),[w,g]=o.useState(!1),[M,_]=o.useState(!1),[b,D]=o.useState(null),[k,A]=o.useState(!1),[te,z]=o.useState(!1),[U,Z]=o.useState(0),[h,y]=o.useState(!1),[P,E]=o.useState([]),[I,O]=o.useState(!1),[K,Q]=o.useState([]),[W,pe]=o.useState(null),[he,De]=o.useState(!1),[C,G]=o.useState([]),[X,ee]=o.useState("idle"),[Pe,Ie]=o.useState(null),$e=o.useCallback((x,T)=>{const J=x.instances??[],N=J.reduce((ie,ae)=>{const Ne={...ae.config};return Ne.request_overrides&&typeof Ne.request_overrides=="object"&&(Ne.request_overrides_json=JSON.stringify(Ne.request_overrides,null,2)),ie[ae.id]=Ne,ie},{});let q=x.defaults?{...x.defaults}:void 0;const ue=x.default_provider_instance_id??null,de=ue?J.find(ie=>ie.id===ue):void 0,xe=typeof(de==null?void 0:de.config.model)=="string"?de.config.model.trim():void 0;!qs(q==null?void 0:q.chat)&&ue&&xe&&(q={...q||{},chat:{provider:ue,model:xe}});const Fe=T?$n(T):void 0,je=Bn(q,ue);return Fe&&!(q!=null&&q.memory_background)&&je&&(q={...q||{},memory_background:{provider:je,model:Fe}}),{defaults:q,features:x.features,providers:N}},[]),Xe=o.useCallback((x,T)=>{Q(x.instances??[]),pe(x.default_provider_instance_id??null),De(!0),a.setFieldsValue($e(x,T)),j(!0)},[$e,a]),V=o.useCallback(x=>{if(!(x!=null&&x.trim()))return;const T=K.find(J=>J.id===x);return T?T.label||ft[T.type]:ft[x]||x},[K]),ve=o.useCallback((x,T)=>{const J=new Set;x!=null&&x.trim()&&J.add(x);for(const N of hs){const q=T==null?void 0:T[N];q&&Object.keys(q).length>0&&J.add(N)}return Array.from(J)},[]);o.useEffect(()=>{if(X!=="success")return;const x=setTimeout(()=>{ee("idle"),Ie(null)},2e3);return()=>clearTimeout(x)},[X]),o.useEffect(()=>{if(!k||!b){Z(0);return}Z(b.expires_in);const x=setInterval(()=>{Z(T=>T<=1?(clearInterval(x),0):T-1)},1e3);return()=>clearInterval(x)},[k,b]);const He=o.useCallback(async()=>{var x;try{i(!0);const[T,J]=await Promise.all([Te.getProviderConfig(),rt.getInstance().getBambooConfig().catch(()=>({}))]);let N=T.defaults?{...T.defaults}:void 0;if(!((x=N==null?void 0:N.chat)!=null&&x.model)&&T.provider&&T.providers){const je=T.provider,ie=T.providers[je],ae=ie==null?void 0:ie.model;ae&&(N={...N||{},chat:{provider:je,model:ae}})}const q=$n(J),ue=Bn(N,T.provider||null);q&&!(N!=null&&N.memory_background)&&ue&&(N={...N||{},memory_background:{provider:ue,model:q}});const de=qs(N==null?void 0:N.chat)?N:void 0,xe={provider:T.provider,defaults:de,providers:T.providers||{},features:T.features};lt("[Provider]","Loaded provider config:",xe);const Fe={...xe.providers||{}};hs.forEach(je=>{const ie=Fe[je];ie&&ie.request_overrides&&typeof ie.request_overrides=="object"&&(ie.request_overrides_json=JSON.stringify(ie.request_overrides,null,2))}),d(xe.provider),De(!1),G(ve(xe.provider,Fe)),a.setFieldsValue({...xe,providers:Fe,defaults:xe.defaults}),j(!0)}catch(T){n.error(e("settings.providerTab.loadConfigFailed")),console.error("Failed to load provider config:",T)}finally{i(!1)}},[a,ve,n,e]),Ce=o.useCallback(async()=>{try{const x=await Te.getEnvVars();E(x.entries||[])}catch(x){console.warn("Failed to load env vars for provider overrides:",x)}},[]),ze=o.useCallback(async()=>{try{const[x,T]=await Promise.all([Te.getProviderInstances(),rt.getInstance().getBambooConfig().catch(()=>({}))]);if(!Array.isArray(x.instances))throw new Error("Provider instances API returned an invalid payload");Xe(x,T)}catch{}},[Xe]),ke=o.useCallback(async()=>{try{g(!0);const x=await Te.getCopilotAuthStatus();S(x)}catch(x){console.error("Failed to check Copilot auth status:",x),S({authenticated:!1,message:e("settings.providerTab.checkStatusFailed")})}finally{g(!1)}},[e]);o.useEffect(()=>{Ce(),Qe.getState().loadCatalog(),ke(),(async()=>{try{const[x,T]=await Promise.all([Te.getProviderInstances(),rt.getInstance().getBambooConfig().catch(()=>({}))]);if(!Array.isArray(x.instances))throw new Error("Provider instances API returned an invalid payload");Xe(x,T)}catch{await He()}})()},[He,Ce,ke,Xe]);const Ke=async()=>{try{_(!0);const x=await Te.startCopilotAuth();D(x),A(!0)}catch(x){n.error(e("settings.providerTab.startCopilotAuthFailed")),console.error("Failed to start Copilot authentication:",x)}finally{_(!1)}},m=async()=>{if(b)try{z(!0),await Te.completeCopilotAuth({device_code:b.device_code,interval:b.interval||5,expires_in:b.expires_in}),n.success(e("settings.providerTab.copilotAuthSuccess")),A(!1),D(null),await ke()}catch(x){n.error(e("settings.providerTab.completeAuthFailed")),console.error("Authentication completion failed:",x)}finally{z(!1)}},re=async()=>{if(b)try{await Zs(b.user_code),y(!0),n.success(e("settings.providerTab.userCodeCopied")),setTimeout(()=>y(!1),2e3)}catch{n.error(`${e("settings.providerTab.copyCodeFailedPrefix")} ${b.user_code}`)}},me=async()=>{try{_(!0),await Te.logoutCopilot(),n.success(e("settings.providerTab.logoutSuccess")),await ke()}catch(x){n.error(e("settings.providerTab.logoutFailed")),console.error("Failed to logout:",x)}finally{_(!1)}},Le=o.useCallback(async()=>{O(!0);try{const x=await Te.fetchCatalogModels();await Qe.getState().loadCatalog();const T=x.fetched.filter(N=>N.models&&N.models.length>0).length;x.fetched.filter(N=>N.error).length>0?n.warning(e("settings.providerTab.fetchModelsPartialSuccess",{success:T,total:x.fetched.length})):n.success(e("settings.providerTab.fetchModelsSuccess",{count:T}))}catch{n.error(e("settings.providerTab.fetchModelsFailed"))}finally{O(!1)}},[n,e]),ye=x=>fs(x)||x instanceof Error?x.message:e("settings.providerTab.unknownError"),Oe=x=>{a.setFields([{name:["provider"],errors:[]},{name:["providers",x,"api_key"],errors:[]},{name:["defaults","chat"],errors:[]}])},cs=x=>{const T=x.trim();return T?T.includes(".")?T.split(".").filter(Boolean):T==="provider"?["provider"]:T==="provider/providers"?["provider"]:null:null},ks=(x,T)=>{if(!x.length)return;const J=x.map(N=>{const q=cs(N.path);return q?{name:q,errors:[N.message]}:N.message.toLowerCase().includes("api key")?{name:["providers",T,"api_key"],errors:[N.message]}:{name:["provider"],errors:[N.message]}}).filter((N,q,ue)=>ue.findIndex(de=>JSON.stringify(de.name)===JSON.stringify(N.name))===q);J.length&&a.setFields(J)},ws=async x=>{var J;const T=x.provider||c;Oe(T);try{const q=await rt.getInstance().validateBambooConfigPatch({provider:x.provider,providers:x.providers||{},defaults:x.defaults,features:{...x.features||{},provider_model_ref:!0}});if(q.valid)return{valid:!0};const ue=((J=q.errors)==null?void 0:J.provider)||[];ks(ue,T);const de=ue[0];return{valid:!1,message:(de==null?void 0:de.message)||e("settings.providerTab.invalidConfig")}}catch(N){return console.warn("Config validation failed, falling back to save:",N),{valid:!0}}},Ot=async(x,T)=>{var J,N;try{i(!0);const q={provider:x.provider,defaults:x.defaults,providers:{...x.providers||{}},features:{...x.features||{},provider_model_ref:!0}},ue=(J=q.defaults)==null?void 0:J.chat;if(!qs(ue)){const ie=e("settings.providerTab.selectModelRequired");if(a.setFields([{name:["defaults","chat"],errors:[ie]}]),(T==null?void 0:T.showMessage)!==!1&&n.error(ie),T!=null&&T.throwOnError)throw new Error(ie);return}const de=q.providers;for(const ie of hs){const ae=de[ie];if(!ae)continue;const Ne=ae.request_overrides_json;if(typeof Ne!="string")continue;const bt=Ne.trim();if(!bt)delete ae.request_overrides;else try{ae.request_overrides=JSON.parse(bt)}catch(Vt){const $t=e("settings.providerTab.invalidRequestOverridesJson",{provider:ie,error:Vt.message});if(a.setFields([{name:["providers",ie,"request_overrides_json"],errors:[$t]}]),(T==null?void 0:T.showMessage)!==!1&&n.error($t),T!=null&&T.throwOnError)throw Vt;return}delete ae.request_overrides_json}const xe={...q.providers||{}},Fe=q.provider,je=(N=q.defaults)==null?void 0:N.chat;if(je!=null&&je.model&&Fe&&So(xe,Fe,je.model),he){const ie=rt.getInstance(),ae={defaults:q.defaults,features:{...q.features||{},provider_model_ref:!0}};lt("[Provider]","Saving instance-mode config:",ae),await ie.setBambooConfig(ae)}else{const ae={provider:q.provider||c,defaults:q.defaults,providers:xe,features:q.features},Ne=await ws(q);if(!Ne.valid){const bt=Ne.message||e("settings.providerTab.invalidConfig");if((T==null?void 0:T.showMessage)!==!1&&n.error(`${e("settings.providerTab.invalidConfigPrefix")}: ${bt}`),T!=null&&T.throwOnError)throw new Error(bt);return}lt("[Provider]","Saving provider config:",ae),await Te.saveProviderConfig(ae)}(T==null?void 0:T.showMessage)!==!1&&n.success(e("settings.providerTab.saveConfigSuccess"))}catch(q){const ue=ye(q);if((T==null?void 0:T.showMessage)!==!1&&n.error(ue?`${e("settings.providerTab.saveConfigErrorPrefix")}: ${ue}`:e("settings.providerTab.saveConfigFailed")),console.error("Failed to save configuration:",q),T!=null&&T.throwOnError)throw q}finally{i(!1)}},gt=async x=>{var T,J,N,q,ue;try{p(!0);const{useProviderStore:de}=await Gs(async()=>{const{useProviderStore:Bt}=await import("./App-CSoVc5kq.js").then(Fs=>Fs.af);return{useProviderStore:Bt}},__vite__mapDeps([4,1,2,3,5,6,7,8]),import.meta.url),{useAppStore:xe}=await Gs(async()=>{const{useAppStore:Bt}=await import("./App-CSoVc5kq.js").then(Fs=>Fs.ag);return{useAppStore:Bt}},__vite__mapDeps([4,1,2,3,5,6,7,8]),import.meta.url),Fe=(T=de.getState().providerConfig.defaults)==null?void 0:T.chat;he?await de.getState().loadProviderInstances():await de.getState().loadProviderConfig();const je=(J=de.getState().providerConfig.defaults)==null?void 0:J.chat;de.getState().setSelectedModelRef(null);const ie=xe.getState().currentSessionId,ae=ie&&xe.getState().chats.find(Bt=>Bt.id===ie)||null,Ne=Fe?`${Fe.provider}/${Fe.model}`:null,bt=je?`${je.provider}/${je.model}`:null,Vt=(N=ae==null?void 0:ae.config)!=null&&N.model_ref?`${ae.config.model_ref.provider}/${ae.config.model_ref.model}`:null,$t=((ue=(q=ae==null?void 0:ae.config)==null?void 0:q.model)==null?void 0:ue.trim())||null;!!(ie&&(ae!=null&&ae.config)&&je&&bt!==Ne&&(!Vt||Vt===Ne)&&(!$t||$t===(Fe==null?void 0:Fe.model)))&&ie&&(ae!=null&&ae.config)&&je&&xe.getState().updateSession(ie,{config:{...ae.config,model:je.model,model_ref:je}}),(x==null?void 0:x.showMessage)!==!1&&n.success(e("settings.providerTab.applyConfigSuccess"))}catch(de){const xe=ye(de);if((x==null?void 0:x.showMessage)!==!1&&n.error(xe?`${e("settings.providerTab.applyConfigErrorPrefix")}: ${xe}`:e("settings.providerTab.applyConfigFailed")),console.error("Failed to apply configuration:",de),x!=null&&x.throwOnError)throw de}finally{p(!1)}},Cs=async x=>{try{const T=a.getFieldsValue(!0);await Ot(T,{throwOnError:!0}),await gt({throwOnError:!0})}catch{}},Ms=async(x,T)=>{if(!(x==="chat"&&!T)&&X!=="saving"){ee("saving"),Ie(null);try{const J=a.getFieldsValue(!0),N=J.defaults;if(!(N!=null&&N.chat))throw new Error(e("settings.providerTab.selectModelRequired"));J.defaults={...N,[x]:T},await Ot(J,{showMessage:!1,throwOnError:!0}),await gt({showMessage:!1,throwOnError:!0}),ee("success"),n.success(e("settings.providerTab.modelUpdated"))}catch(J){const N=ye(J);ee("error"),Ie(N),n.error(N?`${e("settings.providerTab.updateModelErrorPrefix")}: ${N}`:e("settings.providerTab.updateModelFailed"))}}},Es=async(x,T)=>{if(X!=="saving"){ee("saving"),Ie(null);try{if(he){const J=K.find(N=>N.id===x);if(!J)throw new Error(e("settings.providerTab.providerNotConfigured"));await Te.updateProviderInstance(J.id,{config:{reasoning_effort:T??null}}),await ze(),await Qe.getState().loadProviderInstances()}else{const J=a.getFieldsValue(!0);await Ot(J,{showMessage:!1,throwOnError:!0}),await gt({showMessage:!1,throwOnError:!0})}ee("success"),n.success(e("settings.providerTab.reasoningEffortUpdated"))}catch(J){const N=ye(J);ee("error"),Ie(N),n.error(N?`${e("settings.providerTab.updateReasoningEffortErrorPrefix")}: ${N}`:e("settings.providerTab.updateReasoningEffortFailed"))}}},ds=(x,T)=>{if(!x)return null;const J=V(x)||x,N=a.getFieldValue(["providers",x,"reasoning_effort"]),q=(T==null?void 0:T.emphasis)==="subtle",ue=(T==null?void 0:T.label)||e("settings.providerTab.reasoningEffortOptional"),de=(T==null?void 0:T.helperText)||e("settings.providerTab.reasoningEffortHelp");return t.jsx("div",{style:{marginTop:(T==null?void 0:T.marginTop)??8,width:"100%"},children:t.jsxs(F,{direction:"vertical",size:q?6:4,style:{width:"100%"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,flexWrap:"wrap"},children:[t.jsx(Je,{strong:!q,type:q?"secondary":void 0,style:q?{fontSize:s.fontSizeSM,lineHeight:1.4}:void 0,children:ue}),T!=null&&T.showProviderLabel?t.jsx(Je,{type:"secondary",style:{fontSize:s.fontSizeSM,lineHeight:1.4},children:J}):null]}),Et(e,{value:N,disabled:X==="saving",size:(T==null?void 0:T.size)??(q?"small":void 0),style:{width:"100%"},"data-testid":T==null?void 0:T.dataTestId,onChange:xe=>{a.setFieldValue(["providers",x,"reasoning_effort"],xe),T!=null&&T.autoSave&&Es(x,xe)}}),t.jsx(Je,{type:"secondary",style:q?{fontSize:s.fontSizeSM,lineHeight:1.5}:void 0,children:de})]})})},Ds=o.useCallback(x=>{const T=a.getFieldValue(["providers",x]);return T?x==="copilot"?(f==null?void 0:f.authenticated)??!1:!!T.api_key:!1},[a,f]),Ps=()=>{const x=J=>{const N=a.getFieldValue(["defaults",J]);return t.jsx(Sa,{value:N,dataTestId:`model-preference-${J}-picker`,appearance:"contrast",disabled:X==="saving",onChange:q=>{a.setFieldValue(["defaults",J],q),Ms(J,q)}})},T=(J,N,q)=>t.jsxs("div",{style:{width:"100%",display:"flex",alignItems:"flex-start",gap:s.marginLG,flexWrap:"wrap"},children:[t.jsx("div",{style:{flex:"1 1 420px",minWidth:0},children:t.jsxs(F,{direction:"vertical",size:8,style:{width:"100%"},children:[t.jsx(Je,{strong:!0,children:N}),x(J),q?t.jsx(Je,{type:"secondary",children:q}):null]})}),t.jsx("div",{style:{flex:"0 1 320px",minWidth:280},children:t.jsx(v.Item,{noStyle:!0,shouldUpdate:!0,children:()=>{const ue=a.getFieldValue(["defaults",J]),de=ue==null?void 0:ue.provider;return ds(de,{autoSave:!0,dataTestId:`model-preference-${J}-reasoning-effort`,label:e("settings.providerTab.reasoningEffortOptional"),helperText:e("settings.providerTab.reasoningEffortHelp"),marginTop:0,size:"small",emphasis:"subtle",showProviderLabel:!!de})}})})]});return t.jsxs(R,{size:"small",title:e("settings.providerTab.modelPreferences"),style:{marginBottom:16},children:[t.jsx(v.Item,{name:["defaults","chat"],noStyle:!0,preserve:!0,children:t.jsx(Mt,{})}),t.jsx(v.Item,{name:["defaults","fast"],noStyle:!0,preserve:!0,children:t.jsx(Mt,{})}),t.jsx(v.Item,{name:["defaults","task_summary"],noStyle:!0,preserve:!0,children:t.jsx(Mt,{})}),t.jsx(v.Item,{name:["defaults","memory_background"],noStyle:!0,preserve:!0,children:t.jsx(Mt,{})}),t.jsx(v.Item,{name:["defaults","sub_agent"],noStyle:!0,preserve:!0,children:t.jsx(Mt,{})}),t.jsx(v.Item,{name:["defaults","vision"],noStyle:!0,preserve:!0,children:t.jsx(Mt,{})}),t.jsxs(F,{direction:"vertical",size:16,style:{width:"100%"},children:[T("chat",e("settings.providerTab.defaultModel")),T("fast",e("settings.providerTab.fastModel"),e("settings.providerTab.fastModelHelp")),T("task_summary",e("settings.providerTab.taskSummaryModel"),e("settings.providerTab.taskSummaryModelHelp")),T("memory_background",e("settings.providerTab.memoryBackgroundModel"),e("settings.providerTab.memoryBackgroundModelHelp")),T("sub_agent",e("settings.providerTab.subAgentModel"),e("settings.providerTab.subAgentModelHelp")),T("vision",e("settings.providerTab.visionModel"),e("settings.providerTab.visionModelHelp"))]})]})},xt=x=>{const T=P.map(N=>N.name);return t.jsx(v.Item,{name:["providers",x,"request_overrides_json"],label:e("settings.providerTab.advancedRequestOverrides"),extra:t.jsxs(F,{direction:"vertical",size:4,children:[t.jsx(Je,{type:"secondary",children:e("settings.providerTab.advancedRequestOverridesHelp")}),t.jsxs(Je,{type:"secondary",children:[e("settings.providerTab.envVarInjection")," ",t.jsx(Je,{code:!0,children:'{ "type": "env_ref", "name": "YOUR_ENV_NAME" }'})]}),T.length>0&&t.jsx(F,{wrap:!0,size:[6,6],children:T.map(N=>t.jsx(le,{children:N},N))})]}),children:t.jsx(B.TextArea,{autoSize:{minRows:8,maxRows:20},placeholder:`{
4
+ "common": {
5
+ "headers": {
6
+ "x-request-id": { "type": "generated", "generator": "uuid" },
7
+ "x-tenant": { "type": "env_ref", "name": "TENANT_ID" }
8
+ }
9
+ },
10
+ "rules": [
11
+ {
12
+ "model_pattern": "gpt-5*",
13
+ "scope": {
14
+ "body_patch": [
15
+ { "path": "metadata.trace_id", "op": "set", "value": { "type": "generated", "generator": "uuid" } }
16
+ ]
17
+ }
18
+ }
19
+ ]
20
+ }`,style:{fontFamily:"SFMono-Regular, Menlo, Monaco, Consolas, monospace"}})})},Is=x=>{switch(x){case"openai":return t.jsxs(t.Fragment,{children:[t.jsx(v.Item,{name:["providers","openai","api_key"],label:e("settings.providerTab.openaiApiKey"),rules:[{required:!0,message:e("settings.providerTab.openaiApiKeyRequired")}],children:t.jsx(B.Password,{"data-testid":"api-key-input",placeholder:e("settings.providerTab.openaiApiKeyPlaceholder","sk-..."),prefix:t.jsx(yt,{})})}),t.jsx(v.Item,{name:["providers","openai","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.openaiBaseUrlHelp"),children:t.jsx(B,{placeholder:e("settings.providerTab.openaiBaseUrlPlaceholder","https://api.openai.com/v1")})}),t.jsx(v.Item,{name:["providers","openai","reasoning_effort"],label:e("settings.providerTab.reasoningEffortOptional"),extra:e("settings.providerTab.reasoningEffortHelp"),children:Et(e)}),t.jsx(v.Item,{name:["providers","openai","responses_only_models"],label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:qn(e),children:t.jsx(Y,{mode:"tags",placeholder:e("settings.providerTab.responsesOnlyModelsPlaceholder",'e.g. "gpt-5.3-codex", "gpt-5*"'),tokenSeparators:[","," ",`
21
+ `," "]})}),t.jsx(Re,{dashed:!0}),xt("openai")]});case"anthropic":return t.jsxs(t.Fragment,{children:[t.jsx(v.Item,{name:["providers","anthropic","api_key"],label:e("settings.providerTab.anthropicApiKey"),rules:[{required:!0,message:e("settings.providerTab.anthropicApiKeyRequired")}],children:t.jsx(Vn,{placeholder:e("settings.providerTab.anthropicApiKeyPlaceholder","sk-ant-..."),prefix:t.jsx(yt,{})})}),t.jsx(v.Item,{name:["providers","anthropic","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.anthropicBaseUrlHelp"),children:t.jsx(B,{placeholder:e("settings.providerTab.anthropicBaseUrlPlaceholder","https://api.anthropic.com/v1")})}),t.jsx(v.Item,{name:["providers","anthropic","max_tokens"],label:e("settings.providerTab.maxTokensOptional"),extra:e("settings.providerTab.maxTokensHelp"),children:t.jsx(B,{type:"number",placeholder:e("settings.providerTab.maxTokensPlaceholder","4096"),min:1,max:1e5})}),t.jsx(v.Item,{name:["providers","anthropic","reasoning_effort"],label:e("settings.providerTab.reasoningEffortOptional"),extra:e("settings.providerTab.reasoningEffortHelp"),children:Et(e)}),t.jsx(Re,{dashed:!0}),xt("anthropic")]});case"gemini":return t.jsxs(t.Fragment,{children:[t.jsx(v.Item,{name:["providers","gemini","api_key"],label:e("settings.providerTab.geminiApiKey"),rules:[{required:!0,message:e("settings.providerTab.geminiApiKeyRequired")}],children:t.jsx(Vn,{placeholder:e("settings.providerTab.geminiApiKeyPlaceholder","AIza..."),prefix:t.jsx(yt,{})})}),t.jsx(v.Item,{name:["providers","gemini","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.geminiBaseUrlHelp"),children:t.jsx(B,{placeholder:e("settings.providerTab.geminiBaseUrlPlaceholder","https://generativelanguage.googleapis.com/v1beta")})}),t.jsx(v.Item,{name:["providers","gemini","reasoning_effort"],label:e("settings.providerTab.reasoningEffortOptional"),extra:e("settings.providerTab.reasoningEffortHelp"),children:Et(e)}),t.jsx(Re,{dashed:!0}),xt("gemini")]});case"copilot":return t.jsxs(t.Fragment,{children:[t.jsxs(R,{size:"small",style:{marginBottom:16},title:e("settings.providerTab.authStatusTitle"),extra:w?t.jsx(Qt,{size:"small"}):f!=null&&f.authenticated?t.jsx(le,{icon:t.jsx(Ws,{}),color:"success",children:e("settings.providerTab.authenticated")}):t.jsx(le,{icon:t.jsx(fn,{}),color:"error",children:e("settings.providerTab.notAuthenticated")}),children:[(f==null?void 0:f.message)&&t.jsx(Bs,{type:"secondary",style:{marginBottom:16},children:f.message}),t.jsxs(F,{children:[f!=null&&f.authenticated?t.jsx(L,{danger:!0,icon:t.jsx(Ka,{}),onClick:me,loading:M,children:e("settings.providerTab.logoutCopilot")}):t.jsx(L,{type:"primary",icon:t.jsx(Zn,{}),onClick:Ke,loading:M,children:e("settings.providerTab.authenticateCopilot")}),t.jsx(L,{onClick:ke,loading:w,children:e("settings.providerTab.refreshStatus")})]})]}),t.jsx(v.Item,{name:["providers","copilot","headless_auth"],label:e("settings.providerTab.headlessAuth"),valuePropName:"checked",extra:e("settings.providerTab.headlessAuthHelp"),children:t.jsx(ge,{})}),t.jsx(v.Item,{name:["providers","copilot","reasoning_effort"],label:e("settings.providerTab.reasoningEffortOptional"),extra:e("settings.providerTab.reasoningEffortHelp"),children:Et(e)}),t.jsx(v.Item,{name:["providers","copilot","responses_only_models"],label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:qn(e),children:t.jsx(Y,{mode:"tags",placeholder:e("settings.providerTab.responsesOnlyModelsPlaceholder",'e.g. "gpt-5.3-codex", "gpt-5*"'),tokenSeparators:[","," ",`
22
+ `," "]})}),t.jsx(Re,{dashed:!0}),xt("copilot"),t.jsxs(Bs,{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(v.Item,{name:["providers","bodhi","api_key"],label:e("settings.providerTab.bodhiApiKey"),rules:[{required:!0,message:e("settings.providerTab.apiKeyRequired")}],children:t.jsx(B.Password,{"data-testid":"bodhi-api-key-input",placeholder:e("settings.providerTab.bodhiApiKeyPlaceholder","bhi_sk_..."),prefix:t.jsx(yt,{})})}),t.jsx(v.Item,{name:["providers","bodhi","base_url"],label:e("settings.providerTab.bodhiBaseUrl"),extra:e("settings.providerTab.bodhiBaseUrlExtra"),children:t.jsx(B,{placeholder:e("settings.providerTab.bodhiBaseUrlPlaceholder","http://localhost:8080")})}),t.jsx(v.Item,{name:["providers","bodhi","target_provider"],label:e("settings.providerTab.targetProvider"),extra:e("settings.providerTab.targetProviderExtra"),children:t.jsxs(Y,{placeholder:e("settings.providerTab.targetProviderPlaceholder","openai"),allowClear:!0,children:[t.jsx(Y.Option,{value:"openai",children:"OpenAI"}),t.jsx(Y.Option,{value:"anthropic",children:"Anthropic"}),t.jsx(Y.Option,{value:"gemini",children:"Gemini"})]})}),t.jsx(v.Item,{name:["providers","bodhi","reasoning_effort"],label:e("settings.providerTab.reasoningEffortOptional"),extra:e("settings.providerTab.reasoningEffortHelp"),children:Et(e)}),t.jsx(Re,{dashed:!0}),xt("bodhi")]});default:return null}},Nt=x=>{const T=Ds(x),J=ft[x];return t.jsxs(F,{size:"small",children:[t.jsx("span",{style:{fontWeight:500},children:J}),T?t.jsx(le,{color:"success",style:{fontSize:11},children:e("settings.providerTab.authenticated")}):t.jsx(le,{color:"default",style:{fontSize:11},children:e("settings.providerTab.providerNotConfigured")})]})};return t.jsxs(R,{title:e("settings.providerTab.title"),loading:r&&!u,className:"lotus-settings-card",children:[t.jsx(Bs,{type:"secondary",children:e("settings.providerTab.description")}),t.jsx(Re,{}),t.jsxs(v,{form:a,layout:"vertical",onFinish:Cs,disabled:r&&!u,children:[!he&&t.jsxs(t.Fragment,{children:[t.jsx(v.Item,{name:"provider",label:e("settings.providerTab.activeProvider"),rules:[{required:!0,message:e("settings.providerTab.selectProviderRequired")}],children:t.jsx(Y,{"data-testid":"provider-select",size:"large",onChange:x=>d(x),children:Object.keys(ft).map(x=>t.jsx(Y.Option,{value:x,children:ft[x]},x))})}),t.jsx(v.Item,{noStyle:!0,shouldUpdate:!0,children:()=>ds(a.getFieldValue("provider")||c,{autoSave:!0,size:"middle",marginTop:0,dataTestId:"active-provider-reasoning-effort",label:e("settings.providerTab.activeProviderReasoningEffort"),helperText:e("settings.providerTab.reasoningEffortHelp")})}),t.jsx(Re,{})]}),t.jsxs("div",{style:{marginBottom:16},children:[t.jsx(L,{icon:t.jsx(Rt,{}),onClick:Le,loading:I,children:e(I?"settings.providerTab.fetchingAllModels":"settings.providerTab.fetchAllModels")}),X==="saving"&&t.jsx(Qt,{size:"small",style:{marginLeft:8}}),X==="success"&&t.jsx(Ws,{style:{color:"var(--lotus-chart-secondary)",marginLeft:8}}),X==="error"&&t.jsx(Se,{title:Pe,children:t.jsx(fn,{style:{color:"var(--lotus-chart-danger)",marginLeft:8}})})]}),Ps(),he?t.jsx(jo,{instances:K,defaultInstanceId:W,onInstancesChanged:ze}):t.jsx(Ts,{activeKey:C,onChange:x=>G(Array.isArray(x)?x.map(String):x?[String(x)]:[]),ghost:!0,style:{marginBottom:16},items:hs.map(x=>({key:x,label:Nt(x),children:Is(x)}))}),t.jsx(Re,{}),t.jsx(F,{size:"middle",children:t.jsx(L,{"data-testid":"save-api-settings",type:"primary",htmlType:"submit",icon:t.jsx(js,{}),loading:r||l,size:"large",children:e("settings.providerTab.saveAndApply")})})]}),t.jsx(oa,{open:k,onCancel:()=>A(!1),onComplete:m,onCopyCode:re,completingAuth:te,copiedUserCode:h,deviceCodeInfo:b,timeRemaining:U,token:s})]})},{Text:Un}=ce,wo=({skill:e,disabled:s=!1,busy:n=!1,onToggleDisabled:a})=>{const{t:r}=se(),{token:i}=fe.useToken();return t.jsx(R,{title:t.jsxs(F,{size:i.marginXS,wrap:!0,style:{width:"100%",justifyContent:"space-between"},children:[t.jsxs(F,{size:i.marginXS,wrap:!0,children:[t.jsx("span",{children:e.name}),s&&t.jsx(le,{color:"default",children:r("components.skillManager.disabledTag")}),e.license&&t.jsxs(le,{color:"processing",children:["License: ",e.license]})]}),a&&t.jsx(ge,{checked:!s,loading:n,onChange:l=>a(e.id,!l),checkedChildren:r("components.skillManager.switchEnabled"),unCheckedChildren:r("components.skillManager.switchDisabled")})]}),styles:{body:{padding:i.paddingMD}},style:{opacity:s?.72:1},children:t.jsxs(F,{direction:"vertical",size:i.marginXS,style:{width:"100%"},children:[t.jsx(Un,{type:"secondary",children:e.description}),e.compatibility&&t.jsxs(Un,{type:"secondary",children:["Compatibility: ",e.compatibility]}),e.tool_refs.length>0&&t.jsx(F,{size:i.marginXXS,wrap:!0,children:e.tool_refs.map(l=>t.jsx(le,{style:{background:i.colorFillSecondary,borderColor:i.colorBorderSecondary,color:i.colorText},children:l},l))})]})})},Co=3e4,Mo=()=>{const{t:e}=se(),{message:s}=Ft.useApp(),n=ht(z=>z.config),a=ht(z=>z.loadConfig),r=ht(z=>z.saveConfig),[i,l]=o.useState([]),[p,c]=o.useState(!1),[d,u]=o.useState(null),[j,f]=o.useState(null),[S,w]=o.useState(""),[g,M]=o.useState(new Date),_=o.useMemo(()=>{var z;return new Set((((z=n==null?void 0:n.skills)==null?void 0:z.disabled)??[]).map(U=>U.trim()).filter(Boolean))},[n]),b=o.useCallback(async(z=!0)=>{c(!0),u(null);try{const[U]=await Promise.all([_a.listSkills({includeDisabled:!0},z),a({force:z})]);l(U.skills),M(new Date)}catch(U){const Z=U instanceof Error?U.message:e("components.skillManager.loadFailed");u(Z)}finally{c(!1)}},[a,e]);o.useEffect(()=>{b(!0);const z=setInterval(()=>{b(!0)},Co);return()=>clearInterval(z)},[b]),o.useEffect(()=>{const z=()=>{b(!0)};return window.addEventListener("focus",z),()=>window.removeEventListener("focus",z)},[b]);const D=o.useCallback(async()=>{await b(!0),s.success(e("components.skillManager.skillsRefreshed"))},[b,e]);o.useEffect(()=>{d&&(s.error(d),u(null))},[d]);const k=o.useCallback(async(z,U)=>{var Z;f(z);try{const h=await a({force:!0}),y=((Z=h==null?void 0:h.skills)==null?void 0:Z.disabled)??[],P=Array.from(new Set((U?[...y,z]:y.filter(E=>E!==z)).map(E=>E.trim()).filter(Boolean))).sort();await r({...h??{},skills:{...(h==null?void 0:h.skills)??{},disabled:P}}),s.success(e("components.skillManager.skillStateSaved"))}catch(h){s.error(h instanceof Error?h.message:e("components.skillManager.saveFailed"))}finally{f(null)}},[a,r,e]),A=i.filter(z=>{const U=S.trim().toLowerCase();return!(U&&![z.name,z.description,z.license??"",z.compatibility??"",...z.tool_refs].join(" ").toLowerCase().includes(U))}),te=()=>{const U=new Date().getTime()-g.getTime(),Z=Math.floor(U/1e3);if(Z<5)return e("components.skillManager.justNow");if(Z<60)return e("components.skillManager.secondsAgo",{count:Z});const h=Math.floor(Z/60);return h<60?e("components.skillManager.minutesAgo",{count:h}):g.toLocaleTimeString()};return t.jsx("div",{style:{padding:"24px"},children:t.jsxs(R,{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(L,{icon:t.jsx(Rt,{spin:p}),onClick:D,loading:p,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:te()})})]}),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(Ge,{style:{marginBottom:"24px"},children:t.jsx(B,{placeholder:e("components.skillManager.searchPlaceholder"),prefix:t.jsx(Wa,{}),value:S,onChange:z=>w(z.target.value),allowClear:!0})}),t.jsx(Qt,{spinning:p,children:A.length===0?t.jsx(Ue,{description:e(S?"components.skillManager.noMatch":"components.skillManager.noSkillsFound")}):t.jsx(et,{grid:{gutter:16,xs:1,sm:2,md:3,lg:3,xl:4},dataSource:A,renderItem:z=>t.jsx(et.Item,{children:t.jsx(wo,{skill:z,disabled:_.has(z.id),busy:j===z.id,onToggleDisabled:k})})})})]})})},{Title:Eo,Text:Us,Paragraph:Do}=ce,Hn="model_limits",Xs="modelLimitsConfigs",Kn="defaultBudgetStrategy",We=1e3;function Wn(e){return[{vendor:"OpenAI (GPT-5)",model_pattern:"gpt-5.4-thinking",max_context_tokens:1e6,max_output_tokens:128e3,safety_margin:We,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:We,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:We,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:We,note:e("settings.modelLimits.defaults.gpt5Mini")},{vendor:"OpenAI (Legacy)",model_pattern:"gpt-4.1",max_context_tokens:128e3,max_output_tokens:16384,safety_margin:We,note:e("settings.modelLimits.defaults.gpt41")},{vendor:"OpenAI (Legacy)",model_pattern:"gpt-4o",max_context_tokens:128e3,max_output_tokens:16e3,safety_margin:We,note:e("settings.modelLimits.defaults.gpt4o")},{vendor:"Google",model_pattern:"gemini-2.5-pro",max_context_tokens:128e3,max_output_tokens:16e3,safety_margin:We,note:e("settings.modelLimits.defaults.gemini25Pro")},{vendor:"Moonshot",model_pattern:"kimi-k2.5",max_context_tokens:256e3,max_output_tokens:64e3,safety_margin:We,note:e("settings.modelLimits.defaults.kimiK25")},{vendor:"Moonshot",model_pattern:"kimi-for-coding",max_context_tokens:256e3,max_output_tokens:64e3,safety_margin:We,note:e("settings.modelLimits.defaults.kimiCoding")},{vendor:"Zhipu",model_pattern:"glm-5",max_context_tokens:2e5,max_output_tokens:128e3,safety_margin:We,note:e("settings.modelLimits.defaults.glm5")}]}function Po(e){return Array.isArray(e)?nn(e):[]}function Gn(e,s){if(typeof e!="number"||!Number.isFinite(e))return s;const n=Math.floor(e);return n>0?n:s}function Io(e,s){if(typeof e!="number"||!Number.isFinite(e))return s;const n=Math.floor(e);return n>=0?n:s}function Fo(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=Gn(s.max_context_tokens??s.maxContextTokens,128e3),r=Gn(s.max_output_tokens??s.maxOutputTokens,Math.min(4096,Math.floor(a/4))),i=Io(s.safety_margin??s.safetyMargin,We);return{vendor:typeof s.vendor=="string"&&s.vendor.trim()?s.vendor.trim():"",model_pattern:n.trim(),max_context_tokens:a,max_output_tokens:r,safety_margin:i,note:typeof s.note=="string"?s.note:""}}function nn(e){return Array.isArray(e)?e.map(s=>Fo(s)).filter(s=>!!s):[]}function Ao(){const e=localStorage.getItem(Xs);if(!e)return[];try{const s=JSON.parse(e);return nn(s)}catch{return[]}}function Ro(e){const s=Object.prototype.hasOwnProperty.call(e,Hn);return s?{hasModelLimitsKey:s,modelLimits:nn(e[Hn])}:{hasModelLimitsKey:!1,modelLimits:[]}}function zo(e,s){if(e.length===0)return s("settings.modelLimits.validation.atLeastOneRow");const n=new Set;for(const a of e){const r=a.model_pattern.trim();if(!r)return s("settings.modelLimits.validation.modelPatternEmpty");const i=r.toLowerCase();if(n.has(i))return s("settings.modelLimits.validation.duplicateModelPattern",{pattern:r});if(n.add(i),a.max_context_tokens<1e3)return s("settings.modelLimits.validation.contextWindowMin",{pattern:r});if(a.max_output_tokens<1)return s("settings.modelLimits.validation.maxOutputMin",{pattern:r});if(a.max_output_tokens>a.max_context_tokens)return s("settings.modelLimits.validation.maxOutputExceedsContext",{pattern:r});if(a.safety_margin<0)return s("settings.modelLimits.validation.safetyMarginNegative",{pattern:r});if(a.safety_margin>=a.max_context_tokens)return s("settings.modelLimits.validation.safetyMarginTooLarge",{pattern:r})}return null}const Lo=()=>{const{t:e}=se(),[s,n]=o.useState(()=>Wn(e)),[a,r]=o.useState(!1),[i,l]=At.useMessage(),p=o.useCallback((g,M)=>{n(_=>_.map((b,D)=>D===g?{...b,...M}:b))},[]),c=o.useCallback(()=>{n(g=>[...g,{vendor:"",model_pattern:"",max_context_tokens:128e3,max_output_tokens:4096,safety_margin:We,note:""}])},[]),d=o.useCallback(g=>{n(M=>M.filter((_,b)=>b!==g))},[]),u=o.useCallback(async()=>{const g=Wn(e),M=await Ee.getModelLimitDefaults(),_=Po(M.model_limits);return _.length>0?_:g},[e]),j=o.useCallback(async()=>{r(!0);try{const g=await Ee.getBambooConfig(),{hasModelLimitsKey:M,modelLimits:_}=Ro(g);if(_.length>0){n(_);return}if(M){n(await u());return}const b=Ao();if(b.length>0){await Ee.setBambooConfig({model_limits:b}),localStorage.removeItem(Xs),localStorage.removeItem(Kn),n(b),i.info(e("settings.modelLimits.migratedFromLocalStorage"));return}n(await u())}catch(g){console.error("Failed to load model limits settings:",g),i.error(e("settings.modelLimits.loadFailed")),n(await u())}finally{r(!1)}},[u,i,e]);o.useEffect(()=>{j()},[j]);const f=async()=>{const g=zo(s,e);if(g){i.error(g);return}r(!0);try{await Ee.setBambooConfig({model_limits:s}),i.success(e("settings.modelLimits.saveSuccess"))}catch(M){console.error("Failed to save model limits settings:",M),i.error(e("settings.modelLimits.saveFailed"))}finally{r(!1)}},S=async()=>{r(!0);try{const g=await u();await Ee.setBambooConfig({model_limits:g}),n(g),localStorage.removeItem(Xs),localStorage.removeItem(Kn),i.success(e("settings.modelLimits.resetSuccess"))}catch(g){console.error("Failed to reset model limits settings:",g),i.error(e("settings.modelLimits.resetFailed"))}finally{r(!1)}},w=o.useMemo(()=>[{title:e("settings.modelLimits.columns.vendor"),dataIndex:"vendor",key:"vendor",width:170,render:(g,M,_)=>t.jsx(B,{value:g,placeholder:e("settings.modelLimits.placeholders.vendor"),onChange:b=>p(_,{vendor:b.target.value})})},{title:e("settings.modelLimits.columns.model"),dataIndex:"model_pattern",key:"model_pattern",width:220,render:(g,M,_)=>t.jsx(B,{value:g,placeholder:e("settings.modelLimits.placeholders.model"),onChange:b=>p(_,{model_pattern:b.target.value})})},{title:e("settings.modelLimits.columns.contextWindow"),dataIndex:"max_context_tokens",key:"max_context_tokens",width:180,render:(g,M,_)=>t.jsx(be,{value:g,onChange:b=>p(_,{max_context_tokens:Math.max(1e3,Number(b)||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:(g,M,_)=>t.jsx(be,{value:g,onChange:b=>p(_,{max_output_tokens:Math.max(1,Number(b)||4096)}),min:1,max:2e6,step:256,style:{width:"100%"}})},{title:e("settings.modelLimits.columns.notes"),dataIndex:"note",key:"note",width:240,render:(g,M,_)=>t.jsx(B,{value:g,placeholder:e("settings.modelLimits.placeholders.optional"),onChange:b=>p(_,{note:b.target.value})})},{title:e("settings.modelLimits.columns.actions"),key:"actions",width:100,render:(g,M,_)=>t.jsx(L,{danger:!0,size:"small",onClick:()=>d(_),children:e("settings.modelLimits.actions.remove")})}],[d,e,p]);return t.jsxs("div",{className:"model-limits-settings",children:[l,t.jsxs(R,{children:[t.jsx(Eo,{level:4,children:e("settings.modelLimits.title")}),t.jsxs(Do,{type:"secondary",children:[e("settings.modelLimits.descriptionPrefix")," ",t.jsx(Us,{code:!0,children:"config.json"})," ",e("settings.modelLimits.descriptionSuffix")]}),t.jsx(Re,{}),t.jsxs(F,{direction:"vertical",size:"small",style:{width:"100%"},children:[t.jsx(Us,{strong:!0,children:e("settings.modelLimits.defaultsTitle")}),t.jsx(Us,{type:"secondary",children:e("settings.modelLimits.defaultsDescription")})]}),t.jsx(dt,{dataSource:s,columns:w,rowKey:(g,M)=>`${g.model_pattern}-${M}`,pagination:!1,size:"small",style:{margin:"16px 0"},scroll:{x:1150}}),t.jsxs(F,{children:[t.jsx(L,{onClick:c,children:e("settings.modelLimits.actions.addRow")}),t.jsx(L,{type:"primary",icon:t.jsx(js,{}),onClick:()=>void f(),loading:a,children:e("settings.modelLimits.actions.save")}),t.jsx(L,{icon:t.jsx(Rt,{}),onClick:()=>void S(),loading:a,children:e("settings.modelLimits.actions.resetToDefaults")}),t.jsx(L,{onClick:()=>void j(),loading:a,children:e("settings.modelLimits.actions.reload")})]})]})]})},{Text:Hs}=ce,{useToken:Oo}=fe,No="bamboo_dark_mode",Yo=({themeMode:e,onThemeModeChange:s,locale:n,onLocaleChange:a,onBack:r})=>{const{t:i}=se(),{token:l}=Oo(),{deleteAllChats:p}=ar(),[c,d]=o.useState(!1),[u,j]=At.useMessage(),[f,S]=o.useState(""),[w,g]=o.useState(cn()),[M,_]=o.useState(dn()),[b,D]=o.useState(un()),[k,A]=o.useState(gn()),te=Qe(C=>C.currentProvider),U=Qe(C=>C.getProviderType)(te)==="copilot",Z=Ks(C=>C.activeTabKey),h=Ks(C=>C.setActiveTabKey),y=ka(C=>C.isAdvanced),P=l.paddingSM,E=(C,G)=>({key:C,label:t.jsx(Hs,{type:"secondary",style:{fontSize:11,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em",cursor:"default",userSelect:"none"},children:G}),disabled:!0,children:null}),I=(C,G)=>t.jsx("span",{"data-testid":`settings-tab-${C}`,children:G}),O=()=>{localStorage.clear(),u.success(i("settings.notifications.localStorageCleared"))},K=async()=>{d(!0);try{await p(),await Ee.resetSetupStatus(),await Ee.resetBambooConfig(),localStorage.clear(),u.success(i("settings.notifications.resetSuccessReloading")),setTimeout(()=>{window.location.reload()},1500)}catch(C){console.error("Failed to reset application:",C),u.error(C instanceof Error?C.message:i("settings.notifications.resetFailed")),d(!1)}},Q=()=>{Ma(f),u.success(i("settings.notifications.promptEnhancementSaved"))},W=C=>{g(C),Pa(C)},pe=C=>{_(C),Da(C)},he=C=>{D(C),Ea(C)},De=C=>{A(C),Ia(C),window.dispatchEvent(new Event("lotus-vdi-safe-mode-change")),u.success(C?i("settings.appTab.vdiSafeModeEnabled","Graphics compatibility mode enabled"):i("settings.appTab.vdiSafeModeDisabled","Graphics compatibility mode disabled"))};return o.useEffect(()=>{S(wa()),g(cn()),_(dn()),D(un()),A(gn())},[]),t.jsxs(H,{vertical:!0,role:"region","aria-label":i("settings.page.title"),style:{height:"100vh",overflow:"hidden",background:l.colorBgContainer},children:[j,t.jsxs(H,{align:"center",justify:"space-between",style:{padding:l.padding,paddingTop:l.padding+P,borderBottom:`1px solid ${l.colorBorderSecondary}`},children:[t.jsxs(H,{align:"center",gap:l.marginSM,children:[t.jsx(L,{icon:t.jsx(Ga,{}),onClick:r,"aria-label":i("settings.page.back"),children:i("settings.page.back")}),t.jsx(Hs,{strong:!0,"data-testid":"settings-page-title",children:i("settings.page.title")})]}),t.jsxs(Hs,{type:"secondary","data-testid":"settings-page-version",children:[i("settings.appTab.runningVersion","Running version"),": v",Jn]})]}),t.jsx(Ja.Content,{style:{flex:1,minHeight:0,overflow:"auto",padding:l.padding},children:t.jsx(xs,{tabPosition:"left",activeKey:Z,onChange:C=>h(C),items:[E("group-ai",i("settings.page.groups.ai")),{key:"provider",label:I("provider",i("settings.page.tabs.provider")),children:t.jsx(ko,{})},{key:"model-limits",label:I("model-limits",i("settings.page.tabs.modelLimits")),children:t.jsx(Lo,{})},{key:"prompts",label:I("prompts",i("settings.page.tabs.prompts")),children:t.jsx(xr,{promptEnhancement:f,onPromptEnhancementChange:S,mermaidEnhancementEnabled:w,taskEnhancementEnabled:M,showCopilotConclusionWithOptionsEnhancement:U,copilotConclusionWithOptionsEnhancementEnabled:b,onMermaidToggle:W,onTaskToggle:pe,onCopilotConclusionWithOptionsToggle:he,onSaveEnhancement:Q})},E("group-tools",i("settings.page.groups.toolsAndExtensions")),{key:"skills",label:I("skills",i("settings.page.tabs.skills")),children:t.jsx(Mo,{})},{key:"mcp",label:I("mcp",i("settings.page.tabs.mcp")),children:t.jsx(oi,{})},{key:"workflows",label:I("workflows",i("settings.page.tabs.workflows")),children:t.jsx(Dr,{})},{key:"hooks",label:I("hooks",i("settings.page.tabs.hooks")),children:t.jsx(eo,{})},E("group-security",i("settings.page.groups.securityAndPrivacy")),{key:"masking",label:I("masking",i("settings.page.tabs.masking")),children:t.jsx(Sr,{})},{key:"env-vars",label:I("env-vars",i("settings.page.tabs.envVars")),children:t.jsx(wr,{})},E("group-monitoring",i("settings.page.groups.monitoring")),{key:"metrics",label:I("metrics",i("settings.page.tabs.metrics")),children:t.jsx(Xi,{})},{key:"sessions",label:I("sessions",i("settings.page.tabs.sessions")),children:t.jsx(po,{})},E("group-system",i("settings.page.groups.system")),{key:"config",label:I("config",i("settings.page.tabs.config")),children:t.jsx(gr,{msgApi:u,locale:n,onLocaleChange:a})},{key:"schedules",label:I("schedules",i("settings.page.tabs.schedules")),children:t.jsx(mo,{})},{key:"notifications",label:I("notifications",i("settings.page.tabs.notifications","Notifications")),children:t.jsx(fo,{})},{key:"app",label:I("app",i("settings.page.tabs.app")),children:t.jsx(vr,{themeMode:e,onThemeModeChange:s,vdiSafeMode:k,onVdiSafeModeToggle:De,onClearLocalStorage:O,onResetApp:K,isResetting:c,darkModeKey:No})}].filter(C=>!(!y&&C.key&&Ca.has(C.key)||!y&&(C.key==="group-security"||C.key==="group-monitoring")))})})]})};export{Yo as SystemSettingsPage};