@bigduu/lotus 2026.7.7 → 2026.7.9

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 (67) hide show
  1. package/dist/assets/{App-CH_iNVyb.js → App-BbO6pZGu.js} +9 -9
  2. package/dist/assets/{MetricsService-DpXFjto6.js → MetricsService-C90ALhMS.js} +1 -1
  3. package/dist/assets/{SubAgentsPanel-DkdkzHTa.js → SubAgentsPanel-DfcoRpzb.js} +1 -1
  4. package/dist/assets/{architectureDiagram-3BPJPVTR-Pa9A_GeZ.js → architectureDiagram-3BPJPVTR-zn4WxqxE.js} +1 -1
  5. package/dist/assets/{blockDiagram-GPEHLZMM-BrTopsFG.js → blockDiagram-GPEHLZMM-Ch0Ziv1n.js} +1 -1
  6. package/dist/assets/{c4Diagram-AAUBKEIU-DolJWmm5.js → c4Diagram-AAUBKEIU-E8sZoNMD.js} +1 -1
  7. package/dist/assets/{chunk-2J33WTMH-DFRfsnwX.js → chunk-2J33WTMH-Bb08FhRS.js} +1 -1
  8. package/dist/assets/{chunk-4BX2VUAB-BRHfAH23.js → chunk-4BX2VUAB-CqoBM7mt.js} +1 -1
  9. package/dist/assets/{chunk-55IACEB6-Dpi6fPZs.js → chunk-55IACEB6-CuagtSth.js} +1 -1
  10. package/dist/assets/{chunk-727SXJPM-Cd5XWlyk.js → chunk-727SXJPM-BBevu2P-.js} +1 -1
  11. package/dist/assets/{chunk-AQP2D5EJ-DGcXnZoj.js → chunk-AQP2D5EJ-BoimMEmP.js} +1 -1
  12. package/dist/assets/{chunk-FMBD7UC4-DhZ0prpG.js → chunk-FMBD7UC4-Ds8zFWzV.js} +1 -1
  13. package/dist/assets/{chunk-ND2GUHAM-DL2nbZLb.js → chunk-ND2GUHAM-CWCqbI2E.js} +1 -1
  14. package/dist/assets/{chunk-QZHKN3VN-DalupEUz.js → chunk-QZHKN3VN--PEq4c1n.js} +1 -1
  15. package/dist/assets/classDiagram-4FO5ZUOK-Cb6_vGRW.js +1 -0
  16. package/dist/assets/classDiagram-v2-Q7XG4LA2-Cb6_vGRW.js +1 -0
  17. package/dist/assets/{cose-bilkent-S5V4N54A-CHX5fY5N.js → cose-bilkent-S5V4N54A-lHdLyyBT.js} +1 -1
  18. package/dist/assets/{dagre-BM42HDAG-B7351yll.js → dagre-BM42HDAG-DzbtYvED.js} +1 -1
  19. package/dist/assets/{diagram-2AECGRRQ-DMEhSoRB.js → diagram-2AECGRRQ-BF9kNVCU.js} +1 -1
  20. package/dist/assets/{diagram-5GNKFQAL-_oUgeGBQ.js → diagram-5GNKFQAL-BXcYsUYI.js} +1 -1
  21. package/dist/assets/{diagram-KO2AKTUF-GdRQxJvE.js → diagram-KO2AKTUF-Ca5AJNBH.js} +1 -1
  22. package/dist/assets/{diagram-LMA3HP47-CZNmi6mu.js → diagram-LMA3HP47-amJkFRYA.js} +1 -1
  23. package/dist/assets/{diagram-OG6HWLK6-CvCKP0Ao.js → diagram-OG6HWLK6-CaFeFER9.js} +1 -1
  24. package/dist/assets/{en-US-BHmVs299.js → en-US-BrF2u6up.js} +1 -1
  25. package/dist/assets/{erDiagram-TEJ5UH35-DnB_LGjj.js → erDiagram-TEJ5UH35-BxoOik0u.js} +1 -1
  26. package/dist/assets/{flowDiagram-I6XJVG4X-Cr8MwrRD.js → flowDiagram-I6XJVG4X-dkeiO2hH.js} +1 -1
  27. package/dist/assets/{ganttDiagram-6RSMTGT7-BuEAiskm.js → ganttDiagram-6RSMTGT7-CswVWiU9.js} +1 -1
  28. package/dist/assets/{gitGraphDiagram-PVQCEYII-DBy041Sw.js → gitGraphDiagram-PVQCEYII-Dd6AExxZ.js} +1 -1
  29. package/dist/assets/{index-Cur8quEC.js → index-B8CHauZa.js} +1 -1
  30. package/dist/assets/{index-DKcVOIn3.js → index-BQ68M6ks.js} +1 -1
  31. package/dist/assets/index-BR_Vstvx.js +22 -0
  32. package/dist/assets/{index-B-I26ShO.js → index-CA2bZRdR.js} +1 -1
  33. package/dist/assets/{index-Ccwc-6DE.js → index-CIy8jvyx.js} +1 -1
  34. package/dist/assets/{index-BKm-Y6g1.js → index-DCSLre-B.js} +1 -1
  35. package/dist/assets/{index-CpIxq-rS.js → index-Dh4pBGzl.js} +1 -1
  36. package/dist/assets/{index-CU7lQMqL.js → index-Duf3d-S6.js} +1 -1
  37. package/dist/assets/{index-CLzNVEbw.js → index-EeCSowUv.js} +1 -1
  38. package/dist/assets/{index-x60LEDTE.js → index-EgRLn-Uk.js} +1 -1
  39. package/dist/assets/{index-B4FC2zTb.js → index-LBYJ_hLj.js} +1 -1
  40. package/dist/assets/{index-BlKENLxs.js → index-TahpVE7K.js} +1 -1
  41. package/dist/assets/{infoDiagram-5YYISTIA-Cig6E2Y-.js → infoDiagram-5YYISTIA-D0lt97Qw.js} +1 -1
  42. package/dist/assets/{ishikawaDiagram-YF4QCWOH-BaU9GirD.js → ishikawaDiagram-YF4QCWOH-DlSHp01F.js} +1 -1
  43. package/dist/assets/{journeyDiagram-JHISSGLW-Bu7AjxgD.js → journeyDiagram-JHISSGLW-q9U7Sgre.js} +1 -1
  44. package/dist/assets/{kanban-definition-UN3LZRKU-BxTBoFam.js → kanban-definition-UN3LZRKU-BnNVlM7m.js} +1 -1
  45. package/dist/assets/{main-bnHa9vH1.js → main-Bra_iqhj.js} +3 -3
  46. package/dist/assets/{mindmap-definition-RKZ34NQL-9STdRJ65.js → mindmap-definition-RKZ34NQL-PSaSLfIp.js} +1 -1
  47. package/dist/assets/{pieDiagram-4H26LBE5-BhM8ytbm.js → pieDiagram-4H26LBE5-CnXe4K_Q.js} +1 -1
  48. package/dist/assets/{quadrantDiagram-W4KKPZXB-DlKlRsBQ.js → quadrantDiagram-W4KKPZXB-CPY889f9.js} +1 -1
  49. package/dist/assets/{requirementDiagram-4Y6WPE33-Qm51Houd.js → requirementDiagram-4Y6WPE33-2korUSK9.js} +1 -1
  50. package/dist/assets/{sankeyDiagram-5OEKKPKP-DPVIX2yw.js → sankeyDiagram-5OEKKPKP-VqQwHzkn.js} +1 -1
  51. package/dist/assets/{sequenceDiagram-3UESZ5HK-xE5cm0Ad.js → sequenceDiagram-3UESZ5HK-B-UbRHxC.js} +1 -1
  52. package/dist/assets/{stateDiagram-AJRCARHV-C9Mlf8x6.js → stateDiagram-AJRCARHV-DFaTkWDQ.js} +1 -1
  53. package/dist/assets/{stateDiagram-v2-BHNVJYJU-CeWi3ly8.js → stateDiagram-v2-BHNVJYJU-CnbekWW3.js} +1 -1
  54. package/dist/assets/{timeline-definition-PNZ67QCA-CVzX8KRM.js → timeline-definition-PNZ67QCA-CBk63lxT.js} +1 -1
  55. package/dist/assets/{vendor-charts-DMoAsaKk.js → vendor-charts-Bd0YvT0v.js} +1 -1
  56. package/dist/assets/{vendor-mermaid-BWwfm-Vj.js → vendor-mermaid-RKNJ-cQ7.js} +3 -3
  57. package/dist/assets/{vendor-pdf-D6AjS6qD.js → vendor-pdf-t6zJ6Yt2.js} +3 -3
  58. package/dist/assets/{vennDiagram-CIIHVFJN-BORIhifm.js → vennDiagram-CIIHVFJN-CfuV7x76.js} +1 -1
  59. package/dist/assets/{wardley-L42UT6IY-D3k90lJL.js → wardley-L42UT6IY-BNWzkDHh.js} +1 -1
  60. package/dist/assets/{wardleyDiagram-YWT4CUSO-iHR9JFh-.js → wardleyDiagram-YWT4CUSO-CZKpXhFc.js} +1 -1
  61. package/dist/assets/{xychartDiagram-2RQKCTM6-iBAl4dM9.js → xychartDiagram-2RQKCTM6-D97S91oO.js} +1 -1
  62. package/dist/assets/{zh-CN-CVIA9qJS.js → zh-CN-CVlaaAdZ.js} +1 -1
  63. package/dist/index.html +2 -2
  64. package/package.json +1 -1
  65. package/dist/assets/classDiagram-4FO5ZUOK-DG03s0su.js +0 -1
  66. package/dist/assets/classDiagram-v2-Q7XG4LA2-DG03s0su.js +0 -1
  67. package/dist/assets/index-BUO2Zcn6.js +0 -22
@@ -0,0 +1,22 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-B8CHauZa.js","./vendor-markdown-CARODNj-.js","./vendor-i18n-Dm-c3D_C.js","./vendor-antd-C-pjKgeW.js","./App-BbO6pZGu.js","./vendor-mermaid-RKNJ-cQ7.js","./main-Bra_iqhj.js","./main-B6snAd4S.css","./App-xovo7L2Z.css"])))=>i.map(i=>d[i]);
2
+ var yn=Object.defineProperty;var fn=(e,s,a)=>s in e?yn(e,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[s]=a;var da=(e,s,a)=>fn(e,typeof s!="symbol"?s+"":s,a);import{j as t}from"./vendor-markdown-CARODNj-.js";import{a as i,u as ne,R as ua,i as oe}from"./vendor-i18n-Dm-c3D_C.js";import{J as xn,u as We,b as bn,T as vn,g as jn,U as na,d as st,B as dt,V as Tn,W as yt,X as ze,Y as _n,Z as Sn,_ as kn,$ as wn,a0 as Za,a1 as ot,a2 as ce,H as ga,a as Ye,a3 as Qa,G as ra,m as Cn,l as Qs,q as Mn,a4 as En,a5 as ft,k as vs,a6 as Pn,a7 as Dn,a8 as ma,a9 as In,aa as pa,ab as ha,ac as ya,ad as fa,o as Fn,ae as An,A as Rn,af as zn,ag as Ln,ah as On,ai as Nn,aj as Vn}from"./App-BbO6pZGu.js";import{U as N,o as L,I as He,j as de,a9 as H,B as z,t as _e,a4 as f,a3 as rs,aI as Ts,aJ as se,aK as ye,aL as Me,J as Je,aM as Ge,aN as me,D as ke,aO as Ke,aP as $n,aG as Ne,Q as X,aQ as ws,aR as Bn,a6 as zt,a7 as Et,ao as qn,aS as Hn,A as gt,aT as Cs,p as ls,a5 as ut,x as ie,aU as xa,aV as at,a8 as Qe,Z as Un,aw as Lt,a2 as Ot,n as At,aW as Kn,an as Wn,aX as ba,aY as Oe,a0 as Ue,av as en,aZ as Gn,a_ as mt,a$ as Ee,y as Jn,b0 as va,b1 as Xn,X as Yn,z as ea,W as Zn,b2 as Qn,b3 as er,b4 as tn,b5 as xt,b6 as ja,b7 as tr,ah as sr,aC as ar,b8 as nr}from"./vendor-antd-C-pjKgeW.js";import{_ as ta}from"./vendor-mermaid-RKNJ-cQ7.js";import{r as rr}from"./onboardingStorage-BVcEpmTy.js";import"./main-Bra_iqhj.js";import{m as as}from"./MetricsService-C90ALhMS.js";import{R as Nt,B as ia,C as cs,X as ds,Y as us,T as Vt,L as oa,a as _s,b as sn,c as Rt,P as ir,d as or,e as lr}from"./vendor-charts-Bd0YvT0v.js";function cr(e){return e instanceof xn}function dr(){const{chats:e,currentSessionId:s,currentChat:a,addMessage:n,selectSession:r,deleteSession:o,deleteSessions:l,deleteMessage:u,updateSession:m,persistSessionTitle:g,pinSession:d,unpinSession:j,loadChats:x}=We(bn(C=>({chats:C.chats,currentSessionId:C.currentSessionId,currentChat:vn(C),addMessage:C.addMessage,selectSession:C.selectSession,deleteSession:C.deleteSession,deleteSessions:C.deleteSessions,deleteMessage:C.deleteMessage,updateSession:C.updateSession,persistSessionTitle:C.persistSessionTitle,pinSession:C.pinSession,unpinSession:C.unpinSession,loadChats:C.loadChats}))),S=We(jn(s)),y=i.useMemo(()=>(a==null?void 0:a.messages)||[],[a]),b=i.useMemo(()=>e.filter(C=>C.pinned),[e]),R=i.useMemo(()=>e.filter(C=>!C.pinned),[e]),P=e.length;return{chats:e,currentSessionId:s,currentChat:a,isProcessing:S,baseMessages:y,pinnedChats:b,unpinnedChats:R,chatCount:P,addMessage:n,deleteMessage:u,selectSession:r,deleteSession:o,deleteSessions:l,pinSession:d,unpinSession:j,updateSession:m,persistSessionTitle:g,loadChats:x}}function ur(e){const s=We(x=>x.addChat),a=We(x=>x.lastSelectedPromptId),n=We(x=>x.systemPrompts),r=na.getInstance(),o=i.useCallback(async(x,S)=>{var P,C;const y=n.find(I=>I.id===a),b=(y==null?void 0:y.id)||(n.length>0?((P=n.find(I=>I.id==="general_assistant"))==null?void 0:P.id)||n[0].id:""),R={title:x||"New Session",createdAt:Date.now(),messages:[],config:{systemPromptId:b,baseSystemPrompt:(y==null?void 0:y.content)||(n.length>0?((C=n.find(I=>I.id==="general_assistant"))==null?void 0:C.content)||n[0].content:""),lastUsedEnhancedPrompt:null,...st.getState().isProviderModelRefEnabled()?{model_ref:st.getState().selectedModelRef}:{}},...S};await s(R)},[s,a,n]),l=i.useCallback(async x=>{dt("[ChatOps]","[useChatOperations] createChatWithSystemPrompt started with prompt:",x);const S={title:`New Session - ${x.name}`,createdAt:Date.now(),messages:[],config:{systemPromptId:x.id,baseSystemPrompt:x.content,lastUsedEnhancedPrompt:null}};dt("[ChatOps]","[useChatOperations] Calling addChat with newChatData.config:",S.config),await s(S)},[s]),u=i.useCallback(x=>{const S=e.chats.find(y=>y.id===x);S&&(S.pinned?e.unpinSession(x):e.pinSession(x))},[e]),m=i.useCallback((x,S)=>{e.updateSession(x,{title:S})},[e]),g=i.useCallback(async()=>{await r.cleanupSessions("empty",!0),await We.getState().loadChats()},[r]),d=i.useCallback(async()=>{await r.cleanupSessions("all",!0),await We.getState().loadChats()},[r]),j=i.useCallback(async()=>{await r.cleanupSessions("all",!1),await We.getState().loadChats()},[r]);return{createNewChat:o,createChatWithSystemPrompt:l,toggleChatPin:u,updateChatTitle:m,deleteEmptyChats:g,deleteAllUnpinnedChats:d,deleteAllChats:j}}function gr(e,s){const a=i.useMemo(()=>e.baseMessages,[e.baseMessages]),n=i.useCallback(async()=>{var g;if(!e.currentSessionId||!e.currentChat)return;const r=[...e.baseMessages];if(r.length===0)return;const o=r[r.length-1];let l=r;if((o==null?void 0:o.role)==="assistant"){if(!(await e.deleteMessage(e.currentSessionId,o.id)).success)return;l=r.slice(0,-1)}const u=[...l].reverse().find(d=>d.role==="user");if(!u)return;const m="content"in u?u.content:u.displayText;typeof m=="string"&&await((g=s==null?void 0:s.onRetry)==null?void 0:g.call(s,m))},[e,s]);return{currentMessages:a,retryLastMessage:n}}const mr=()=>{const e=dr(),s=ur(e),a=Tn({sessionId:e.currentSessionId,addMessage:e.addMessage,updateSession:e.updateSession}),n=gr(e,{onRetry:a.sendMessage});return{chats:e.chats,currentSessionId:e.currentSessionId,currentChat:e.currentChat,pinnedChats:e.pinnedChats,unpinnedChats:e.unpinnedChats,chatCount:e.chatCount,currentMessages:n.currentMessages,agentAvailable:a.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:n.retryLastMessage,sendMessage:a.sendMessage,cancelMessage:a.cancel}},{Text:hs}=de,{useToken:pr}=_e,hr=({httpProxy:e,httpsProxy:s,onHttpProxyChange:a,onHttpsProxyChange:n,onReload:r,onSave:o,isLoading:l})=>{const{t:u}=ne(),{token:m}=pr(),g=yt(p=>p.proxyAuthStatus),d=yt(p=>p.isLoadingProxyAuthStatus),j=yt(p=>p.loadProxyAuthStatus),x=yt(p=>p.applyProxyAuth),S=yt(p=>p.clearProxyAuth),[y,b]=i.useState({username:"",password:""}),[R,P]=i.useState(!1);i.useEffect(()=>{j()},[j]);const C=async()=>{const p=y.username.trim();if(p){P(!0);try{await x({username:p,password:y.password}),b({username:"",password:""})}catch(k){console.error("Failed to apply proxy auth:",k)}finally{P(!1)}}},I=async()=>{P(!0);try{await S()}catch(p){console.error("Failed to clear proxy auth:",p)}finally{P(!1)}};return t.jsx(N,{size:"small",title:t.jsx(hs,{strong:!0,children:u("settings.networkCard.title")}),className:"lotus-settings-card",children:t.jsxs(L,{direction:"vertical",size:m.marginSM,style:{width:"100%"},children:[t.jsx(He,{message:u("settings.networkCard.guideTip"),type:"info",showIcon:!0}),t.jsxs(L,{direction:"vertical",size:m.marginXXS,style:{width:"100%"},children:[t.jsx(hs,{type:"secondary",children:u("settings.networkCard.httpProxy")}),t.jsx(H,{"data-testid":"proxy-url",style:{width:"100%"},value:e,onChange:p=>a(p.target.value),placeholder:u("settings.networkCard.proxyPlaceholder"),disabled:l})]}),t.jsxs(L,{direction:"vertical",size:m.marginXXS,style:{width:"100%"},children:[t.jsx(hs,{type:"secondary",children:u("settings.networkCard.httpsProxy")}),t.jsx(H,{style:{width:"100%"},value:s,onChange:p=>n(p.target.value),placeholder:u("settings.networkCard.proxyPlaceholder"),disabled:l})]}),t.jsx(N,{size:"small",title:u("settings.networkCard.proxyAuthTitle"),className:"lotus-settings-card",style:{marginTop:m.marginSM},children:g!=null&&g.configured?t.jsxs(L,{direction:"vertical",style:{width:"100%"},children:[t.jsx(He,{type:"success",message:u("settings.networkCard.proxyConfiguredForUser",{username:g.username??""}),showIcon:!0}),t.jsx(z,{onClick:I,loading:R||d,danger:!0,children:u("settings.networkCard.clearCredentials")})]}):t.jsxs(L,{direction:"vertical",size:m.marginXS,style:{width:"100%"},children:[t.jsx(H,{placeholder:u("settings.networkCard.username"),value:y.username,onChange:p=>b(k=>({...k,username:p.target.value}))}),t.jsx(H.Password,{placeholder:u("settings.networkCard.password"),value:y.password,onChange:p=>b(k=>({...k,password:p.target.value}))}),t.jsx(z,{type:"primary",onClick:C,loading:R||d,disabled:!y.username.trim(),children:u("settings.networkCard.apply")})]})}),t.jsx(hs,{type:"secondary",style:{fontSize:m.fontSizeSM},children:u("settings.networkCard.credentialsStorageNote")}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:m.marginSM},children:[t.jsx(z,{onClick:()=>Promise.resolve(r()).finally(()=>j({force:!0})),disabled:l,children:u("settings.networkCard.reload")}),t.jsx(z,{"data-testid":"save-proxy-settings",type:"primary",onClick:()=>Promise.resolve(o()).finally(()=>j({force:!0})),disabled:l,children:u("settings.networkCard.save")})]})]})})};function an(e){return typeof e=="object"&&e!==null&&"errorFields"in e}const{Text:yr}=de,{useToken:fr}=_e,xr=({msgApi:e})=>{const{t:s}=ne(),{token:a}=fr(),[n]=f.useForm(),[r,o]=i.useState(!1),[l,u]=i.useState(!1),[m,g]=i.useState(!1),[d,j]=i.useState(!1),[x,S]=i.useState(null),y=m&&!d,b=i.useMemo(()=>s(m?d?"settings.configTab.accessPassword.helperLocalBypass":"settings.configTab.accessPassword.helperRemote":"settings.configTab.accessPassword.helperNotEnabled"),[d,m,s]),R=i.useCallback(async()=>{o(!0),S(null);try{const C=await ze.getAccessStatus();g(C.password_enabled),j(C.local_bypass)}catch(C){const I=C instanceof Error?C.message:s("settings.configTab.accessPassword.loadStatusFailed","Failed to load access status");S(I)}finally{o(!1)}},[s]);i.useEffect(()=>{R()},[R]);const P=async()=>{var C;try{const I=await n.validateFields();u(!0),await ze.updateAccessPassword({current_password:((C=I.currentPassword)==null?void 0:C.trim())||void 0,new_password:I.newPassword.trim()}),e.success(s(m?"settings.configTab.accessPassword.updated":"settings.configTab.accessPassword.enabled")),n.resetFields(),await R()}catch(I){if(an(I))return;const p=I instanceof Error?I.message:s("settings.configTab.accessPassword.updateFailed","Failed to update access password");e.error(p)}finally{u(!1)}};return t.jsx(N,{size:"small",className:"lotus-settings-card",title:t.jsx(yr,{strong:!0,children:s("settings.configTab.accessPasswordTitle")}),children:t.jsxs(L,{direction:"vertical",size:a.marginMD,style:{width:"100%"},children:[t.jsx(He,{type:m?"info":"warning",showIcon:!0,message:s(m?"settings.configTab.accessPassword.statusEnabled":"settings.configTab.accessPassword.statusDisabled"),description:b}),x?t.jsx(He,{type:"error",showIcon:!0,message:x}):null,t.jsxs(f,{form:n,layout:"vertical",disabled:r||l,children:[y?t.jsx(f.Item,{label:s("settings.configTab.accessPassword.currentPasswordLabel"),name:"currentPassword",rules:[{required:!0,message:s("settings.configTab.accessPassword.validation.currentPasswordRequired")}],children:t.jsx(H.Password,{autoComplete:"current-password"})}):null,t.jsx(f.Item,{label:s(m?"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(H.Password,{autoComplete:"new-password"})}),t.jsx(f.Item,{label:s("settings.configTab.accessPassword.confirmPasswordLabel"),name:"confirmPassword",dependencies:["newPassword"],rules:[{required:!0,message:s("settings.configTab.accessPassword.validation.confirmPasswordRequired")},({getFieldValue:C})=>({validator(I,p){return!p||C("newPassword")===p?Promise.resolve():Promise.reject(new Error(s("settings.configTab.accessPassword.validation.passwordMismatch")))}})],children:t.jsx(H.Password,{autoComplete:"new-password"})}),t.jsx(z,{type:"primary",loading:l,onClick:()=>void P(),children:s(m?"settings.configTab.accessPassword.updateAction":"settings.configTab.accessPassword.enableAction")})]})]})})},{Text:qe}=de,{useToken:br}=_e,Ta="http://127.0.0.1:9562/v1",ts=e=>[...new Set(e.map(s=>s.trim()).filter(s=>s.length>0))].sort(),vr=e=>{var a;const s=(a=e.tools)==null?void 0:a.disabled;return Array.isArray(s)?ts(s.filter(n=>typeof n=="string")):[]},jr=({msgApi:e,locale:s,onLocaleChange:a})=>{const{t:n}=ne(),{token:r}=br(),[o,l]=i.useState({http_proxy:"",https_proxy:"",memory:{auto_dream_enabled:!1},subagents:{}}),[u,m]=i.useState(Ta),[g,d]=i.useState([]),[j,x]=i.useState([]),[S,y]=i.useState([]),[b,R]=i.useState(!1),[P,C]=i.useState(!1),I=i.useCallback(async()=>{var O,Q;R(!0);try{const[W,re]=await Promise.all([ze.getBambooConfig(),ze.getBambooTools()]);l({http_proxy:W.http_proxy||"",https_proxy:W.https_proxy||"",memory:{auto_dream_enabled:((O=W.memory)==null?void 0:O.auto_dream_enabled)??!1},subagents:{max_concurrent:(Q=W.subagents)==null?void 0:Q.max_concurrent}});const ue=vr(W);x(ue),y(ue),d(ts(re.tools||[]))}catch(W){console.error("Failed to load config:",W),e.error(n("settings.configTab.loadConfigFailed"))}finally{R(!1)}},[e,n]);i.useEffect(()=>{I()},[I]);const p=O=>{l(Q=>({...Q,http_proxy:O}))},k=O=>{l(Q=>({...Q,https_proxy:O}))},V=O=>{l(Q=>({...Q,memory:{...Q.memory,auto_dream_enabled:O}}))},F=O=>{l(Q=>({...Q,subagents:{...Q.subagents,max_concurrent:O!==null&&Number.isFinite(O)&&O>0?O:void 0}}))},U=async O=>{var Q,W;R(!0);try{let re;O==="network"?re={http_proxy:o.http_proxy,https_proxy:o.https_proxy}:O==="memory"?re={memory:{auto_dream_enabled:o.memory.auto_dream_enabled}}:re={subagents:{max_concurrent:o.subagents.max_concurrent}};const ue=await ze.validateBambooConfigPatch(re);if(!ue.valid){const c=((W=(Q=ue.errors)==null?void 0:Q.proxy)==null?void 0:W[0])??Object.values(ue.errors||{}).flat().filter(Boolean)[0];e.error((c==null?void 0:c.message)||n("settings.configTab.invalidConfig"));return}await ze.setBambooConfig(re),e.success(n("settings.configTab.saveConfigSuccess"))}catch(re){console.error("Failed to save config:",re);const ue=re instanceof Error&&re.message.trim()?re.message:n("settings.configTab.saveConfigFailed");e.error(ue)}finally{R(!1)}},ae=async()=>{e.success(n("settings.configTab.backendSaved"))},q=()=>{m(Ta),e.success(n("settings.configTab.backendResetDefault"))},v=(O,Q)=>{x(W=>{const re=new Set(W);return Q?re.delete(O):re.add(O),ts([...re])})},T=async()=>{C(!0);try{const O=await ze.getBambooTools();d(ts(O.tools||[])),e.success(n("settings.configTab.toolsReloadSuccess"))}catch(O){console.error("Failed to reload tools:",O),e.error(n("settings.configTab.toolsLoadFailed"))}finally{C(!1)}},D=async()=>{C(!0);try{const O=ts(j);await ze.setBambooConfig({tools:{disabled:O}}),x(O),y(O),e.success(n("settings.configTab.toolsSaveSuccess"))}catch(O){console.error("Failed to save tool settings:",O),e.error(n("settings.configTab.toolsSaveFailed"))}finally{C(!1)}},A=JSON.stringify(j)!==JSON.stringify(S),ee=new Set(j);return t.jsx(rs,{spinning:b,tip:n("settings.common.loading"),children:t.jsx(Ts,{items:[{key:"general",label:n("settings.configTab.tabs.general"),children:t.jsxs(L,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[t.jsx(hr,{httpProxy:o.http_proxy,httpsProxy:o.https_proxy,onHttpProxyChange:p,onHttpsProxyChange:k,onReload:I,onSave:()=>U("network"),isLoading:b}),t.jsx(N,{size:"small",className:"lotus-settings-card",title:t.jsx(qe,{strong:!0,children:n("settings.configTab.language")}),children:t.jsx(se,{value:s,style:{width:260},options:[{label:n("settings.configTab.languageEnglish"),value:"en-US"},{label:n("settings.configTab.languageChinese"),value:"zh-CN"},{label:n("settings.configTab.languageTraditionalChinese"),value:"zh-TW"},{label:n("settings.configTab.languageFrench"),value:"fr-FR"},{label:n("settings.configTab.languageJapanese"),value:"ja-JP"},{label:n("settings.configTab.languageHindi"),value:"hi-IN"}],onChange:O=>a(O)})}),t.jsx(N,{size:"small",className:"lotus-settings-card",title:t.jsx(qe,{strong:!0,children:n("settings.configTab.memoryTitle")}),children:t.jsxs(L,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[t.jsx(qe,{type:"secondary",children:n("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(qe,{strong:!0,children:n("settings.configTab.autoDreamEnabled")}),t.jsx("div",{children:t.jsx(qe,{type:"secondary",style:{fontSize:r.fontSizeSM},children:n("settings.configTab.autoDreamEnabledHint")})})]}),t.jsx(ye,{"data-testid":"auto-dream-toggle",checked:o.memory.auto_dream_enabled,onChange:V})]}),t.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:t.jsx(z,{"data-testid":"save-memory-settings",type:"primary",onClick:()=>U("memory"),loading:b,children:n("settings.configTab.save")})})]})}),t.jsx(N,{size:"small",className:"lotus-settings-card",title:t.jsx(qe,{strong:!0,children:n("settings.configTab.subagentsTitle")}),children:t.jsxs(L,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[t.jsx(qe,{type:"secondary",children:n("settings.configTab.subagentsDescription")}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:r.marginMD,flexWrap:"wrap"},children:[t.jsxs("div",{children:[t.jsx(qe,{strong:!0,children:n("settings.configTab.subagentMaxConcurrent")}),t.jsx("div",{children:t.jsx(qe,{type:"secondary",style:{fontSize:r.fontSizeSM},children:n("settings.configTab.subagentMaxConcurrentHint")})})]}),t.jsx(Me,{"data-testid":"subagent-max-concurrent",style:{width:120},min:1,step:1,precision:0,placeholder:"8",value:o.subagents.max_concurrent??null,onChange:O=>F(typeof O=="number"?O:null)})]}),t.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:t.jsx(z,{"data-testid":"save-subagent-settings",type:"primary",onClick:()=>U("subagents"),loading:b,children:n("settings.configTab.save")})})]})}),t.jsx(N,{size:"small",title:t.jsx(qe,{strong:!0,children:n("settings.configTab.backendApiBaseUrlTitle")}),children:t.jsxs(L,{direction:"vertical",size:r.marginSM,style:{width:"100%"},children:[t.jsx(L,{direction:"vertical",size:r.marginXXS,style:{width:"100%"},children:t.jsx(H,{style:{width:"100%"},value:u,onChange:O=>m(O.target.value),placeholder:n("settings.configTab.backendApiPlaceholder")})}),t.jsx(qe,{type:"secondary",style:{fontSize:r.fontSizeSM},children:n("settings.configTab.backendApiHint")}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:r.marginSM},children:[t.jsx(z,{"data-testid":"reset-to-defaults",onClick:q,children:n("settings.configTab.resetToDefault")}),t.jsx(z,{"data-testid":"save-api-settings",type:"primary",onClick:ae,children:n("settings.configTab.save")})]})]})}),t.jsx(xr,{msgApi:e})]})},{key:"tools",label:n("settings.configTab.tabs.tools"),children:t.jsx(N,{size:"small",title:t.jsx(qe,{strong:!0,children:n("settings.configTab.toolsTitle")}),children:t.jsxs(L,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[t.jsx(qe,{type:"secondary",children:n("settings.configTab.toolsDescription")}),g.length===0?t.jsx(He,{type:"info",showIcon:!0,message:n("settings.configTab.toolsEmpty")}):t.jsx(Je,{bordered:!0,dataSource:g,renderItem:O=>t.jsx(Je.Item,{actions:[t.jsx(ye,{checked:!ee.has(O),onChange:Q=>v(O,Q)},`${O}-switch`)],children:t.jsx(qe,{code:!0,children:O})})}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:r.marginSM},children:[t.jsx(z,{onClick:T,loading:P,children:n("settings.configTab.reloadTools")}),t.jsx(z,{type:"primary",onClick:D,loading:P,disabled:!A,children:n("settings.configTab.save")})]})]})})}]})})},{Title:Tr,Text:Ns}=de,{useToken:_r}=_e,Sr=()=>{const{t:e}=ne(),{token:s}=_r(),a=_n(),n=Sn(),r=kn(),[o]=f.useForm(),l=ua.useRef(a);ua.useEffect(()=>{l.current!==a&&(o.setFieldsValue(a),l.current=a)},[a,o]);const u=g=>{l.current={...l.current,...g},n(g)},m=()=>{r(),o.resetFields()};return t.jsxs("div",{style:{padding:"24px",maxWidth:"1200px",margin:"0 auto"},children:[t.jsx(Tr,{level:3,style:{marginBottom:"8px"},children:e("settings.mermaidTab.title")}),t.jsx(Ns,{type:"secondary",style:{display:"block",marginBottom:"24px"},children:e("settings.mermaidTab.description")}),t.jsxs(f,{form:o,layout:"vertical",initialValues:a,onValuesChange:u,children:[t.jsxs(N,{title:e("settings.mermaidTab.themeCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:[t.jsx(Ge,{gutter:16,children:t.jsx(me,{span:24,children:t.jsx(f.Item,{name:"theme",label:t.jsxs(L,{children:[e("settings.mermaidTab.themeLabel"),t.jsx(ke,{title:e("settings.mermaidTab.themeTooltip"),children:t.jsx(Ke,{style:{color:s.colorTextSecondary}})})]}),children:t.jsxs(se,{children:[t.jsx(se.Option,{value:"default",children:e("settings.mermaidTab.themeOptions.default")}),t.jsx(se.Option,{value:"neutral",children:e("settings.mermaidTab.themeOptions.neutral")}),t.jsx(se.Option,{value:"dark",children:e("settings.mermaidTab.themeOptions.dark")}),t.jsx(se.Option,{value:"forest",children:e("settings.mermaidTab.themeOptions.forest")}),t.jsx(se.Option,{value:"base",children:e("settings.mermaidTab.themeOptions.base")})]})})})}),t.jsxs(Ns,{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(N,{title:e("settings.mermaidTab.globalCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:[t.jsxs(Ge,{gutter:16,children:[t.jsx(me,{span:12,children:t.jsx(f.Item,{name:"fontSize",label:t.jsxs(L,{children:[e("settings.mermaidTab.fontSizeLabel"),t.jsx(ke,{title:e("settings.mermaidTab.fontSizeTooltip"),children:t.jsx(Ke,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:10,max:32,step:1,style:{width:"100%"},addonAfter:"px"})})}),t.jsx(me,{span:12,children:t.jsx(f.Item,{name:"defaultScale",label:t.jsxs(L,{children:[e("settings.mermaidTab.defaultZoomLabel"),t.jsx(ke,{title:e("settings.mermaidTab.defaultZoomTooltip"),children:t.jsx(Ke,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:.1,max:3,step:.1,style:{width:"100%"}})})})]}),t.jsx(f.Item,{name:"useMaxWidth",label:t.jsxs(L,{children:[e("settings.mermaidTab.responsiveWidthLabel"),t.jsx(ke,{title:e("settings.mermaidTab.responsiveWidthTooltip"),children:t.jsx(Ke,{style:{color:s.colorTextSecondary}})})]}),valuePropName:"checked",children:t.jsx(ye,{})})]}),t.jsx(N,{title:e("settings.mermaidTab.flowchartCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsxs(Ge,{gutter:16,children:[t.jsx(me,{span:8,children:t.jsx(f.Item,{name:"flowchartNodeSpacing",label:t.jsxs(L,{children:[e("settings.mermaidTab.flowchartNodeSpacingLabel"),t.jsx(ke,{title:e("settings.mermaidTab.flowchartNodeSpacingTooltip"),children:t.jsx(Ke,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:20,max:200,step:10,style:{width:"100%"}})})}),t.jsx(me,{span:8,children:t.jsx(f.Item,{name:"flowchartRankSpacing",label:t.jsxs(L,{children:[e("settings.mermaidTab.flowchartRankSpacingLabel"),t.jsx(ke,{title:e("settings.mermaidTab.flowchartRankSpacingTooltip"),children:t.jsx(Ke,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:20,max:200,step:10,style:{width:"100%"}})})}),t.jsx(me,{span:8,children:t.jsx(f.Item,{name:"flowchartCurve",label:t.jsxs(L,{children:[e("settings.mermaidTab.flowchartCurveTypeLabel"),t.jsx(ke,{title:e("settings.mermaidTab.flowchartCurveTypeTooltip"),children:t.jsx(Ke,{style:{color:s.colorTextSecondary}})})]}),children:t.jsxs(se,{children:[t.jsx(se.Option,{value:"basis",children:e("settings.mermaidTab.flowchartCurveOptions.basis")}),t.jsx(se.Option,{value:"linear",children:e("settings.mermaidTab.flowchartCurveOptions.linear")}),t.jsx(se.Option,{value:"cardinal",children:e("settings.mermaidTab.flowchartCurveOptions.cardinal")})]})})})]})}),t.jsx(N,{title:e("settings.mermaidTab.sequenceCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsxs(Ge,{gutter:16,children:[t.jsx(me,{span:6,children:t.jsx(f.Item,{name:"sequenceActorMargin",label:t.jsxs(L,{children:[e("settings.mermaidTab.sequenceActorMarginLabel"),t.jsx(ke,{title:e("settings.mermaidTab.sequenceActorMarginTooltip"),children:t.jsx(Ke,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:20,max:200,step:10,style:{width:"100%"}})})}),t.jsx(me,{span:6,children:t.jsx(f.Item,{name:"sequenceMessageMargin",label:t.jsxs(L,{children:[e("settings.mermaidTab.sequenceMessageMarginLabel"),t.jsx(ke,{title:e("settings.mermaidTab.sequenceMessageMarginTooltip"),children:t.jsx(Ke,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:10,max:100,step:5,style:{width:"100%"}})})}),t.jsx(me,{span:6,children:t.jsx(f.Item,{name:"sequenceWidth",label:t.jsxs(L,{children:[e("settings.mermaidTab.sequenceActorWidthLabel"),t.jsx(ke,{title:e("settings.mermaidTab.sequenceActorWidthTooltip"),children:t.jsx(Ke,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:100,max:300,step:10,style:{width:"100%"}})})}),t.jsx(me,{span:6,children:t.jsx(f.Item,{name:"sequenceHeight",label:t.jsxs(L,{children:[e("settings.mermaidTab.sequenceActorHeightLabel"),t.jsx(ke,{title:e("settings.mermaidTab.sequenceActorHeightTooltip"),children:t.jsx(Ke,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:40,max:150,step:5,style:{width:"100%"}})})})]})}),t.jsx(N,{title:e("settings.mermaidTab.ganttCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsxs(Ge,{gutter:16,children:[t.jsx(me,{span:12,children:t.jsx(f.Item,{name:"ganttBarHeight",label:t.jsxs(L,{children:[e("settings.mermaidTab.ganttBarHeightLabel"),t.jsx(ke,{title:e("settings.mermaidTab.ganttBarHeightTooltip"),children:t.jsx(Ke,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:10,max:50,step:5,style:{width:"100%"},addonAfter:"px"})})}),t.jsx(me,{span:12,children:t.jsx(f.Item,{name:"ganttTopPadding",label:t.jsxs(L,{children:[e("settings.mermaidTab.ganttTopPaddingLabel"),t.jsx(ke,{title:e("settings.mermaidTab.ganttTopPaddingTooltip"),children:t.jsx(Ke,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:20,max:100,step:10,style:{width:"100%"}})})})]})}),t.jsx(L,{children:t.jsx(z,{icon:t.jsx($n,{}),onClick:m,children:e("settings.mermaidTab.resetToDefaults")})}),t.jsx(Ne,{}),t.jsx(N,{title:e("settings.mermaidTab.previewTitle"),styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsx(Ns,{type:"secondary",children:e("settings.mermaidTab.previewDescription")})})]})]})},kr=i.lazy(()=>ta(()=>import("./index-B8CHauZa.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8]),import.meta.url)),{Text:jt}=de,{useToken:wr}=_e,Cr=({promptEnhancement:e,onPromptEnhancementChange:s,mermaidEnhancementEnabled:a,taskEnhancementEnabled:n,showCopilotConclusionWithOptionsEnhancement:r,copilotConclusionWithOptionsEnhancementEnabled:o,onMermaidToggle:l,onTaskToggle:u,onCopilotConclusionWithOptionsToggle:m,onSaveEnhancement:g})=>{const{t:d}=ne(),{token:j}=wr(),x=j.marginLG;return t.jsxs(X,{vertical:!0,gap:x,children:[t.jsx(N,{size:"small",className:"lotus-settings-card",children:t.jsx(i.Suspense,{fallback:t.jsx(rs,{size:"small"}),children:t.jsx(kr,{})})}),t.jsx(N,{size:"small",className:"lotus-settings-card",children:t.jsxs(L,{direction:"vertical",size:j.marginXS,style:{width:"100%"},children:[t.jsx(jt,{strong:!0,children:d("settings.promptsTab.title")}),t.jsxs(X,{align:"center",gap:j.marginSM,children:[t.jsx(jt,{strong:!0,children:d("settings.promptsTab.mermaidEnhancement")}),t.jsx(ye,{checked:a,onChange:l})]}),t.jsxs(X,{align:"center",gap:j.marginSM,children:[t.jsx(jt,{strong:!0,children:d("settings.promptsTab.taskListRules")}),t.jsx(ye,{checked:n,onChange:u})]}),r&&t.jsxs(L,{direction:"vertical",size:j.marginXXS,style:{width:"100%"},children:[t.jsxs(X,{align:"center",gap:j.marginSM,children:[t.jsx(jt,{strong:!0,children:d("settings.promptsTab.copilotConclusionWithOptionsBeforeFinish")}),t.jsx(ye,{checked:o,onChange:m})]}),t.jsx(jt,{type:"secondary",style:{fontSize:j.fontSizeSM},children:d("settings.promptsTab.copilotConclusionWithOptionsBeforeFinishDescription",{defaultValue:wn()})})]}),t.jsx(H.TextArea,{rows:6,placeholder:d("settings.promptsTab.enhancementPlaceholder"),value:e,onChange:S=>s(S.target.value)}),t.jsx(X,{justify:"flex-end",children:t.jsx(z,{type:"primary",onClick:g,children:d("settings.promptsTab.saveEnhancement")})}),t.jsx(jt,{type:"secondary",style:{fontSize:j.fontSizeSM},children:d("settings.promptsTab.description")})]})}),a&&t.jsx(ws,{size:"small",items:[{key:"mermaid",label:t.jsx(jt,{strong:!0,children:d("settings.mermaidTab.title")}),children:t.jsx(Sr,{})}]})]})},{Text:pt}=de,{useToken:Mr}=_e,Er=({themeMode:e,onThemeModeChange:s,vdiSafeMode:a,onVdiSafeModeToggle:n,onClearLocalStorage:r,onResetApp:o,isResetting:l,darkModeKey:u})=>{const{t:m}=ne(),{token:g}=Mr();return t.jsx(N,{size:"small",className:"lotus-settings-card",children:t.jsxs(L,{direction:"vertical",size:g.marginSM,style:{width:"100%"},children:[t.jsxs(X,{align:"center",justify:"space-between",gap:g.marginSM,children:[t.jsx(pt,{strong:!0,children:m("settings.appTab.runningVersion","Running version")}),t.jsxs(pt,{code:!0,"data-testid":"settings-app-version",children:["v",Za]})]}),t.jsx(pt,{type:"secondary",style:{fontSize:g.fontSizeSM},children:m("settings.appTab.runningVersionDesc","This is the currently running Lotus frontend version.")}),t.jsxs(X,{align:"center",gap:g.marginSM,children:[t.jsx(pt,{strong:!0,children:m("settings.appTab.darkMode")}),t.jsx(ye,{"data-testid":"dark-mode-toggle",checked:e==="dark",onChange:d=>{const j=d?"dark":"light";s(j),localStorage.setItem(u,j)}})]}),t.jsxs(X,{align:"center",gap:g.marginSM,children:[t.jsx(pt,{strong:!0,children:m("settings.appTab.vdiSafeMode","Graphics compatibility mode")}),t.jsx(ye,{"data-testid":"vdi-safe-mode-toggle",checked:a,onChange:n})]}),t.jsx(pt,{type:"secondary",style:{fontSize:g.fontSizeSM},children:m("settings.appTab.vdiSafeModeDesc","Disables blur and glass effects that can break dropdowns and hover overlays in some virtual desktop, remote, or graphics-constrained environments.")}),t.jsx(z,{block:!0,icon:t.jsx(Bn,{}),onClick:()=>{rr(),window.location.reload()},children:m("settings.appTab.resetStepReplayGuide")}),t.jsx(zt,{title:m("settings.appTab.clearLocalStorageTitle"),description:m("settings.appTab.clearLocalStorageDescription"),onConfirm:r,okText:m("settings.appTab.confirmClear"),cancelText:m("settings.appTab.cancel"),placement:"top",children:t.jsx(z,{danger:!0,block:!0,icon:t.jsx(Et,{}),children:m("settings.appTab.clearLocalStorageButton")})}),t.jsx(Ne,{style:{margin:`${g.marginSM}px 0`}}),t.jsxs(X,{align:"center",gap:g.marginSM,children:[t.jsx(qn,{style:{color:g.colorError}}),t.jsx(pt,{strong:!0,style:{color:g.colorError},children:m("settings.appTab.dangerZone")})]}),t.jsx(pt,{type:"secondary",style:{fontSize:g.fontSizeSM},children:m("settings.appTab.dangerDescription")}),t.jsx(zt,{title:m("settings.appTab.resetApplicationTitle"),description:t.jsxs("div",{children:[t.jsx("p",{children:m("settings.appTab.resetApplicationIntro")}),t.jsxs("ul",{style:{margin:0,paddingLeft:16},children:[t.jsx("li",{children:m("settings.appTab.resetStepDeleteAllSessions")}),t.jsx("li",{children:m("settings.appTab.resetStepClearStorage")}),t.jsx("li",{children:m("settings.appTab.resetStepResetConfig")}),t.jsx("li",{children:m("settings.appTab.resetStepSetupFlow")}),t.jsx("li",{children:m("settings.appTab.resetStepReload")})]})]}),onConfirm:o,okText:m("settings.appTab.resetConfirm"),cancelText:m("settings.appTab.cancel"),placement:"top",okButtonProps:{danger:!0},children:t.jsx(z,{"data-testid":"reset-to-defaults",danger:!0,block:!0,type:"primary",icon:t.jsx(Hn,{}),loading:l,children:m("settings.appTab.resetButton")})})]})})},{Text:Tt}=de,{useToken:Pr}=_e,_a=[{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,}"}],Dr=(e,s,a)=>{if(!s)return{masked:e};if(a==="exact")return{masked:e.split(s).join("[MASKED]")};try{const n=new RegExp(s,"g");return{masked:e.replace(n,"[MASKED]")}}catch(n){return{masked:e,error:n instanceof Error?n.message:oe.t("settings.keywordMaskingTab.invalidRegexPattern")}}},Ir=()=>{const{t:e}=ne(),{message:s}=gt.useApp(),{token:a}=Pr(),[n,r]=i.useState([]),[o,l]=i.useState(!1),[u,m]=i.useState(null),[g,d]=i.useState(""),[j,x]=i.useState("exact"),[S,y]=i.useState(!0),[b,R]=i.useState(),[P,C]=i.useState("My token is sk-123"),I=i.useCallback(async()=>{try{l(!0);const D=await ot.getInstance().getKeywordMaskingConfig();r(D.entries)}catch(T){s.error(e("settings.keywordMaskingTab.loadFailed")),console.error(T)}finally{l(!1)}},[s,e]);i.useEffect(()=>{I()},[I]);const p=async T=>{try{const D=ot.getInstance(),A=await D.validateKeywordEntries(T);if(!A.valid&&A.errors){const O=A.errors.map(Q=>`Entry ${Q.index+1}: ${Q.message}`).join("; ");return s.error(`${e("settings.keywordMaskingTab.validationFailedPrefix")}: ${O}`),!1}const ee=await D.updateKeywordMaskingConfig(T);return r(ee.entries),s.success(e("settings.keywordMaskingTab.saveSuccess")),!0}catch(D){return s.error(D instanceof Error?D.message:e("settings.keywordMaskingTab.saveFailed")),!1}},k=async()=>{const T={pattern:"",match_type:"exact",enabled:!0},D=[...n,T];r(D),m(D.length-1),d(""),x("exact"),y(!0),R(void 0)},V=T=>{const D=n[T];m(T),d(D.pattern),x(D.match_type),y(D.enabled),R(void 0)},F=async()=>{if(u===null)return;if(!g.trim()){s.error(e("settings.keywordMaskingTab.patternRequired"));return}const T=[...n];T[u]={pattern:g.trim(),match_type:j,enabled:S},await p(T)&&m(null)},U=()=>{var T;u!==null&&!((T=n[u])!=null&&T.pattern)&&r(n.filter((D,A)=>A!==u)),m(null)},ae=async T=>{const D=n.filter((A,ee)=>ee!==T);await p(D)},q=async(T,D)=>{const A=[...n];A[T]={...A[T],enabled:D},await p(A)},v=Dr(P,g,j);return t.jsx(N,{className:"lotus-settings-card",title:e("settings.keywordMaskingTab.title"),extra:t.jsx(z,{"data-testid":"add-keyword",type:"primary",icon:t.jsx(ut,{}),onClick:k,loading:o,children:e("settings.keywordMaskingTab.addKeyword")}),children:t.jsxs(L,{direction:"vertical",style:{width:"100%"},size:"large",children:[t.jsx(Tt,{type:"secondary",children:e("settings.keywordMaskingTab.description")}),t.jsx(Je,{loading:o,dataSource:n,locale:{emptyText:e("settings.keywordMaskingTab.empty")},renderItem:(T,D)=>t.jsx(Je.Item,{style:{backgroundColor:a.colorFillAlter,marginBottom:8,borderRadius:a.borderRadius,padding:12},actions:u===D?[t.jsx(z,{"data-testid":"save-keyword",type:"primary",icon:t.jsx(Cs,{}),onClick:F,"aria-label":e("settings.keywordMaskingTab.save")},"save"),t.jsx(z,{onClick:U,children:e("settings.keywordMaskingTab.cancel")},"cancel")]:[t.jsx(z,{icon:t.jsx(ls,{}),onClick:()=>V(D),"aria-label":e("settings.keywordMaskingTab.edit")},"edit"),t.jsx(z,{"data-testid":`delete-keyword-${D}`,danger:!0,icon:t.jsx(Et,{}),onClick:()=>ae(D),"aria-label":e("settings.keywordMaskingTab.delete")},"delete")],children:t.jsx(X,{vertical:!0,style:{width:"100%"},gap:8,children:u===D?t.jsxs(t.Fragment,{children:[t.jsx(H,{"data-testid":"keyword-pattern-input",placeholder:e("settings.keywordMaskingTab.patternPlaceholder"),value:g,onChange:A=>d(A.target.value),autoFocus:!0}),t.jsxs(X,{gap:8,align:"center",wrap:"wrap",children:[t.jsx(se,{"data-testid":"keyword-examples-select","aria-label":e("settings.keywordMaskingTab.examples"),placeholder:e("settings.keywordMaskingTab.examples"),value:b,onChange:A=>{R(A);const ee=_a.find(O=>O.value===A);ee&&(d(ee.pattern),x(ee.match_type))},options:_a.map(A=>({value:A.value,label:e(A.labelKey)})),style:{minWidth:220}}),t.jsx(se,{value:j,onChange:x,options:[{value:"exact",label:e("settings.keywordMaskingTab.exactMatch")},{value:"regex",label:e("settings.keywordMaskingTab.regexPattern")}],style:{width:150}}),t.jsx(ye,{checked:S,onChange:y})]}),t.jsxs(X,{vertical:!0,gap:6,children:[t.jsx(Tt,{type:"secondary",children:e("settings.keywordMaskingTab.sampleText")}),t.jsx(H,{placeholder:e("settings.keywordMaskingTab.sampleTextPlaceholder"),value:P,onChange:A=>C(A.target.value)}),t.jsx(Tt,{type:"secondary",children:e("settings.keywordMaskingTab.maskedPreview")}),t.jsx(H,{readOnly:!0,value:v.masked,status:v.error?"error":void 0}),v.error&&t.jsx(Tt,{type:"danger",children:v.error})]})]}):t.jsxs(X,{justify:"space-between",align:"center",children:[t.jsxs(X,{vertical:!0,gap:4,children:[t.jsx(Tt,{strong:!0,children:T.pattern||e("settings.keywordMaskingTab.emptyPattern")}),t.jsxs(X,{gap:8,children:[t.jsx(Tt,{type:"secondary",style:{fontSize:12},children:T.match_type==="regex"?e("settings.keywordMaskingTab.regexPattern"):e("settings.keywordMaskingTab.exactMatch")}),!T.enabled&&t.jsx(Tt,{type:"warning",style:{fontSize:12},children:e("settings.keywordMaskingTab.disabled")})]})]}),t.jsx(ye,{checked:T.enabled,onChange:A=>q(D,A),size:"small"})]})})})})]})})},{Text:Sa,Paragraph:Fr}=de,Ar=["Bash(rm -rf *)","Bash(git push *)","Bash(sudo *)","Write(/etc/**)"],Rr=()=>{const{t:e}=ne(),{message:s}=gt.useApp(),[a,n]=i.useState([]),[r,o]=i.useState(""),[l,u]=i.useState(!1),[m,g]=i.useState(!1),d=i.useCallback(async()=>{try{u(!0),n(await ce.getPermissionAskRules())}catch(y){s.error(e("settings.permissionsTab.loadFailed")),console.error(y)}finally{u(!1)}},[s,e]);i.useEffect(()=>{d()},[d]);const j=i.useCallback(async y=>{try{g(!0);const b=await ce.updatePermissionAskRules(y);return n(b),s.success(e("settings.permissionsTab.saveSuccess")),!0}catch(b){return s.error(b instanceof Error?b.message:e("settings.permissionsTab.saveFailed")),!1}finally{g(!1)}},[s,e]),x=i.useCallback(async y=>{const b=y.trim();if(!b)return;if(a.includes(b)){s.info(e("settings.permissionsTab.duplicate"));return}await j([...a,b])&&o("")},[a,j,s,e]),S=i.useCallback(y=>j(a.filter(b=>b!==y)),[a,j]);return t.jsx(N,{className:"lotus-settings-card",title:e("settings.permissionsTab.title"),extra:t.jsx(z,{type:"primary",icon:t.jsx(ut,{}),loading:m,disabled:!r.trim(),onClick:()=>void x(r),children:e("settings.permissionsTab.add")}),children:t.jsxs(L,{direction:"vertical",style:{width:"100%"},size:"large",children:[t.jsx(Fr,{type:"secondary",style:{marginBottom:0},children:e("settings.permissionsTab.description")}),t.jsx(H,{value:r,onChange:y=>o(y.target.value),onPressEnter:()=>void x(r),placeholder:e("settings.permissionsTab.placeholder"),allowClear:!0}),t.jsxs(X,{gap:8,wrap:"wrap",align:"center",children:[t.jsx(Sa,{type:"secondary",style:{fontSize:12},children:e("settings.permissionsTab.examples")}),Ar.map(y=>t.jsx(ie.CheckableTag,{checked:a.includes(y),onChange:()=>{a.includes(y)||x(y)},children:y},y))]}),t.jsx(Je,{loading:l,dataSource:a,locale:{emptyText:e("settings.permissionsTab.empty")},renderItem:y=>t.jsx(Je.Item,{actions:[t.jsx(z,{danger:!0,size:"small",icon:t.jsx(Et,{}),loading:m,onClick:()=>void S(y),"aria-label":e("settings.permissionsTab.remove")},"delete")],children:t.jsx(Sa,{code:!0,children:y})})})]})})},{Text:Dt,Paragraph:zr}=de,Lr=/^[A-Za-z_][A-Za-z0-9_]*$/,Or=()=>{const{t:e}=ne(),{message:s}=gt.useApp(),[a,n]=i.useState([]),[r,o]=i.useState(!1),[l,u]=i.useState(!1),[m,g]=i.useState(null),[d]=f.useForm(),j=i.useCallback(async()=>{o(!0);try{const C=await ce.getEnvVars();n(C.entries)}catch{s.error(e("settings.envVars.fetchError","Failed to load environment variables"))}finally{o(!1)}},[s,e]);i.useEffect(()=>{j()},[j]);const x=async C=>{var p;const I={name:C.name.trim(),value:C.value,secret:C.secret??!1,description:((p=C.description)==null?void 0:p.trim())||void 0};try{const k=await ce.upsertEnvVar(I);n(k.entries),s.success(m?e("settings.envVars.updated","Variable updated"):e("settings.envVars.created","Variable created")),R()}catch(k){s.error((k instanceof Error?k.message:void 0)||e("settings.envVars.saveError","Failed to save variable"))}},S=async C=>{try{const I=await ce.deleteEnvVar(C);n(I.entries),s.success(e("settings.envVars.deleted","Variable deleted"))}catch(I){s.error((I instanceof Error?I.message:void 0)||e("settings.envVars.deleteError","Failed to delete variable"))}},y=()=>{g(null),d.resetFields(),d.setFieldsValue({secret:!1}),u(!0)},b=C=>{g(C.name),d.setFieldsValue({name:C.name,value:"",secret:C.secret,description:C.description??""}),u(!0)},R=()=>{u(!1),g(null),d.resetFields()},P=[{title:e("settings.envVars.name","Name"),dataIndex:"name",key:"name",render:C=>t.jsx(Dt,{code:!0,children:C})},{title:e("settings.envVars.value","Value"),dataIndex:"value",key:"value",render:(C,I)=>I.secret?t.jsxs(Dt,{type:"secondary",children:[t.jsx(xa,{style:{marginRight:4}}),I.has_value?"••••••••":e("settings.envVars.notSet","(not set)")]}):t.jsx(Dt,{children:C||t.jsx(Dt,{type:"secondary",children:e("settings.envVars.empty","(empty)")})})},{title:e("settings.envVars.type","Type"),key:"secret",width:100,render:(C,I)=>I.secret?t.jsx(ie,{color:"warning",icon:t.jsx(xa,{}),children:e("settings.envVars.secret","Secret")}):t.jsx(ie,{color:"processing",children:e("settings.envVars.plain","Plain")})},{title:e("settings.envVars.descriptionCol","Description"),dataIndex:"description",key:"description",ellipsis:!0,render:C=>C?t.jsx(Dt,{type:"secondary",children:C}):t.jsx(Dt,{type:"secondary",italic:!0,children:"—"})},{title:e("settings.envVars.actions","Actions"),key:"actions",width:120,render:(C,I)=>t.jsxs(L,{size:"small",children:[t.jsx(z,{type:"text",size:"small",icon:t.jsx(ls,{}),onClick:()=>b(I),"aria-label":e("settings.envVars.edit","Edit")}),t.jsx(zt,{title:e("settings.envVars.deleteConfirm","Delete this variable?"),onConfirm:()=>S(I.name),okText:e("settings.envVars.yes","Yes"),cancelText:e("settings.envVars.no","No"),children:t.jsx(z,{type:"text",size:"small",danger:!0,icon:t.jsx(Et,{}),"aria-label":e("settings.envVars.delete","Delete")})})]})}];return t.jsxs("div",{style:{maxWidth:900},children:[t.jsxs(N,{className:"lotus-settings-card",title:e("settings.envVars.title","Environment Variables"),extra:t.jsx(z,{type:"primary",icon:t.jsx(ut,{}),onClick:y,children:e("settings.envVars.addButton","Add Variable")}),children:[t.jsx(zr,{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(at,{dataSource:a,columns:P,rowKey:"name",size:"small",pagination:!1,loading:r,locale:{emptyText:e("settings.envVars.noVars","No environment variables configured")}})]}),t.jsx(Qe,{title:m?e("settings.envVars.editTitle","Edit Variable"):e("settings.envVars.addTitle","Add Environment Variable"),open:l,onCancel:R,onOk:()=>d.submit(),okText:e("settings.envVars.save","Save"),cancelText:e("settings.envVars.cancel","Cancel"),destroyOnClose:!0,children:t.jsxs(f,{form:d,layout:"vertical",onFinish:x,initialValues:{secret:!1},children:[t.jsx(f.Item,{name:"name",label:e("settings.envVars.name","Name"),rules:[{required:!0,message:e("settings.envVars.nameRequired","Variable name is required")},{pattern:Lr,message:e("settings.envVars.nameInvalid","Must start with a letter or underscore, followed by letters, digits, or underscores")}],children:t.jsx(H,{placeholder:"GITHUB_TOKEN",disabled:m!==null,autoFocus:m===null})}),t.jsx(f.Item,{name:"value",label:e("settings.envVars.value","Value"),rules:[{required:m===null,message:e("settings.envVars.valueRequired","Value is required for new variables")}],extra:m?e("settings.envVars.valueEditHint","Leave empty to keep the existing value"):void 0,children:t.jsx(H.Password,{placeholder:m?e("settings.envVars.valuePlaceholderEdit","Enter new value or leave empty"):e("settings.envVars.valuePlaceholder","Enter value"),visibilityToggle:!0})}),t.jsx(f.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(ye,{})}),t.jsx(f.Item,{name:"description",label:e("settings.envVars.descriptionField","Description"),children:t.jsx(H,{placeholder:e("settings.envVars.descriptionPlaceholder","Optional description")})})]})})]})},{Text:Kt,Paragraph:Nr}=de,Vs="****...****",Vr={not_deployed:"default",deploying:"processing",running:"success",unreachable:"warning",stopped:"default",failed:"error"},$r=e=>{if(!e)return"";const s=new Date(e).getTime();if(Number.isNaN(s))return"";const a=Math.max(0,Math.floor((Date.now()-s)/1e3));if(a<60)return`${a}s ago`;const n=Math.floor(a/60);if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`},Br=3e4,qr=()=>{const{t:e}=ne(),{message:s}=gt.useApp(),[a,n]=i.useState([]),[r,o]=i.useState([]),[l,u]=i.useState(!1),[m,g]=i.useState(!1),[d,j]=i.useState(null),[x]=f.useForm(),[S,y]=i.useState(!1),[b,R]=i.useState(null),[P,C]=i.useState(""),[I,p]=i.useState(!1),k=f.useWatch("placement_type",x),V=f.useWatch("auth_method",x),F=i.useRef(0),U=i.useCallback(async(c=!1)=>{const E=++F.current;c||u(!0);try{const M=await ce.listNodes();if(E!==F.current)return;n(M.nodes),o(M.clusters)}catch{c||s.error(e("settings.clusters.fetchError","Failed to load clusters"))}finally{c||u(!1)}},[s,e]);i.useEffect(()=>{U()},[U]),i.useEffect(()=>{const c=()=>{document.visibilityState==="visible"&&!m&&!S&&U(!0)},E=window.setInterval(c,Br);return document.addEventListener("visibilitychange",c),()=>{window.clearInterval(E),document.removeEventListener("visibilitychange",c)}},[U,m,S]);const ae=i.useMemo(()=>{const c=new Map;for(const E of r)for(const M of E.node_ids)c.has(M)||c.set(M,E.name);return c},[r]),q=()=>{j(null),x.resetFields(),x.setFieldsValue({placement_type:"ssh",port:22,auth_method:"password",enabled:!0}),g(!0)},v=c=>{var G,Z,ge;j(c.id);const M=c.placement.type==="ssh"?c.placement:void 0;x.setFieldsValue({label:c.label,placement_type:c.placement.type,host:M==null?void 0:M.host,port:(M==null?void 0:M.port)??22,username:M==null?void 0:M.username,auth_method:(M==null?void 0:M.auth.method)??"password",password:"",private_key:"",private_key_path:(M==null?void 0:M.auth.method)==="private_key"?M.auth.private_key_path:void 0,passphrase:"",artifact_path:(G=c.deploy)==null?void 0:G.artifact_path,default_role:(Z=c.deploy)==null?void 0:Z.default_role,auto_recover:((ge=c.deploy)==null?void 0:ge.auto_recover)??!1,cluster_name:(()=>{const xe=ae.get(c.id);return xe?[xe]:[]})(),enabled:c.enabled}),g(!0)},T=()=>{g(!1),j(null),x.resetFields()},D=c=>{var ge,xe;if(c.placement_type==="local")return{type:"local"};const E=d?a.find(je=>je.id===d):void 0,M=(E==null?void 0:E.placement.type)==="ssh"?E.placement.auth:void 0,G=(je,$)=>!!je&&!$;let Z;if(c.auth_method==="system_ssh_config")Z={method:"system_ssh_config"};else if(c.auth_method==="private_key"){const je=(M==null?void 0:M.method)==="private_key"?M.private_key:void 0,$=(M==null?void 0:M.method)==="private_key"?M.passphrase:void 0;Z={method:"private_key",private_key:G(je,c.private_key)?Vs:c.private_key||void 0,private_key_path:c.private_key_path||void 0,passphrase:G($,c.passphrase)?Vs:c.passphrase||void 0}}else{const je=(M==null?void 0:M.method)==="password"?M.password:void 0;Z={method:"password",password:G(je,c.password)?Vs:c.password}}return{type:"ssh",host:((ge=c.host)==null?void 0:ge.trim())??"",port:c.port??22,username:((xe=c.username)==null?void 0:xe.trim())??"",auth:Z}},A=async c=>{var M,G;const E={label:c.label.trim(),placement:D(c),enabled:c.enabled??!0,deploy:{artifact_path:((M=c.artifact_path)==null?void 0:M.trim())||void 0,default_role:((G=c.default_role)==null?void 0:G.trim())||void 0,auto_recover:c.auto_recover??!1}};try{const Z=d?await ce.updateNode(d,E):await ce.createNode(E),ge=Array.isArray(c.cluster_name)?c.cluster_name[0]:c.cluster_name;try{await ee(Z.id,ge)}catch(xe){s.warning((xe instanceof Error?xe.message:void 0)||e("settings.clusters.membershipError","Node saved, but updating cluster membership failed")),T(),U();return}s.success(d?e("settings.clusters.updated","Node updated"):e("settings.clusters.created","Node created")),T(),U()}catch(Z){s.error((Z instanceof Error?Z.message:void 0)||e("settings.clusters.saveError","Failed to save node"))}},ee=async(c,E)=>{const M=E==null?void 0:E.trim();for(const Z of r){const ge=Z.name===M,xe=Z.node_ids.includes(c);!ge&&xe&&await ce.updateCluster(Z.name,{name:Z.name,description:Z.description,node_ids:Z.node_ids.filter(je=>je!==c)})}if(!M)return;const G=r.find(Z=>Z.name===M);G?G.node_ids.includes(c)||await ce.updateCluster(M,{name:M,description:G.description,node_ids:[...G.node_ids,c]}):await ce.createCluster({name:M,node_ids:[c]})},O=async c=>{try{await ce.deleteNode(c),s.success(e("settings.clusters.deleted","Node deleted")),U()}catch(E){s.error((E instanceof Error?E.message:void 0)||e("settings.clusters.deleteError","Failed to delete node"))}},Q=async(c,E)=>{try{const M=await ce.nodeAction(c,E),G=E==="test"&&M&&typeof M=="object"&&"preflight"in M?String(M.preflight??""):"";s.success(G?e("settings.clusters.testOk","Reachable: {{info}}",{info:G}):e("settings.clusters.actionOk","Action triggered")),U()}catch(M){s.error((M instanceof Error?M.message:void 0)||e("settings.clusters.actionFailed","Action failed"))}},W=async c=>{R(c),y(!0),p(!0),C("");try{const E=await ce.nodeLogs(c.id,200);C(E.logs||e("settings.clusters.logsEmpty","(no log output yet)"))}catch(E){C((E instanceof Error?E.message:void 0)||e("settings.clusters.logsError","Failed to read logs"))}finally{p(!1)}},re=[{title:e("settings.clusters.label","Label"),dataIndex:"label",key:"label",render:(c,E)=>t.jsxs(L,{children:[t.jsx(Un,{}),t.jsx(Kt,{strong:!0,children:c}),!E.enabled&&t.jsx(ie,{children:e("settings.clusters.disabled","disabled")})]})},{title:e("settings.clusters.target","Target"),key:"target",render:(c,E)=>E.placement.type==="ssh"?t.jsxs(Kt,{code:!0,children:[E.placement.username,"@",E.placement.host,":",E.placement.port]}):t.jsx(ie,{color:"blue",children:e("settings.clusters.local","local")})},{title:e("settings.clusters.cluster","Cluster"),key:"cluster",render:(c,E)=>{const M=ae.get(E.id);return M?t.jsx(ie,{children:M}):t.jsx(Kt,{type:"secondary",children:"—"})}},{title:e("settings.clusters.status","Status"),key:"status",render:(c,E)=>{var xe,je,$;const M=((xe=E.state)==null?void 0:xe.status)??"not_deployed",G=(je=E.state)==null?void 0:je.last_error,Z=$r(($=E.state)==null?void 0:$.last_health),ge=t.jsx(ie,{color:Vr[M],children:M.replace(/_/g," ")});return t.jsxs(L,{direction:"vertical",size:0,children:[G&&(M==="unreachable"||M==="failed")?t.jsx(ke,{title:G,children:ge}):ge,Z&&t.jsx(Kt,{type:"secondary",style:{fontSize:11},children:e("settings.clusters.lastSeen","seen {{ago}}",{ago:Z})})]})}},{title:e("settings.clusters.actions","Actions"),key:"actions",width:320,render:(c,E)=>t.jsxs(L,{size:"small",wrap:!0,children:[t.jsx(z,{size:"small",onClick:()=>Q(E.id,"test"),children:e("settings.clusters.test","Test")}),t.jsx(z,{size:"small",type:"primary",ghost:!0,onClick:()=>Q(E.id,"deploy"),children:e("settings.clusters.deploy","Deploy")}),t.jsx(z,{size:"small",onClick:()=>Q(E.id,"stop"),children:e("settings.clusters.stop","Stop")}),t.jsx(z,{size:"small",onClick:()=>W(E),children:e("settings.clusters.logs","Logs")}),t.jsx(z,{type:"text",size:"small",icon:t.jsx(ls,{}),onClick:()=>v(E),"aria-label":e("settings.clusters.edit","Edit")}),t.jsx(zt,{title:e("settings.clusters.deleteConfirm","Delete this node?"),onConfirm:()=>O(E.id),okText:e("settings.clusters.yes","Yes"),cancelText:e("settings.clusters.no","No"),children:t.jsx(z,{type:"text",size:"small",danger:!0,icon:t.jsx(Et,{}),"aria-label":e("settings.clusters.delete","Delete")})})]})}],ue=k!=="local",be=d?a.find(c=>c.id===d):void 0;return t.jsxs("div",{style:{maxWidth:1e3},children:[t.jsxs(N,{className:"lotus-settings-card",title:e("settings.clusters.title","Remote Clusters"),extra:t.jsx(z,{type:"primary",icon:t.jsx(ut,{}),onClick:q,children:e("settings.clusters.addButton","Add Node")}),children:[t.jsx(Nr,{type:"secondary",style:{marginBottom:16},children:e("settings.clusters.description","Register machines (local or over SSH) to deploy worker agents onto. SSH credentials are encrypted at rest and never sent to the agent. Deploy/Test/Stop are wired but the deploy engine ships in a later phase.")}),t.jsx(at,{dataSource:a,columns:re,rowKey:"id",size:"small",pagination:!1,loading:l,locale:{emptyText:e("settings.clusters.noNodes","No nodes registered")}})]}),t.jsx(Qe,{title:d?e("settings.clusters.editTitle","Edit Node"):e("settings.clusters.addTitle","Add Node"),open:m,onCancel:T,onOk:()=>x.submit(),okText:e("settings.clusters.save","Save"),cancelText:e("settings.clusters.cancel","Cancel"),width:560,destroyOnClose:!0,children:t.jsxs(f,{form:x,layout:"vertical",onFinish:A,children:[t.jsx(f.Item,{name:"label",label:e("settings.clusters.label","Label"),rules:[{required:!0,message:e("settings.clusters.labelRequired","Label is required")}],children:t.jsx(H,{placeholder:"gpu-1",autoFocus:!0})}),t.jsx(f.Item,{name:"placement_type",label:e("settings.clusters.placement","Placement"),children:t.jsx(se,{options:[{value:"ssh",label:e("settings.clusters.ssh","SSH (remote)")},{value:"local",label:e("settings.clusters.localhost","Local (this host)")}]})}),ue&&t.jsxs(t.Fragment,{children:[t.jsxs(L.Compact,{block:!0,children:[t.jsx(f.Item,{name:"host",label:e("settings.clusters.host","Host"),style:{width:"70%"},rules:[{required:!0,message:e("settings.clusters.hostRequired","Host is required")}],children:t.jsx(H,{placeholder:"10.0.0.5"})}),t.jsx(f.Item,{name:"port",label:e("settings.clusters.port","Port"),style:{width:"30%"},children:t.jsx(Me,{min:1,max:65535,style:{width:"100%"}})})]}),t.jsx(f.Item,{name:"username",label:e("settings.clusters.username","Username"),rules:[{required:!0,message:e("settings.clusters.usernameRequired","Username is required")}],children:t.jsx(H,{placeholder:"deploy"})}),t.jsx(f.Item,{name:"auth_method",label:e("settings.clusters.authMethod","Auth method"),children:t.jsx(se,{options:[{value:"password",label:e("settings.clusters.password","Password")},{value:"private_key",label:e("settings.clusters.privateKey","Private key")},{value:"system_ssh_config",label:e("settings.clusters.systemSsh","Use host's SSH config")}]})}),V==="password"&&t.jsx(f.Item,{name:"password",label:e("settings.clusters.password","Password"),extra:be?e("settings.clusters.secretEditHint","Leave empty to keep the existing secret"):void 0,rules:[{required:!be,message:e("settings.clusters.passwordRequired","Password is required")}],children:t.jsx(H.Password,{visibilityToggle:!0,placeholder:be?e("settings.clusters.keepSecret","Enter new password or leave empty"):void 0})}),V==="private_key"&&t.jsxs(t.Fragment,{children:[t.jsx(f.Item,{name:"private_key_path",label:e("settings.clusters.privateKeyPath","Private key file path (on this host)"),children:t.jsx(H,{placeholder:"~/.ssh/id_ed25519"})}),t.jsx(f.Item,{name:"private_key",label:e("settings.clusters.privateKeyInline","…or paste key (PEM)"),dependencies:["private_key_path"],extra:be?e("settings.clusters.secretEditHint","Leave empty to keep the existing secret"):void 0,rules:[{validator:async()=>{var G,Z;const c=(G=x.getFieldValue("private_key_path"))==null?void 0:G.trim(),E=(Z=x.getFieldValue("private_key"))==null?void 0:Z.trim();if(c||E)return;const M=(be==null?void 0:be.placement.type)==="ssh"?be.placement.auth:void 0;if(!((M==null?void 0:M.method)==="private_key"&&(M.private_key||M.private_key_path)))throw new Error(e("settings.clusters.privateKeyRequired","Provide a key file path or paste a private key"))}}],children:t.jsx(H.TextArea,{rows:3,placeholder:"-----BEGIN OPENSSH PRIVATE KEY-----"})}),t.jsx(f.Item,{name:"passphrase",label:e("settings.clusters.passphrase","Passphrase"),children:t.jsx(H.Password,{visibilityToggle:!0})})]})]}),t.jsx(f.Item,{name:"artifact_path",label:e("settings.clusters.artifactPath","Artifact path (binary to upload)"),extra:e("settings.clusters.artifactHint","Path on this host to the correct-arch bamboo binary; used at deploy time (P2)."),children:t.jsx(H,{placeholder:"/path/to/bamboo-linux-x64"})}),t.jsx(f.Item,{name:"default_role",label:e("settings.clusters.role","Default role"),children:t.jsx(H,{placeholder:"worker"})}),t.jsx(f.Item,{name:"auto_recover",label:e("settings.clusters.autoRecover","Auto-recover"),valuePropName:"checked",extra:e("settings.clusters.autoRecoverHint","Redeploy this node automatically if the health monitor finds its worker gone."),children:t.jsx(ye,{})}),t.jsx(f.Item,{name:"cluster_name",label:e("settings.clusters.cluster","Cluster"),children:t.jsx(se,{allowClear:!0,showSearch:!0,mode:"tags",maxCount:1,placeholder:e("settings.clusters.clusterPlaceholder","Pick or type a cluster name"),options:r.map(c=>({value:c.name,label:c.name}))})}),t.jsx(f.Item,{name:"enabled",label:e("settings.clusters.enabled","Enabled"),valuePropName:"checked",children:t.jsx(ye,{})})]})}),t.jsx(Qe,{title:e("settings.clusters.logsTitle","Logs — {{label}}",{label:(b==null?void 0:b.label)??""}),open:S,onCancel:()=>y(!1),onOk:()=>b&&W(b),okText:e("settings.clusters.refresh","Refresh"),cancelText:e("settings.clusters.close","Close"),width:760,destroyOnClose:!0,children:I?t.jsx(Kt,{type:"secondary",children:e("settings.clusters.loading","Loading…")}):t.jsx("pre",{style:{maxHeight:420,overflow:"auto",fontSize:12,whiteSpace:"pre-wrap",wordBreak:"break-all",margin:0},children:P})})]})},Ct=class Ct{constructor(){}static getInstance(){return Ct.instance||(Ct.instance=new Ct),Ct.instance}async listWorkflows(){try{dt("[WorkflowManager]","[WorkflowManagerService] Listing workflows");const s=await ga.get("bamboo/workflows"),a=Array.isArray(s)?s:[];return dt("[WorkflowManager]","[WorkflowManagerService] Listed workflows:",a),a.map(n=>({name:String(n.name||""),filename:String(n.filename||(n.name||"workflow")+".md"),size:Number(n.size||0),modified_at:typeof n.modified_at=="string"?n.modified_at:void 0,source:"global"}))}catch(s){throw console.error("[WorkflowManagerService] Failed to list workflows:",s),s}}async getWorkflow(s){try{dt("[WorkflowManager]","[WorkflowManagerService] Getting workflow: "+s);const a=await ga.get("bamboo/workflows/"+encodeURIComponent(s)),n=a!=null&&a.name?String(a.name):s,r={name:n,filename:String((a==null?void 0:a.filename)||n+".md"),size:Number((a==null?void 0:a.size)||0),modified_at:a==null?void 0:a.modified_at,source:"global"};return dt("[WorkflowManager]","[WorkflowManagerService] Got workflow:",a),{name:n,content:String((a==null?void 0:a.content)||""),metadata:r}}catch(a){throw console.error("[WorkflowManagerService] Failed to get workflow "+s+":",a),cr(a)&&a.status===404?new Error("Workflow '"+s+"' not found"):a instanceof Error&&a.message.includes("404")?new Error("Workflow '"+s+"' not found"):a}}};da(Ct,"instance");let sa=Ct;const{Text:$s}=de,{TextArea:Hr}=H,{useToken:Ur}=_e,Kr=e=>!(!e||e.includes("/")||e.includes("\\")||e.includes("..")),Wr=()=>{const{t:e}=ne(),{token:s}=Ur(),[a,n]=Lt.useMessage(),[r,o]=i.useState([]),[l,u]=i.useState(!1),[m,g]=i.useState(!1),[d,j]=i.useState(!1),[x,S]=i.useState(null),[y,b]=i.useState(""),[R,P]=i.useState(""),[C,I]=i.useState(!1),p=i.useMemo(()=>sa.getInstance(),[]),k=i.useCallback(async()=>{u(!0);try{const q=await p.listWorkflows();return o(q),q}catch{return a.error(e("settings.workflowsTab.loadFailed")),[]}finally{u(!1)}},[a,e,p]);i.useEffect(()=>{k()},[k]);const V=i.useCallback(async q=>{S(q),b(q.name),I(!1),g(!0);try{const v=await p.getWorkflow(q.name);P(v.content??"")}catch{a.error(e("settings.workflowsTab.loadContentFailed")),P("")}finally{g(!1)}},[a,e,p]),F=()=>{S(null),b(""),P(""),I(!1)},U=i.useCallback(async()=>{if(!Kr(y)){a.error(e("settings.workflowsTab.invalidName"));return}const q=r.some(v=>v.name===y);if(!x&&q){a.error(e("settings.workflowsTab.nameAlreadyExists"));return}j(!0);try{await ot.getInstance().saveWorkflow(y,R),a.success(e("settings.workflowsTab.saved")),I(!1);const D=(await k()).find(A=>A.name===y);D&&S(D)}catch(v){a.error(v instanceof Error?v.message:e("settings.workflowsTab.saveFailed"))}finally{j(!1)}},[R,y,k,a,x,e,r]),ae=i.useCallback(async q=>{try{await ot.getInstance().deleteWorkflow(q.name),a.success(e("settings.workflowsTab.deleted")),(x==null?void 0:x.name)===q.name&&F(),await k()}catch(v){a.error(v instanceof Error?v.message:e("settings.workflowsTab.deleteFailed"))}},[k,a,x,e]);return t.jsxs("div",{style:{padding:"24px"},children:[n,t.jsxs(N,{title:e("settings.workflowsTab.title"),extra:t.jsxs(L,{children:[t.jsx(z,{icon:t.jsx(Ot,{}),onClick:k,loading:l,children:e("settings.workflowsTab.refresh")}),t.jsx(z,{"data-testid":"create-workflow",icon:t.jsx(ut,{}),onClick:F,children:e("settings.workflowsTab.newWorkflow")}),t.jsx(z,{"data-testid":"save-workflow",type:"primary",icon:t.jsx(Cs,{}),onClick:U,loading:d,disabled:!C,children:e("settings.workflowsTab.save")})]}),children:[t.jsx($s,{type:"secondary",children:e("settings.workflowsTab.description")}),t.jsxs(X,{gap:s.marginLG,style:{marginTop:s.marginLG},children:[t.jsx("div",{style:{width:320,flexShrink:0},children:t.jsx(Je,{loading:l,dataSource:r,locale:{emptyText:e("settings.workflowsTab.empty")},renderItem:q=>t.jsx(Je.Item,{style:{cursor:"pointer",backgroundColor:(x==null?void 0:x.name)===q.name?s.colorFillSecondary:"transparent",borderRadius:s.borderRadius,padding:s.paddingSM},onClick:()=>V(q),actions:[t.jsx(z,{"data-testid":`delete-workflow-${q.name}`,type:"text",danger:!0,size:"small",icon:t.jsx(Et,{}),onClick:v=>{v.stopPropagation(),ae(q)},"aria-label":e("settings.workflowsTab.delete")},"delete")],children:t.jsxs(L,{direction:"vertical",size:0,children:[t.jsxs($s,{strong:!0,children:["/",q.name]}),t.jsx($s,{type:"secondary",style:{fontSize:12},children:q.filename})]})})})}),t.jsx("div",{style:{flex:1},children:t.jsxs(L,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(H,{"data-testid":"workflow-name",placeholder:e("settings.workflowsTab.namePlaceholder"),value:y,onChange:q=>{b(q.target.value),I(!0)},disabled:!!x,prefix:t.jsx(ls,{})}),t.jsx(Hr,{"data-testid":"workflow-content",placeholder:e("settings.workflowsTab.contentPlaceholder"),value:R,onChange:q=>{P(q.target.value),I(!0)},autoSize:{minRows:12},disabled:m})]})})]})]})]})};var J=(e=>(e.Connecting="connecting",e.Ready="ready",e.Degraded="degraded",e.Stopped="stopped",e.Error="error",e))(J||{});const gs=6e4,ms=3e4,is=2e4,Ss=1e4,Ms=e=>({id:e,enabled:!0,transport:{type:"stdio",command:"",args:[],env:{},startup_timeout_ms:is},request_timeout_ms:gs,healthcheck_interval_ms:ms,allowed_tools:[],denied_tools:[]}),Gr=()=>({status:"stopped",tool_count:0,restart_count:0}),Jr=e=>{switch(typeof e=="string"?e.trim().toLowerCase():""){case J.Connecting:return J.Connecting;case J.Ready:return J.Ready;case J.Degraded:return J.Degraded;case J.Error:return J.Error;case J.Stopped:default:return J.Stopped}},lt=(e,s)=>{if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const a=Number(e);if(Number.isFinite(a))return a}return s},Xr=(e,s)=>{if(!e||typeof e!="object")return s;const a=e;if(a.type==="sse"){const o=Array.isArray(a.headers)?a.headers.map(l=>{if(!l||typeof l!="object")return null;const u=l;return typeof u.name!="string"||typeof u.value!="string"?null:{name:u.name,value:u.value}}).filter(l=>!!l):[];return{type:"sse",url:typeof a.url=="string"?a.url:"",headers:o,connect_timeout_ms:lt(a.connect_timeout_ms,Ss)}}const n=Array.isArray(a.args)?a.args.filter(o=>typeof o=="string"):[],r=a.env&&typeof a.env=="object"?Object.entries(a.env):[];return{type:"stdio",command:typeof a.command=="string"?a.command:"",args:n,cwd:typeof a.cwd=="string"?a.cwd:void 0,env:r.reduce((o,[l,u])=>(typeof u=="string"&&(o[l]=u),o),{}),startup_timeout_ms:lt(a.startup_timeout_ms,is)}},Yr=(e,s)=>{const a=Ms(e.id),n=s??{};return{...a,...n,id:e.id,name:typeof n.name=="string"?n.name:typeof e.name=="string"?e.name:void 0,enabled:typeof e.enabled=="boolean"?e.enabled:typeof n.enabled=="boolean"?n.enabled:!0,request_timeout_ms:lt(n.request_timeout_ms,gs),healthcheck_interval_ms:lt(n.healthcheck_interval_ms,ms),allowed_tools:Array.isArray(n.allowed_tools)?n.allowed_tools.filter(o=>typeof o=="string"):[],denied_tools:Array.isArray(n.denied_tools)?n.denied_tools.filter(o=>typeof o=="string"):[],reconnect:n.reconnect&&typeof n.reconnect=="object"?{enabled:typeof n.reconnect.enabled=="boolean"?n.reconnect.enabled:!0,initial_backoff_ms:lt(n.reconnect.initial_backoff_ms,1e3),max_backoff_ms:lt(n.reconnect.max_backoff_ms,3e4),max_attempts:lt(n.reconnect.max_attempts,0)}:void 0,transport:Xr(n.transport,a.transport)}},Zr=e=>{const s=Gr(),n=e.runtime??{},r=n.status??e.status;return{status:Jr(r),last_error:typeof n.last_error=="string"?n.last_error:typeof e.last_error=="string"?e.last_error:void 0,connected_at:typeof n.connected_at=="string"?n.connected_at:void 0,disconnected_at:typeof n.disconnected_at=="string"?n.disconnected_at:void 0,tool_count:lt(n.tool_count??e.tool_count,s.tool_count),restart_count:lt(n.restart_count??e.restart_count,s.restart_count),last_ping_at:typeof n.last_ping_at=="string"?n.last_ping_at:void 0}},Qr=e=>{const s=Yr(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:Zr(e)}},ei=(e,s)=>`mcp__${e}__${s}`,ti=e=>{if(!e.startsWith("mcp__"))return null;const s=e.slice(5),a=s.indexOf("__");if(a<=0)return null;const n=s.slice(0,a),r=s.slice(a+2);return!n||!r?null:{server_id:n,original_name:r}},si=(e,s,a=0)=>{if(!e||typeof e!="object")return null;const n=e,r=typeof n.alias=="string"?n.alias:typeof n.name=="string"&&n.name.startsWith("mcp__")?n.name:void 0,o=r&&typeof r=="string"?ti(r):null,l=(typeof n.server_id=="string"?n.server_id:void 0)??(typeof n.serverId=="string"?n.serverId:void 0)??(o==null?void 0:o.server_id)??s??"",u=(typeof n.original_name=="string"?n.original_name:void 0)??(typeof n.originalName=="string"?n.originalName:void 0)??(o==null?void 0:o.original_name)??(typeof n.name=="string"?n.name:void 0)??"",m=r??(l&&u?ei(l,u):""),g=typeof n.description=="string"?n.description:"",d=n,j="parameters"in d?d.parameters:"inputSchema"in d?d.inputSchema:"input_schema"in d?d.input_schema:void 0,x=m||u||`mcp_tool_${a}`;return{alias:x,server_id:l||"unknown",original_name:u||x,description:g,parameters:j}};class ai{async getServers(){const s=await Ye.get("mcp/servers");return Array.isArray(s.servers)?s.servers.map(Qr):[]}async addServer(s){return Ye.post("mcp/servers",s)}async updateServer(s,a){const n={...a,id:s};return Ye.put(`mcp/servers/${s}`,n)}async deleteServer(s){return Ye.delete(`mcp/servers/${s}`)}async connectServer(s){return Ye.post(`mcp/servers/${s}/connect`)}async disconnectServer(s){return Ye.post(`mcp/servers/${s}/disconnect`)}async refreshTools(s){return Ye.post(`mcp/servers/${s}/refresh`)}async getTools(s){const a=s?`mcp/servers/${s}/tools`:"mcp/tools",n=await Ye.get(a);return(Array.isArray(n.tools)?n.tools:[]).map((o,l)=>si(o,s,l)).filter(o=>!!o)}async importServers(s){return Ye.post("mcp/servers/import",s)}}const nn=new ai,ni=5e3,rt=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,ka=(e,s)=>`${e}:${s}`,ri=(e={})=>{const{service:s=nn,autoRefreshMs:a=ni,autoRefreshEnabled:n=!0}=e,[r,o]=i.useState([]),[l,u]=i.useState(null),[m,g]=i.useState({}),[d,j]=i.useState({}),[x,S]=i.useState({}),[y,b]=i.useState(!1),[R,P]=i.useState(!1),[C,I]=i.useState(!1),[p,k]=i.useState(null),V=i.useRef({}),F=i.useCallback(c=>{const E=new Set(c.map(G=>G.id)),M=c.map(G=>{const ge=V.current[G.id]??G.config,xe={...ge,id:G.id,name:ge.name??G.name};return V.current[G.id]=xe,{...G,name:G.name||xe.name||G.id,enabled:G.enabled??xe.enabled,config:xe}});return Object.keys(V.current).forEach(G=>{E.has(G)||delete V.current[G]}),M},[]),U=i.useCallback(async({silent:c=!1}={})=>{c||b(!0);try{const E=await s.getServers(),M=F(E);o(M),u(G=>{var Z;return G&&M.some(ge=>ge.id===G)?G:((Z=M[0])==null?void 0:Z.id)??null}),k(null)}catch(E){throw k(rt(E,"Failed to load MCP servers")),E}finally{c||b(!1)}},[F,s]),ae=i.useCallback(async(c,E=!1)=>{if(!c)return[];if(!E&&m[c])return m[c];j(M=>({...M,[c]:!0}));try{const M=await s.getTools(c);return g(G=>({...G,[c]:M})),k(null),M}catch(M){throw k(rt(M,"Failed to load MCP tools")),M}finally{j(M=>({...M,[c]:!1}))}},[s,m]),q=i.useCallback((c,E,M)=>{const G=ka(c,E);S(Z=>({...Z,[G]:M}))},[]),v=i.useCallback(async c=>{P(!0);try{await s.addServer(c),V.current[c.id]=c,await U()}catch(E){throw k(rt(E,"Failed to add MCP server")),E}finally{P(!1)}},[U,s]),T=i.useCallback(async(c,E)=>{P(!0);try{const M={...E,id:c};await s.updateServer(c,M),V.current[c]=M,await U()}catch(M){throw k(rt(M,"Failed to update MCP server")),M}finally{P(!1)}},[U,s]),D=i.useCallback(async c=>{q(c,"delete",!0);try{await s.deleteServer(c),g(E=>{const M={...E};return delete M[c],M}),delete V.current[c],await U()}catch(E){throw k(rt(E,"Failed to delete MCP server")),E}finally{q(c,"delete",!1)}},[U,s,q]),A=i.useCallback(async c=>{q(c,"connect",!0);try{await s.connectServer(c),await U({silent:!0})}catch(E){throw k(rt(E,"Failed to connect MCP server")),E}finally{q(c,"connect",!1)}},[U,s,q]),ee=i.useCallback(async c=>{q(c,"disconnect",!0);try{await s.disconnectServer(c),await U({silent:!0})}catch(E){throw k(rt(E,"Failed to disconnect MCP server")),E}finally{q(c,"disconnect",!1)}},[U,s,q]),O=i.useCallback(async c=>{q(c,"refresh",!0);try{await s.refreshTools(c),await ae(c,!0),await U({silent:!0})}catch(E){throw k(rt(E,"Failed to refresh MCP tools")),E}finally{q(c,"refresh",!1)}},[ae,U,s,q]),Q=i.useCallback(async()=>{I(!0);try{const c=r.map(E=>E.id);await Promise.all(c.map(async E=>{try{await s.refreshTools(E)}catch{}})),await U(),l&&await ae(l,!0)}catch(c){throw k(rt(c,"Failed to refresh MCP status")),c}finally{I(!1)}},[ae,U,l,r,s]),W=i.useCallback(c=>{u(c)},[]),re=i.useCallback((c,E)=>!!x[ka(c,E)],[x]),ue=i.useMemo(()=>l?m[l]??[]:[],[l,m]),be=i.useMemo(()=>l?!!d[l]:!1,[l,d]);return i.useEffect(()=>{U().catch(()=>{})},[U]),i.useEffect(()=>{if(!n||a<=0)return;const c=window.setInterval(()=>{U({silent:!0}).catch(()=>{})},a);return()=>{window.clearInterval(c)}},[n,a,U]),i.useEffect(()=>{l&&ae(l).catch(()=>{})},[ae,l]),{servers:r,selectedServerId:l,selectedServerTools:ue,isLoadingServers:y,isMutatingConfig:R,isRefreshingAll:C,isSelectedServerToolsLoading:be,error:p,setSelectedServerId:W,refreshServers:U,addServer:v,updateServer:T,deleteServer:D,connectServer:A,disconnectServer:ee,refreshServerTools:O,refreshAll:Q,isServerActionLoading:re}},ii={[J.Connecting]:"blue",[J.Ready]:"green",[J.Degraded]:"orange",[J.Stopped]:"default",[J.Error]:"red"},oi=e=>e===J.Connecting||e===J.Ready||e===J.Degraded,li=e=>{if(!e)return;const s=e.replace(/\s+/g," ").trim();if(s)return s.length>180?`${s.slice(0,180)}...`:s},ci=({servers:e,loading:s=!1,selectedServerId:a,onSelectServer:n,onEditServer:r,onDeleteServer:o,onConnectServer:l,onDisconnectServer:u,onRefreshTools:m,isServerActionLoading:g})=>{const{t:d}=ne(),{token:j}=_e.useToken(),x=i.useMemo(()=>({[J.Connecting]:d("settings.mcpTab.statusHelp.connecting"),[J.Ready]:d("settings.mcpTab.statusHelp.ready"),[J.Degraded]:d("settings.mcpTab.statusHelp.degraded"),[J.Stopped]:d("settings.mcpTab.statusHelp.stopped"),[J.Error]:d("settings.mcpTab.statusHelp.error")}),[d]),S=i.useMemo(()=>[{key:"name",title:d("settings.mcpServerTable.columns.name"),render:(y,b)=>b.name||b.id},{key:"transport",title:d("settings.mcpServerTable.columns.transportType"),render:(y,b)=>b.config.transport.type==="sse"?d("settings.mcpServerTable.transportOptions.sse"):d("settings.mcpServerTable.transportOptions.stdio"),width:140},{key:"status",title:d("settings.mcpServerTable.columns.status"),render:(y,b)=>{var p,k;const R=((p=b.runtime)==null?void 0:p.status)??J.Stopped,P=li((k=b.runtime)==null?void 0:k.last_error),C=x[R],I={[J.Connecting]:d("settings.mcpTab.status.connecting"),[J.Ready]:d("settings.mcpTab.status.ready"),[J.Degraded]:d("settings.mcpTab.status.degraded"),[J.Stopped]:d("settings.mcpTab.status.stopped"),[J.Error]:d("settings.mcpTab.status.error")};return t.jsx(ke,{title:P?`${C} ${d("settings.mcpTab.statusLastError",{error:P})}`:C,children:t.jsx(ie,{color:R===J.Stopped?void 0:ii[R],style:{marginInlineEnd:0,cursor:"help",...R===J.Stopped?{background:j.colorFillSecondary,borderColor:j.colorBorderSecondary,color:j.colorTextSecondary}:void 0},children:I[R]})})},width:120},{key:"toolCount",title:d("settings.mcpServerTable.columns.toolCount"),render:(y,b)=>{var R;return((R=b.runtime)==null?void 0:R.tool_count)??0},width:100},{key:"actions",title:d("settings.mcpServerTable.columns.actions"),width:360,render:(y,b)=>{var C;const R=((C=b.runtime)==null?void 0:C.status)??J.Stopped,P=oi(R);return t.jsxs(L,{size:j.marginXS,children:[t.jsx(z,{size:"small",onClick:I=>{I.stopPropagation(),r==null||r(b)},children:d("settings.mcpServerTable.actions.edit")}),t.jsx(zt,{title:d("settings.mcpServerTable.deleteTitle"),description:d("settings.mcpServerTable.deleteDescription",{name:b.name||b.id}),onConfirm:()=>o==null?void 0:o(b),okText:d("settings.mcpServerTable.actions.delete"),okButtonProps:{danger:!0,loading:g==null?void 0:g(b.id,"delete")},children:t.jsx(z,{size:"small",danger:!0,loading:g==null?void 0:g(b.id,"delete"),onClick:I=>I.stopPropagation(),children:d("settings.mcpServerTable.actions.delete")})}),P?t.jsx(z,{size:"small",onClick:I=>{I.stopPropagation(),u==null||u(b)},loading:g==null?void 0:g(b.id,"disconnect"),children:d("settings.mcpServerTable.actions.disconnect")}):t.jsx(z,{size:"small",type:"primary",ghost:!0,onClick:I=>{I.stopPropagation(),l==null||l(b)},loading:g==null?void 0:g(b.id,"connect"),children:d("settings.mcpServerTable.actions.connect")}),t.jsx(z,{size:"small",onClick:I=>{I.stopPropagation(),m==null||m(b)},loading:g==null?void 0:g(b.id,"refresh"),children:d("settings.mcpServerTable.actions.refreshTools")})]})}}],[g,l,o,u,r,m,x,d,j.colorBorderSecondary,j.colorFillSecondary,j.colorTextSecondary,j.marginXS]);return t.jsx(at,{rowKey:"id",columns:S,dataSource:e,loading:s,pagination:!1,locale:{emptyText:d("settings.mcpServerTable.empty")},onRow:y=>({onClick:()=>n==null?void 0:n(y.id),style:{cursor:n?"pointer":"default",backgroundColor:a===y.id?j.colorFillSecondary:void 0}})})},{Text:wa}=de,{TextArea:di}=H,Ca=e=>{const s=e??Ms(""),a=s.transport,n=a.type==="stdio"?Object.entries(a.env??{}).map(([o,l])=>({key:o,value:l})):[],r=a.type==="sse"?a.headers.map(o=>({name:o.name,value:o.value})):[];return{id:s.id,name:s.name,enabled:s.enabled,transportType:a.type,command:a.type==="stdio"?a.command:void 0,args:a.type==="stdio"?a.args:[],envEntries:n,url:a.type==="sse"?a.url:void 0,headerEntries:r,requestTimeoutMs:s.request_timeout_ms||gs,healthcheckIntervalMs:s.healthcheck_interval_ms||ms,allowedTools:s.allowed_tools||[],deniedTools:s.denied_tools||[]}},ui=e=>e.reduce((s,a)=>{var r;const n=(r=a.key)==null?void 0:r.trim();return n&&(s[n]=a.value??""),s},{}),gi=e=>e.filter(s=>{var a;return(a=s.name)==null?void 0:a.trim()}).map(s=>{var a;return{name:((a=s.name)==null?void 0:a.trim())||"",value:s.value??""}}),Ma=(e,s,a)=>{var d,j,x;const n=s==="edit"&&(a==null?void 0:a.id)||e.id,r=(d=e.name)==null?void 0:d.trim(),o=typeof e.requestTimeoutMs=="number"?e.requestTimeoutMs:(a==null?void 0:a.request_timeout_ms)??gs,l=typeof e.healthcheckIntervalMs=="number"?e.healthcheckIntervalMs:(a==null?void 0:a.healthcheck_interval_ms)??ms,u=Array.isArray(e.allowedTools)?e.allowedTools:(a==null?void 0:a.allowed_tools)??[],m=Array.isArray(e.deniedTools)?e.deniedTools:(a==null?void 0:a.denied_tools)??[],g=e.transportType==="sse"?{type:"sse",url:((j=e.url)==null?void 0:j.trim())||"",headers:gi(e.headerEntries||[]),connect_timeout_ms:(a==null?void 0:a.transport.type)==="sse"?a.transport.connect_timeout_ms??Ss:Ss}:{type:"stdio",command:((x=e.command)==null?void 0:x.trim())||"",args:e.args||[],env:ui(e.envEntries||[]),cwd:(a==null?void 0:a.transport.type)==="stdio"?a.transport.cwd:void 0,startup_timeout_ms:(a==null?void 0:a.transport.type)==="stdio"?a.transport.startup_timeout_ms??is:is};return{id:n,name:r||void 0,enabled:e.enabled,transport:g,request_timeout_ms:o,healthcheck_interval_ms:l,allowed_tools:u,denied_tools:m,reconnect:a==null?void 0:a.reconnect}},Ea=e=>JSON.stringify(e||Ms(""),null,2),Bs=(e,s)=>{try{const a=JSON.parse(e);if(!a||typeof a!="object")return{valid:!1,error:s("settings.mcpServerForm.jsonMustBeObject")};const n=a;if(n.mcpServers&&typeof n.mcpServers=="object")return{valid:!1,error:s("settings.mcpServerForm.detectedBulkConfig")};const r=typeof n.id=="string"?n.id:"";if(!r.trim())return{valid:!1,error:s("settings.mcpServerForm.missingIdField")};if(n.transport&&typeof n.transport=="object"){const j=n;return!j.transport||typeof j.transport!="object"?{valid:!1,error:s("settings.mcpServerForm.missingTransportField")}:{valid:!0,config:j}}const o=typeof n.enabled=="boolean"?n.enabled:typeof n.disabled=="boolean"?!n.disabled:!0,l=typeof n.request_timeout_ms=="number"?n.request_timeout_ms:gs,u=typeof n.healthcheck_interval_ms=="number"?n.healthcheck_interval_ms:ms,m=Array.isArray(n.allowed_tools)?n.allowed_tools.filter(j=>typeof j=="string"):[],g=Array.isArray(n.denied_tools)?n.denied_tools.filter(j=>typeof j=="string"):[],d=typeof n.name=="string"?n.name:void 0;if(typeof n.url=="string"){const j=n.headers,x=Array.isArray(j)?j.map(y=>{if(!y||typeof y!="object")return null;const b=y,R=typeof b.name=="string"?b.name:"",P=typeof b.value=="string"?b.value:"";return R.trim()?{name:R,value:P}:null}).filter(y=>!!y):j&&typeof j=="object"?Object.entries(j).filter(([y])=>y.trim()).map(([y,b])=>({name:y,value:typeof b=="string"?b:""})):[],S=typeof n.connect_timeout_ms=="number"?n.connect_timeout_ms:Ss;return{valid:!0,config:{id:r,name:d,enabled:o,transport:{type:"sse",url:n.url,headers:x,connect_timeout_ms:S},request_timeout_ms:l,healthcheck_interval_ms:u,allowed_tools:m,denied_tools:g,reconnect:void 0}}}if(typeof n.command=="string"){const j=Array.isArray(n.args)?n.args.filter(b=>typeof b=="string"):[],x=n.env,S=x&&typeof x=="object"?Object.entries(x).reduce((b,[R,P])=>(typeof P=="string"&&(b[R]=P),b),{}):{},y=typeof n.startup_timeout_ms=="number"?n.startup_timeout_ms:is;return{valid:!0,config:{id:r,name:d,enabled:o,transport:{type:"stdio",command:n.command,args:j,cwd:typeof n.cwd=="string"?n.cwd:void 0,env:S,startup_timeout_ms:y},request_timeout_ms:l,healthcheck_interval_ms:u,allowed_tools:m,denied_tools:g,reconnect:void 0}}}return{valid:!1,error:s("settings.mcpServerForm.missingTransportInfo")}}catch(a){return{valid:!1,error:s("settings.mcpServerForm.invalidJson",{message:a instanceof Error?a.message:s("settings.mcpServerForm.unknownError")})}}},mi=({open:e,mode:s,initialConfig:a,confirmLoading:n=!1,onCancel:r,onSubmit:o})=>{const{t:l}=ne(),[u]=f.useForm(),[m,g]=i.useState("form"),[d,j]=i.useState(""),[x,S]=i.useState(null),y=i.useMemo(()=>Ca(a),[a]),b=f.useWatch("transportType",u)??"stdio";i.useEffect(()=>{e&&(u.setFieldsValue(y),j(Ea(a)),S(null),g("form"))},[u,y,a,e]);const R=()=>{u.resetFields(),j(""),S(null),r()},P=async()=>{if(m==="json"){const p=Bs(d,l);if(!p.valid){S(p.error);return}S(null);try{await o(p.config),j("")}catch(k){console.error("MCP server JSON submission error:",k)}return}try{const p=await u.validateFields(),k=Ma(p,s,a);await o(k),u.resetFields()}catch(p){console.error("MCP server form submission error:",p)}},C=p=>{j(p),x&&Bs(p,l).valid&&S(null)},I=p=>{if(p==="json")try{const k=u.getFieldsValue(),V=Ma(k,s,a);j(JSON.stringify(V,null,2))}catch{j(Ea(a))}else{const k=Bs(d,l);k.valid&&u.setFieldsValue(Ca(k.config))}g(p),S(null)};return t.jsxs(Qe,{title:l(s==="edit"?"settings.mcpServerForm.editTitle":"settings.mcpServerForm.addTitle"),open:e,onCancel:R,onOk:()=>{P()},okText:l("settings.mcpServerForm.save"),destroyOnClose:!0,forceRender:!0,confirmLoading:n,width:720,children:[t.jsx("div",{style:{marginBottom:16},children:t.jsxs(At.Group,{value:m,onChange:p=>I(p.target.value),optionType:"button",buttonStyle:"solid",children:[t.jsxs(At.Button,{value:"form",children:[t.jsx(Kn,{})," ",l("settings.mcpServerForm.modeForm")]}),t.jsxs(At.Button,{value:"json",children:[t.jsx(Wn,{})," ",l("settings.mcpServerForm.modeJson")]})]})}),m==="json"&&x&&t.jsx(He,{type:"error",message:l("settings.mcpServerForm.jsonError"),description:x,showIcon:!0,style:{marginBottom:16},closable:!0,onClose:()=>S(null)}),m==="json"?t.jsx(di,{value:d,onChange:p=>C(p.target.value),rows:20,style:{fontFamily:"monospace",fontSize:13},placeholder:JSON.stringify(Ms("example-server"),null,2)}):t.jsxs(f,{layout:"vertical",form:u,preserve:!0,initialValues:y,children:[t.jsx(f.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(H,{placeholder:"filesystem",disabled:s==="edit",autoComplete:"off"})}),t.jsx(f.Item,{name:"name",label:l("settings.mcpServerForm.displayName"),children:t.jsx(H,{placeholder:"Filesystem MCP",autoComplete:"off"})}),t.jsx(f.Item,{name:"enabled",label:l("settings.mcpServerForm.enabled"),valuePropName:"checked",extra:l("settings.mcpServerForm.enabledHelp"),children:t.jsx(ye,{})}),t.jsx(f.Item,{name:"transportType",label:l("settings.mcpServerForm.transportType"),rules:[{required:!0,message:l("settings.mcpServerForm.transportTypeRequired")}],children:t.jsx(se,{options:[{label:l("settings.mcpServerForm.transportOptions.stdio"),value:"stdio"},{label:l("settings.mcpServerForm.transportOptions.sse"),value:"sse"}]})}),b==="stdio"?t.jsxs(t.Fragment,{children:[t.jsx(f.Item,{name:"command",label:l("settings.mcpServerForm.command"),rules:[{required:!0,message:l("settings.mcpServerForm.commandRequired")}],children:t.jsx(H,{placeholder:"npx",autoComplete:"off"})}),t.jsx(f.Item,{name:"args",label:l("settings.mcpServerForm.arguments"),children:t.jsx(se,{mode:"tags",tokenSeparators:[","],placeholder:l("settings.mcpServerForm.argumentsPlaceholder"),open:!1})}),t.jsx(f.List,{name:"envEntries",children:(p,{add:k,remove:V})=>t.jsxs(L,{direction:"vertical",style:{width:"100%"},children:[t.jsxs(L,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[t.jsx(wa,{strong:!0,children:l("settings.mcpServerForm.envVars")}),t.jsx(z,{icon:t.jsx(ut,{}),onClick:()=>k({key:"",value:""}),type:"dashed",children:l("settings.mcpServerForm.addEnv")})]}),p.map(F=>t.jsxs(L,{align:"baseline",style:{display:"flex"},children:[t.jsx(f.Item,{...F,name:[F.name,"key"],rules:[{required:!0,message:l("settings.mcpServerForm.keyRequired")}],children:t.jsx(H,{placeholder:"MCP_ROOT",autoComplete:"off"})}),t.jsx(f.Item,{...F,name:[F.name,"value"],children:t.jsx(H,{placeholder:"/Users/me/workspace",autoComplete:"off"})}),t.jsx(z,{danger:!0,type:"text",icon:t.jsx(ba,{}),onClick:()=>V(F.name),"aria-label":l("settings.mcpServerForm.removeEnv","Remove environment variable")})]},F.key))]})})]}):t.jsxs(t.Fragment,{children:[t.jsx(f.Item,{name:"url",label:l("settings.mcpServerForm.sseUrl"),rules:[{required:!0,message:l("settings.mcpServerForm.sseUrlRequired")},{validator:async(p,k)=>{if(k)try{new URL(k)}catch{throw new Error(l("settings.mcpServerForm.validUrlRequired"))}}}],children:t.jsx(H,{placeholder:"http://localhost:4000/sse",autoComplete:"off"})}),t.jsx(f.List,{name:"headerEntries",children:(p,{add:k,remove:V})=>t.jsxs(L,{direction:"vertical",style:{width:"100%"},children:[t.jsxs(L,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[t.jsx(wa,{strong:!0,children:l("settings.mcpServerForm.headers")}),t.jsx(z,{icon:t.jsx(ut,{}),onClick:()=>k({name:"",value:""}),type:"dashed",children:l("settings.mcpServerForm.addHeader")})]}),p.map(F=>t.jsxs(L,{align:"baseline",style:{display:"flex"},children:[t.jsx(f.Item,{...F,name:[F.name,"name"],rules:[{required:!0,message:l("settings.mcpServerForm.headerNameRequired")}],children:t.jsx(H,{placeholder:"Authorization",autoComplete:"off"})}),t.jsx(f.Item,{...F,name:[F.name,"value"],children:t.jsx(H,{placeholder:"Bearer token",autoComplete:"off"})}),t.jsx(z,{danger:!0,type:"text",icon:t.jsx(ba,{}),onClick:()=>V(F.name),"aria-label":l("settings.mcpServerForm.removeHeader","Remove header")})]},F.key))]})})]})]})]})},js=e=>!!e&&typeof e=="object"&&!Array.isArray(e),_t=(e,s)=>{const a=e[s];return typeof a=="string"?a:void 0},Pa=(e,s)=>{const a=e[s];return typeof a=="boolean"?a:void 0},pi=(e,s)=>{const a=e[s];return Array.isArray(a)?a:void 0},ss=e=>{if(!js(e))return"any";const s=e.type;if(typeof s=="string"){if(s==="array"){const o=e.items;return`array<${ss(o)}>`}return s==="object"?"object":s}if(Array.isArray(s)){const o=s.filter(l=>typeof l=="string").map(l=>l==="array"?"array<any>":l);return o.length>0?o.join(" | "):"any"}const a=Array.isArray(e.oneOf)?e.oneOf:null;if(a)return a.map(ss).join(" | ")||"any";const n=Array.isArray(e.anyOf)?e.anyOf:null;if(n)return n.map(ss).join(" | ")||"any";const r=Array.isArray(e.allOf)?e.allOf:null;return r&&r.map(ss).join(" & ")||"any"},hi=e=>{if(!js(e))return null;const s=e.properties;if(!js(s))return{schemaUri:_t(e,"$schema"),title:_t(e,"title"),description:_t(e,"description"),additionalProperties:Pa(e,"additionalProperties"),fields:[]};const a=new Set((pi(e,"required")??[]).filter(r=>typeof r=="string").map(r=>r)),n=Object.entries(s).map(([r,o])=>{const l=js(o)?o:void 0;return{name:r,type:ss(o),required:a.has(r),description:l?_t(l,"description"):void 0,defaultValue:l?l.default:void 0,enumValues:l&&Array.isArray(l.enum)?l.enum:void 0}});return n.sort((r,o)=>r.required!==o.required?r.required?-1:1:r.name.localeCompare(o.name)),{schemaUri:_t(e,"$schema"),title:_t(e,"title"),description:_t(e,"description"),additionalProperties:Pa(e,"additionalProperties"),fields:n}},{Text:et}=de,yi=e=>e===void 0?"":e===null?"null":typeof e=="string"?e:Qa(e,0),fi=({schema:e})=>{const{token:s}=_e.useToken(),{t:a}=ne(),n=i.useMemo(()=>hi(e),[e]);if(!n)return t.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:Qa(e,2)});const r=[{title:a("components.jsonSchema.field"),dataIndex:"name",key:"name",width:180,render:l=>t.jsx(et,{code:!0,children:l})},{title:a("components.jsonSchema.type"),dataIndex:"type",key:"type",width:140,render:l=>t.jsx(et,{children:l})},{title:a("components.jsonSchema.required"),dataIndex:"required",key:"required",width:110,render:l=>l?t.jsx(et,{strong:!0,style:{color:s.colorError},children:a("components.jsonSchema.yes")}):t.jsx(et,{type:"secondary",children:a("components.jsonSchema.no")})},{title:a("components.jsonSchema.default"),dataIndex:"defaultValue",key:"default",width:160,render:l=>l===void 0?t.jsx(et,{type:"secondary",children:"-"}):t.jsx(et,{children:yi(l)})},{title:a("components.jsonSchema.description"),dataIndex:"description",key:"description",render:l=>l?t.jsx(et,{style:{whiteSpace:"pre-wrap"},children:l}):t.jsx(et,{type:"secondary",children:"-"})}],o=(n.fields??[]).map(l=>({...l,key:l.name}));return t.jsxs("div",{style:{width:"100%"},children:[t.jsx(Oe,{size:"small",column:1,items:[n.schemaUri?{key:"schema",label:"$schema",children:t.jsx(et,{code:!0,children:n.schemaUri})}:null,typeof n.additionalProperties=="boolean"?{key:"additionalProperties",label:"additionalProperties",children:t.jsx(et,{children:n.additionalProperties?"true":"false"})}:null].filter(Boolean)}),t.jsx(at,{size:"small",pagination:!1,columns:r,dataSource:o,locale:{emptyText:a("components.jsonSchema.noProperties")},style:{marginTop:s.marginSM}})]})},{Text:Wt}=de,xi=(e,s)=>`mcp__${e}__${s}`,bi=({server:e,tools:s,loading:a=!1})=>{const{t:n}=ne();return t.jsx(N,{title:n("settings.mcpToolList.title"),size:"small",children:e?t.jsx(Je,{loading:a,dataSource:s,locale:{emptyText:n("settings.mcpToolList.empty")},renderItem:r=>{const o=xi(r.server_id,r.original_name);return t.jsx(Je.Item,{children:t.jsxs(L,{direction:"vertical",size:2,style:{width:"100%"},children:[t.jsx(Wt,{strong:!0,children:r.original_name}),t.jsx(Wt,{type:"secondary",children:r.description||n("settings.mcpToolList.noDescription")}),t.jsx(Wt,{code:!0,children:r.alias}),t.jsxs(Wt,{type:"secondary",children:[n("settings.mcpToolList.aliasMapping"),": ",t.jsx(Wt,{code:!0,children:o})]}),r.parameters!==void 0&&t.jsx(ws,{size:"small",items:[{key:"schema",label:n("settings.mcpToolList.parametersSchema"),children:t.jsx(fi,{schema:r.parameters})}]})]})})}}):t.jsx(Ue,{image:Ue.PRESENTED_IMAGE_SIMPLE,description:n("settings.mcpToolList.selectServerHint")})})},{Text:Gt}=de,{useToken:vi}=_e,{TextArea:ji}=H,Da={[J.Connecting]:"processing",[J.Ready]:"success",[J.Degraded]:"warning",[J.Stopped]:"default",[J.Error]:"error"},Ti=()=>({[J.Connecting]:0,[J.Ready]:0,[J.Degraded]:0,[J.Stopped]:0,[J.Error]:0}),St=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,_i=e=>{var a,n,r;const s={};for(const o of e){const l=(a=o.id)==null?void 0:a.trim();if(!l)continue;const m=!(o.enabled??o.config.enabled),g=o.config.transport;if(g.type==="sse"){const j={};for(const S of g.headers??[]){const y=(n=S.name)==null?void 0:n.trim();y&&(j[y]=S.value??"")}const x={url:g.url};m&&(x.disabled=!0),Object.keys(j).length&&(x.headers=j),s[l]=x;continue}const d={command:g.command};m&&(d.disabled=!0),(r=g.args)!=null&&r.length&&(d.args=g.args),g.cwd&&(d.cwd=g.cwd),g.env&&Object.keys(g.env).length&&(d.env=g.env),s[l]=d}return{mcpServers:s}},Si=()=>{const{t:e}=ne(),{token:s}=vi(),[a,n]=Lt.useMessage(),{servers:r,selectedServerId:o,selectedServerTools:l,isLoadingServers:u,isMutatingConfig:m,isRefreshingAll:g,isSelectedServerToolsLoading:d,error:j,setSelectedServerId:x,addServer:S,updateServer:y,deleteServer:b,connectServer:R,disconnectServer:P,refreshServerTools:C,refreshAll:I,isServerActionLoading:p}=ri(),k=i.useMemo(()=>({[J.Connecting]:e("settings.mcpTab.status.connecting"),[J.Ready]:e("settings.mcpTab.status.ready"),[J.Degraded]:e("settings.mcpTab.status.degraded"),[J.Stopped]:e("settings.mcpTab.status.stopped"),[J.Error]:e("settings.mcpTab.status.error")}),[e]),V=i.useMemo(()=>({[J.Connecting]:e("settings.mcpTab.statusHelp.connecting"),[J.Ready]:e("settings.mcpTab.statusHelp.ready"),[J.Degraded]:e("settings.mcpTab.statusHelp.degraded"),[J.Stopped]:e("settings.mcpTab.statusHelp.stopped"),[J.Error]:e("settings.mcpTab.statusHelp.error")}),[e]),[F,U]=i.useState(!1),[ae,q]=i.useState("create"),[v,T]=i.useState(null),[D,A]=i.useState(!1),[ee,O]=i.useState("merge"),[Q,W]=i.useState(""),[re,ue]=i.useState(null),[be,c]=i.useState(!1),E=i.useMemo(()=>o?r.find(h=>h.id===o)??null:null,[o,r]),M=i.useMemo(()=>{const h=Ti();let le=0;return r.forEach(ve=>{var Ce,Be;const $e=((Ce=ve.runtime)==null?void 0:Ce.status)??J.Stopped;h[$e]+=1,le+=((Be=ve.runtime)==null?void 0:Be.tool_count)??0}),{byStatus:h,totalServers:r.length,totalTools:le}},[r]),G={background:s.colorFillSecondary,borderColor:s.colorBorderSecondary,color:s.colorTextSecondary},Z=async h=>{try{await b(h.id),a.success(e("settings.mcpTab.serverDeleted"))}catch(le){a.error(St(le,e("settings.mcpTab.deleteServerFailed")))}},ge=async h=>{try{await R(h.id),a.success(e("settings.mcpTab.connectedTo",{name:h.name||h.id}))}catch(le){a.error(St(le,e("settings.mcpTab.connectServerFailed")))}},xe=async h=>{try{await P(h.id),a.success(e("settings.mcpTab.disconnected",{name:h.name||h.id}))}catch(le){a.error(St(le,e("settings.mcpTab.disconnectServerFailed")))}},je=async h=>{try{await C(h.id),a.success(e("settings.mcpTab.toolsRefreshedFor",{name:h.name||h.id}))}catch(le){a.error(St(le,e("settings.mcpTab.refreshToolsFailed")))}},$=async()=>{try{await I(),a.success(e("settings.mcpTab.statusRefreshed"))}catch(h){a.error(St(h,e("settings.mcpTab.refreshStatusFailed")))}},Te=()=>{T(null),q("create"),U(!0)},Xe=h=>{T(h),q("edit"),U(!0)},Ie=async h=>{try{if(ae==="edit"){if(!v){a.error(e("settings.mcpTab.noServerForEditing"));return}await y(v.id,h),a.success(e("settings.mcpTab.savedServer",{name:v.name||v.id}))}else await S(h),a.success(e("settings.mcpTab.addedServer",{name:h.name||h.id}));U(!1),T(null)}catch(le){a.error(St(le,e("settings.mcpTab.saveServerFailed")))}},Ve=()=>{A(!0),ue(null),O("merge"),W("")},Le=async()=>{const h=_i(r),le=JSON.stringify(h,null,2);try{await ra(le),a.success(e("settings.mcpTab.copiedConfig"))}catch{A(!0),ue(null),O("merge"),W(le),a.warning(e("settings.mcpTab.clipboardUnavailable"))}},Ae=async()=>{var $e;ue(null);let h;try{h=JSON.parse(Q)}catch(Ce){ue(`${e("settings.mcpTab.invalidJsonPrefix")}: ${Ce instanceof Error?Ce.message:e("settings.mcpTab.unknownError")}`);return}if(!h||typeof h!="object"){ue(e("settings.mcpTab.jsonMustBeObject"));return}const ve=h.mcpServers;if(!ve||typeof ve!="object"){ue(e("settings.mcpTab.missingMcpServers"));return}c(!0);try{const Ce=await nn.importServers({mcpServers:ve,mode:ee}),Be=(($e=Ce.start_errors)==null?void 0:$e.length)??0;a.success(e("settings.mcpTab.importSummary",{count:Ce.server_ids.length,added:Ce.added,updated:Ce.updated,removed:Ce.removed,failed:Be})),Be&&a.warning(e("settings.mcpTab.importStartFailures")),A(!1),W(""),await $()}catch(Ce){ue(St(Ce,e("settings.mcpTab.importFailed")))}finally{c(!1)}};return t.jsxs(L,{direction:"vertical",size:s.marginMD,style:{width:"100%"},children:[n,j?t.jsx(He,{type:"error",showIcon:!0,message:j}):null,t.jsx(N,{size:"small",title:e("settings.mcpTab.overviewTitle"),children:t.jsxs(L,{direction:"vertical",size:s.marginXS,style:{width:"100%"},children:[t.jsx(Gt,{type:"secondary",children:e("settings.mcpTab.overviewDescription")}),t.jsxs(L,{wrap:!0,children:[t.jsx(ie,{style:G,children:e("settings.mcpTab.totalServers",{count:M.totalServers})}),t.jsx(ie,{style:G,children:e("settings.mcpTab.totalTools",{count:M.totalTools})}),Object.values(J).map(h=>t.jsx(ke,{title:V[h],children:t.jsxs(ie,{color:h===J.Stopped?void 0:Da[h],style:{cursor:"help",...h===J.Stopped?G:void 0},children:[k[h],": ",M.byStatus[h]]})},h))]}),t.jsx(Gt,{type:"secondary",children:e("settings.mcpTab.statusGuideTitle")}),t.jsx(L,{direction:"vertical",size:2,style:{width:"100%"},children:Object.values(J).map(h=>t.jsxs(Gt,{type:"secondary",children:[t.jsx(ie,{color:h===J.Stopped?void 0:Da[h],style:{marginInlineEnd:8,...h===J.Stopped?G:void 0},children:k[h]}),V[h]]},`guide-${h}`))})]})}),t.jsx(N,{size:"small",title:e("settings.mcpTab.serversTitle"),extra:t.jsxs(L,{children:[t.jsx(z,{type:"primary",onClick:Te,children:e("settings.mcpTab.addServer")}),t.jsx(z,{icon:t.jsx(Ot,{}),loading:g,onClick:()=>{$()},children:e("settings.mcpTab.refreshAll")}),t.jsx(z,{icon:t.jsx(en,{}),onClick:()=>void Le(),children:e("settings.mcpTab.export")}),t.jsx(z,{icon:t.jsx(Gn,{}),onClick:Ve,children:e("settings.mcpTab.import")})]}),children:t.jsx(ci,{servers:r,loading:u,selectedServerId:o,onSelectServer:x,onEditServer:Xe,onDeleteServer:Z,onConnectServer:ge,onDisconnectServer:xe,onRefreshTools:je,isServerActionLoading:p})}),t.jsx(bi,{server:E,tools:l,loading:d}),t.jsx(mi,{open:F,mode:ae,initialConfig:(v==null?void 0:v.config)??null,confirmLoading:m,onCancel:()=>{m||(U(!1),T(null))},onSubmit:h=>void Ie(h)}),t.jsx(Qe,{open:D,title:e("settings.mcpTab.importModalTitle"),okText:e("settings.mcpTab.import"),onOk:()=>void Ae(),okButtonProps:{loading:be},onCancel:()=>{be||(A(!1),ue(null))},width:800,destroyOnClose:!1,children:t.jsxs(L,{direction:"vertical",style:{width:"100%"},size:"middle",children:[t.jsxs(Gt,{type:"secondary",children:[e("settings.mcpTab.importHint"),t.jsx("br",{}),t.jsx(Gt,{code:!0,children:'{ "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "..."] } } }'})]}),t.jsxs(At.Group,{value:ee,onChange:h=>O(h.target.value),optionType:"button",buttonStyle:"solid",children:[t.jsx(At.Button,{value:"merge",children:e("settings.mcpTab.importModeMerge")}),t.jsx(At.Button,{value:"replace",children:e("settings.mcpTab.importModeReplace")})]}),ee==="replace"?t.jsx(He,{type:"warning",showIcon:!0,message:e("settings.mcpTab.replaceWarning")}):null,re?t.jsx(He,{type:"error",showIcon:!0,message:re}):null,t.jsx(ji,{value:Q,onChange:h=>W(h.target.value),rows:14,placeholder:'{"mcpServers": { "filesystem": { "command": "...", "args": [], "env": {} } }}',spellCheck:!1})]})})]})},rn=1,ki=365,on=e=>Number.isFinite(e)?Math.min(ki,Math.max(rn,Math.floor(e??30))):30,qs=e=>{if(!e)return null;const s=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!s)return null;const a=Number(s[1]),n=Number(s[2]),r=Number(s[3]),o=new Date(Date.UTC(a,n-1,r));return o.getUTCFullYear()!==a||o.getUTCMonth()!==n-1||o.getUTCDate()!==r?null:o},Jt=e=>e.toISOString().slice(0,10),wi=(e,s)=>{const a=new Date(e.getTime());return a.setUTCDate(a.getUTCDate()+s),a},Ci=(e,s)=>{const a=s.getTime()-e.getTime(),n=Math.floor(a/864e5)+1;return on(n)},la=(e,s=new Date)=>{const a=on(e.days),n=Jt(s),r=qs(e.endDate)??qs(n);if(!r)return{startDate:n,endDate:n,days:rn};const o=qs(e.startDate);if(o){const u=r<o?o:r;return{startDate:Jt(o),endDate:Jt(u),days:Ci(o,u)}}const l=wi(r,-(a-1));return{startDate:Jt(l),endDate:Jt(r),days:a}},Mi=15e3,Ei=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,Pi=(e={})=>{const{filters:s,autoRefreshMs:a=Mi}=e,n=i.useMemo(()=>({startDate:s==null?void 0:s.startDate,endDate:s==null?void 0:s.endDate,days:(s==null?void 0:s.days)??30,endpoint:s==null?void 0:s.endpoint,model:s==null?void 0:s.model,limit:(s==null?void 0:s.limit)??100}),[s==null?void 0:s.startDate,s==null?void 0:s.endDate,s==null?void 0:s.days,s==null?void 0:s.endpoint,s==null?void 0:s.model,s==null?void 0:s.limit]),r=i.useMemo(()=>la({startDate:n.startDate,endDate:n.endDate,days:n.days}),[n.days,n.endDate,n.startDate]),[o,l]=i.useState(null),[u,m]=i.useState([]),[g,d]=i.useState([]),[j,x]=i.useState(!1),[S,y]=i.useState(!1),[b,R]=i.useState(null),P=i.useCallback(async I=>{I?x(!0):y(!0);try{const p={startDate:r.startDate,endDate:r.endDate,endpoint:n.endpoint,model:n.model,limit:n.limit},[k,V,F]=await Promise.all([as.getForwardSummary(p),as.getForwardByEndpoint(p),as.getForwardRequests(p)]);l(k),m(V),d(F),R(null)}catch(p){R(Ei(p,"Failed to load forward metrics"))}finally{I?x(!1):y(!1)}},[n.endpoint,n.model,n.limit,r.endDate,r.startDate]),C=i.useCallback(async()=>{await P(!1)},[P]);return i.useEffect(()=>{P(!0)},[P]),i.useEffect(()=>{if(a<=0)return;const I=window.setInterval(()=>{P(!1)},a);return()=>{window.clearInterval(I)}},[a,P]),{summary:o,endpointMetrics:u,requests:g,isLoading:j,isRefreshing:S,error:b,refresh:C}},Di=15e3,Ia=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,Ii=(e={})=>{const{filters:s,autoRefreshMs:a=Di,service:n=as}=e,r=i.useMemo(()=>({startDate:s==null?void 0:s.startDate,endDate:s==null?void 0:s.endDate,model:s==null?void 0:s.model,days:(s==null?void 0:s.days)??30,granularity:(s==null?void 0:s.granularity)??"daily",sessionLimit:(s==null?void 0:s.sessionLimit)??200}),[s==null?void 0:s.startDate,s==null?void 0:s.endDate,s==null?void 0:s.model,s==null?void 0:s.days,s==null?void 0:s.granularity,s==null?void 0:s.sessionLimit]),o=i.useMemo(()=>la({startDate:r.startDate,endDate:r.endDate,days:r.days}),[r.days,r.endDate,r.startDate]),[l,u]=i.useState(null),[m,g]=i.useState([]),[d,j]=i.useState([]),[x,S]=i.useState([]),[y,b]=i.useState(null),[R,P]=i.useState([]),[C,I]=i.useState(null),[p,k]=i.useState(!1),[V,F]=i.useState(!1),[U,ae]=i.useState(!1),[q,v]=i.useState(null),T=i.useCallback(async O=>{O?F(!0):ae(!0);try{const Q=n.getMemorySummary?n.getMemorySummary().catch(()=>null):Promise.resolve(null),W=n.getMemoryTimeline?n.getMemoryTimeline({days:o.days,endDate:o.endDate,granularity:r.granularity}).catch(()=>[]):Promise.resolve([]),[re,ue,be,c,E,M]=await Promise.all([n.getSummary({startDate:o.startDate,endDate:o.endDate}),n.getByModel({startDate:o.startDate,endDate:o.endDate}),n.getSessions({startDate:o.startDate,endDate:o.endDate,model:r.model,limit:r.sessionLimit}),n.getDaily({days:o.days,endDate:o.endDate,granularity:r.granularity}),Q,W]);u(re),g(ue),j(be),S(c),b(E),P(M),v(null)}catch(Q){v(Ia(Q,"Failed to load metrics"))}finally{O?F(!1):ae(!1)}},[r.granularity,r.model,r.sessionLimit,o.days,o.endDate,o.startDate,n]),D=i.useCallback(async()=>{await T(!1)},[T]),A=i.useCallback(async O=>{k(!0);try{const Q=await n.getSessionDetail(O);I(Q)}catch(Q){v(Ia(Q,"Failed to load session detail"))}finally{k(!1)}},[n]),ee=i.useCallback(()=>{I(null)},[]);return i.useEffect(()=>{T(!0)},[T]),i.useEffect(()=>{if(a<=0)return;const O=window.setInterval(()=>{T(!1)},a);return()=>{window.clearInterval(O)}},[a,T]),{summary:l,modelMetrics:m,sessions:d,timeline:x,memorySummary:y,memoryTimeline:R,sessionDetail:C,isLoading:V,isRefreshing:U,isSessionDetailLoading:p,error:q,refresh:D,loadSessionDetail:A,clearSessionDetail:ee}},Fi=15e3,Ai=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,Ri=(e={})=>{const{filters:s,autoRefreshMs:a=Fi}=e,n=i.useMemo(()=>({startDate:s==null?void 0:s.startDate,endDate:s==null?void 0:s.endDate,days:(s==null?void 0:s.days)??30,model:s==null?void 0:s.model}),[s==null?void 0:s.days,s==null?void 0:s.endDate,s==null?void 0:s.model,s==null?void 0:s.startDate]),r=i.useMemo(()=>la({startDate:n.startDate,endDate:n.endDate,days:n.days}),[n.days,n.endDate,n.startDate]),[o,l]=i.useState(null),[u,m]=i.useState(!1),[g,d]=i.useState(!1),[j,x]=i.useState(null),S=i.useCallback(async b=>{b?m(!0):d(!0);try{const R=await as.getUsageBreakdown({startDate:r.startDate,endDate:r.endDate,model:n.model});l(R),x(null)}catch(R){x(Ai(R,"Failed to load usage breakdown"))}finally{b?m(!1):d(!1)}},[n.model,r.endDate,r.startDate]),y=i.useCallback(async()=>{await S(!1)},[S]);return i.useEffect(()=>{S(!0)},[S]),i.useEffect(()=>{if(a<=0)return;const b=window.setInterval(()=>{S(!1)},a);return()=>{window.clearInterval(b)}},[a,S]),{data:o,isLoading:u,isRefreshing:g,error:j,refresh:y}},{useToken:zi}=_e,Li=({data:e,loading:s})=>{const{t:a}=ne(),{token:n}=zi();if(s)return t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("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:n.colorTextSecondary},children:a("settings.common.loading")})})});if(e.length===0)return t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.charts.endpointDistribution"),children:t.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:240,color:n.colorTextSecondary},children:a("settings.charts.noForwardMetrics")})});const r=e.map(o=>({endpoint:o.endpoint.split(".").pop()||o.endpoint,requests:o.requests,successful:o.successful,failed:o.failed}));return t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.charts.endpointDistribution"),children:t.jsx("div",{style:{width:"100%",height:240},children:t.jsx(Nt,{children:t.jsxs(ia,{data:r,children:[t.jsx(cs,{strokeDasharray:"3 3"}),t.jsx(ds,{dataKey:"endpoint"}),t.jsx(us,{}),t.jsx(Vt,{formatter:(o,l)=>[`${o}`,l.charAt(0).toUpperCase()+l.slice(1)]}),t.jsx(oa,{}),t.jsx(_s,{dataKey:"successful",fill:"var(--lotus-chart-secondary)",name:a("settings.common.successful"),fillOpacity:.9,radius:[4,4,0,0]}),t.jsx(_s,{dataKey:"failed",fill:"var(--lotus-chart-danger)",name:a("settings.common.failed"),fillOpacity:.9,radius:[4,4,0,0]})]})})})})},Hs=e=>e.replace(/\.0$/,""),ln=e=>e.toLocaleString(),cn=e=>Number.isFinite(e)?e.toLocaleString(void 0,{maximumFractionDigits:20}):String(e),ca=e=>{if(!Number.isFinite(e))return String(e);const s=Math.abs(e);if(s>=1e9){const a=s>=1e10?0:1;return`${Hs((e/1e9).toFixed(a))}B`}if(s>=1e6){const a=s>=1e7?0:1;return`${Hs((e/1e6).toFixed(a))}M`}if(s>=1e3){const a=s>=1e4?0:1;return`${Hs((e/1e3).toFixed(a))}K`}return ln(e)},Oi=e=>Number.isFinite(e)&&Math.abs(e)>=1e3,dn=e=>cn(e),os=e=>{if(!Number.isFinite(e))return String(e);const s=ca(e);return Oi(e)?t.jsx(ke,{title:t.jsx("div",{children:cn(e)}),children:t.jsx("span",{children:s})}):s},ct=e=>{const s=Number(e??0);return Number.isFinite(s)?os(s):e==null?"-":String(e)},{useToken:Ni}=_e,Vi=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),a=Math.floor(s/60),n=s%60;if(a>=60){const r=Math.floor(a/60),o=a%60;return`${r}h ${o}m`}return a>0?`${a}m ${n}s`:`${n}s`},Fa=({summary:e,loading:s})=>{const{t:a}=ne(),{token:n}=Ni();if(s)return t.jsx(mt,{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:[n.marginSM,n.marginSM],children:[t.jsx(me,{xs:24,sm:12,xl:6,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:a("settings.forwardMetricsCards.totalForwardRequests"),value:(e==null?void 0:e.total_requests)??0,precision:0,formatter:ct,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),t.jsx(me,{xs:24,sm:12,xl:6,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:a("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(me,{xs:24,sm:12,xl:6,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:a("settings.forwardMetricsCards.forwardTokens"),value:(e==null?void 0:e.total_tokens.total_tokens)??0,precision:0,formatter:ct,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})}),t.jsx(me,{xs:24,sm:12,xl:6,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:a("settings.forwardMetricsCards.avgResponseTime"),value:Vi(e==null?void 0:e.avg_duration_ms),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:kt}=de,$i=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),a=Math.floor(s/60),n=s%60;return a>0?`${a}m ${n}s`:`${n}s`},Bi=e=>new Date(e).toLocaleString(),qi=({requests:e,loading:s})=>{const{t:a}=ne(),n=[{title:a("settings.metricsTable.forward.columns.id"),dataIndex:"forward_id",key:"forward_id",width:120,render:r=>t.jsxs(kt,{style:{fontSize:12},copyable:!0,children:[r.slice(0,8),"..."]})},{title:a("settings.metricsTable.forward.columns.endpoint"),dataIndex:"endpoint",key:"endpoint",width:150,render:r=>t.jsx(ie,{color:"processing",children:r.split(".").pop()||r})},{title:a("settings.metricsTable.forward.columns.model"),dataIndex:"model",key:"model",width:120},{title:a("settings.metricsTable.forward.columns.type"),dataIndex:"is_stream",key:"is_stream",width:80,render:r=>t.jsx(ie,{color:r?"purple":"processing",children:a(r?"settings.metricsTable.forward.typeStream":"settings.metricsTable.forward.typeSync")})},{title:a("settings.metricsTable.forward.columns.status"),key:"status",width:100,render:(r,o)=>{const l=o.status==="success"?"success":o.status==="error"?"error":"default";return t.jsx(Jn,{status:l,text:o.status_code?t.jsxs("span",{children:[o.status,t.jsxs(kt,{type:"secondary",style:{marginLeft:4},children:["(",o.status_code,")"]})]}):o.status||"-"})}},{title:a("settings.metricsTable.forward.columns.tokens"),key:"tokens",width:100,render:(r,o)=>o.token_usage?t.jsx(kt,{children:os(o.token_usage.total_tokens)}):t.jsx(kt,{type:"secondary",children:"-"})},{title:a("settings.metricsTable.forward.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",width:100,render:r=>$i(r)},{title:a("settings.metricsTable.forward.columns.started"),dataIndex:"started_at",key:"started_at",width:160,render:r=>t.jsx(kt,{type:"secondary",style:{fontSize:12},children:Bi(r)})},{title:a("settings.metricsTable.forward.columns.error"),dataIndex:"error",key:"error",width:200,render:r=>r?t.jsx(kt,{type:"danger",ellipsis:!0,style:{maxWidth:180},children:r}):t.jsx(kt,{type:"secondary",children:"-"})}];return t.jsx(at,{rowKey:"forward_id",className:"lotus-metric-table",columns:n,dataSource:e,loading:s,size:"small",pagination:{pageSize:10,showSizeChanger:!0,showTotal:r=>a("settings.metricsTable.forward.totalRequests",{total:r}),pageSizeOptions:["10","20","50","100"]},scroll:{x:1200},locale:{emptyText:a("settings.metricsTable.forward.empty")}})},{useToken:Hi}=_e,Ui=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString()},Aa=({summary:e,loading:s})=>{const{t:a}=ne(),{token:n}=Hi();return s?t.jsx(mt,{active:!0,paragraph:{rows:1}}):t.jsxs(Ge,{gutter:[n.marginSM,n.marginSM],children:[t.jsx(me,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:a("settings.unifiedMetricsCards.totalMemories"),value:(e==null?void 0:e.total_memories)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:a("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(me,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:a("settings.unifiedMetricsCards.memoryProjects"),value:(e==null?void 0:e.project_count)??0,precision:0,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:a("settings.unifiedMetricsCards.lastReindex"),value:Ui(e==null?void 0:e.last_reindex_at),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:Ki}=de,Wi=({data:e,loading:s})=>{const{t:a}=ne();return s?t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.charts.memoryTrendTitle"),children:t.jsx(mt,{active:!0,paragraph:{rows:5}})}):t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.charts.memoryTrendTitle"),children:e.length===0?t.jsx(Ue,{image:Ue.PRESENTED_IMAGE_SIMPLE,description:a("settings.charts.noMemoryTrend")}):t.jsxs(t.Fragment,{children:[t.jsx(Ki,{type:"secondary",children:a("settings.charts.memoryTrendDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(Nt,{children:t.jsxs(sn,{data:e,children:[t.jsx(cs,{strokeDasharray:"3 3"}),t.jsx(ds,{dataKey:"label",minTickGap:24}),t.jsx(us,{allowDecimals:!1}),t.jsx(Vt,{}),t.jsx(oa,{}),t.jsx(Rt,{type:"monotone",dataKey:"total_memories",name:a("settings.charts.totalMemories"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),t.jsx(Rt,{type:"monotone",dataKey:"created_memories",name:a("settings.charts.createdMemories"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),t.jsx(Rt,{type:"monotone",dataKey:"updated_memories",name:a("settings.charts.updatedMemories"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{useToken:Gi}=_e,Ji=e=>{const s=Math.floor(e/1e3),a=Math.floor(s/60),n=s%60;return a>0?`${a}m ${n}s`:`${n}s`},Xi=e=>{const s=e.filter(n=>typeof n.duration_ms=="number"&&n.duration_ms>0);if(s.length===0)return 0;const a=s.reduce((n,r)=>n+(r.duration_ms??0),0);return Math.floor(a/s.length)},Ra=({summary:e,sessions:s,loading:a})=>{const{t:n}=ne(),{token:r}=Gi();if(a)return t.jsx(mt,{active:!0,paragraph:{rows:1}});const o=Xi(s);return t.jsxs(Ge,{gutter:[r.marginSM,r.marginSM],children:[t.jsx(me,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:n("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(me,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:n("settings.metricsCards.totalSessions"),value:(e==null?void 0:e.total_sessions)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:n("settings.metricsCards.chatTokens"),value:(e==null?void 0:e.total_tokens.total_tokens)??0,precision:0,formatter:ct,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:n("settings.metricsCards.totalToolCalls"),value:(e==null?void 0:e.total_tool_calls)??0,precision:0,formatter:ct,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:n("settings.metricsCards.tokensSaved",{defaultValue:"Saved Tokens"}),value:(e==null?void 0:e.total_tokens_saved)??0,precision:0,formatter:ct,valueStyle:{color:"var(--lotus-chart-cyan)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:n("settings.metricsCards.toolContextSavedTokens",{defaultValue:"Tool Context Saved Tokens"}),value:(e==null?void 0:e.tool_context_tokens_saved)??0,precision:0,formatter:ct,valueStyle:{color:"var(--lotus-chart-accent)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:n("settings.metricsCards.compressionEvents",{defaultValue:"Compression Events"}),value:(e==null?void 0:e.total_compression_events)??0,precision:0,formatter:ct,valueStyle:{color:"var(--lotus-chart-secondary)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:n("settings.metricsCards.avgSessionDuration"),value:o>0?Ji(o):"-",valueStyle:{color:"var(--lotus-chart-accent)"}})})})]})},{Text:Yi}=de,za=["var(--lotus-chart-primary)","var(--lotus-chart-secondary)","var(--lotus-chart-accent)","var(--lotus-chart-purple)","var(--lotus-chart-cyan)"],Zi=({data:e,loading:s})=>{const{t:a}=ne();if(s)return t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.charts.modelDistribution"),children:t.jsx(mt,{active:!0,paragraph:{rows:5}})});const n=e.map(r=>({name:r.model,value:r.tokens.total_tokens}));return t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.charts.modelDistribution"),children:n.length===0?t.jsx(Ue,{image:Ue.PRESENTED_IMAGE_SIMPLE,description:a("settings.charts.noModelMetrics")}):t.jsxs(t.Fragment,{children:[t.jsx(Yi,{type:"secondary",children:a("settings.charts.modelDistributionDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(Nt,{children:t.jsxs(ir,{children:[t.jsx(or,{data:n,cx:"50%",cy:"50%",outerRadius:90,fill:"var(--lotus-chart-primary)",dataKey:"value",nameKey:"name",label:!0,children:n.map((r,o)=>t.jsx(lr,{fill:za[o%za.length]},`${r.name}-${o}`))}),t.jsx(Vt,{formatter:r=>dn(r)})]})})})]})})},Qi=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?"-":s.toLocaleString()},eo=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),a=Math.floor(s/60),n=s%60;if(a>=60){const r=Math.floor(a/60),o=a%60;return`${r}h ${o}m`}return a>0?`${a}m ${n}s`:`${n}s`},to=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"}},so=(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}},ao=({sessions:e,loading:s,onSelectSession:a})=>{const{t:n}=ne(),r=[{title:n("settings.metricsTable.session.columns.session"),dataIndex:"session_id",key:"session_id",render:o=>t.jsx(ke,{title:o,children:t.jsxs("span",{children:[o.slice(0,8),"..."]})}),width:120},{title:n("settings.metricsTable.session.columns.model"),dataIndex:"model",key:"model",width:160},{title:n("settings.metricsTable.session.columns.status"),dataIndex:"status",key:"status",width:120,render:o=>t.jsx(ie,{color:to(o),children:so(o,n)})},{title:n("settings.metricsTable.session.columns.started"),dataIndex:"started_at",key:"started_at",render:o=>Qi(o),width:200,sorter:(o,l)=>new Date(o.started_at).getTime()-new Date(l.started_at).getTime(),defaultSortOrder:"descend"},{title:n("settings.metricsTable.session.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",render:o=>eo(o),width:120},{title:n("settings.metricsTable.session.columns.tokens"),key:"tokens",render:(o,l)=>os(l.total_token_usage.total_tokens),width:120,sorter:(o,l)=>o.total_token_usage.total_tokens-l.total_token_usage.total_tokens},{title:n("settings.metricsTable.session.columns.toolCalls"),dataIndex:"tool_call_count",key:"tool_call_count",width:120,sorter:(o,l)=>o.tool_call_count-l.tool_call_count},{title:n("settings.metricsTable.session.columns.messages"),dataIndex:"message_count",key:"message_count",width:120,sorter:(o,l)=>o.message_count-l.message_count},{title:n("settings.metricsTable.session.columns.action"),key:"action",fixed:"right",width:120,render:(o,l)=>t.jsx(z,{type:"link",onClick:()=>{a(l.session_id)},children:n("settings.metricsTable.session.view")})}];return t.jsx(at,{rowKey:"session_id",size:"small",className:"lotus-metric-table",columns:r,loading:s,dataSource:e,pagination:{pageSize:10,showSizeChanger:!1},scroll:{x:1100}})},{Text:no}=de,La={message_count:"Message Count",last_message_id:"Last Message",pending_question:"Pending Question"},ro=e=>La[e]?La[e]:e.split("_").map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "),io=({breakdown:e,loading:s})=>{const{t:a}=ne();if(s)return t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),children:t.jsx(mt,{active:!0,paragraph:{rows:5}})});const n=Object.entries(e??{}).map(([r,o])=>({reason:r,label:a(`settings.syncMismatchReasons.${r}`,{defaultValue:ro(r)}),count:o})).sort((r,o)=>o.count-r.count);return t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),extra:t.jsx(no,{type:"secondary",children:a("settings.metricsDashboard.syncMismatchBreakdownSubtitle",{defaultValue:"Grouped by execute sync mismatch reason"})}),children:n.length===0?t.jsx(Ue,{image:Ue.PRESENTED_IMAGE_SIMPLE,description:a("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(Nt,{children:t.jsxs(ia,{data:n,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[t.jsx(cs,{strokeDasharray:"3 3"}),t.jsx(ds,{type:"number",allowDecimals:!1}),t.jsx(us,{dataKey:"label",type:"category",width:110}),t.jsx(Vt,{formatter:r=>[r.toLocaleString(),a("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})],labelFormatter:r=>a("settings.metricsDashboard.syncMismatchReasonLabel",{defaultValue:"Reason: {{label}}",label:r})}),t.jsx(_s,{dataKey:"count",fill:"var(--lotus-chart-danger)",radius:[0,6,6,0],name:a("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})})]})})})})},{Text:oo}=de,lo=({data:e,loading:s})=>{const{t:a}=ne();return s?t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.charts.tokenUsageOverTime"),children:t.jsx(mt,{active:!0,paragraph:{rows:5}})}):t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.charts.tokenUsageOverTime"),children:e.length===0?t.jsx(Ue,{image:Ue.PRESENTED_IMAGE_SIMPLE,description:a("settings.charts.noTokenUsage")}):t.jsxs(t.Fragment,{children:[t.jsx(oo,{type:"secondary",children:a("settings.charts.tokenUsageDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(Nt,{children:t.jsxs(sn,{data:e,children:[t.jsx(cs,{strokeDasharray:"3 3"}),t.jsx(ds,{dataKey:"label",minTickGap:24}),t.jsx(us,{allowDecimals:!1,tickFormatter:ca}),t.jsx(Vt,{formatter:n=>dn(n)}),t.jsx(oa,{}),t.jsx(Rt,{type:"monotone",dataKey:"totalTokens",name:a("settings.charts.total"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),t.jsx(Rt,{type:"monotone",dataKey:"promptTokens",name:a("settings.charts.prompt"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),t.jsx(Rt,{type:"monotone",dataKey:"completionTokens",name:a("settings.charts.completion"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{Text:co}=de,Xt=({title:e,subtitle:s,emptyText:a,color:n="var(--lotus-chart-primary)",data:r,loading:o,countLabel:l})=>{const{t:u}=ne();return o?t.jsx(N,{size:"small",className:"lotus-metric-card",title:e,children:t.jsx(mt,{active:!0,paragraph:{rows:5}})}):t.jsx(N,{size:"small",className:"lotus-metric-card",title:e,children:r.length===0?t.jsx(Ue,{image:Ue.PRESENTED_IMAGE_SIMPLE,description:a}):t.jsxs(t.Fragment,{children:[s?t.jsx(co,{type:"secondary",children:s}):null,t.jsx("div",{style:{width:"100%",minWidth:0,height:280,marginTop:s?12:0},children:t.jsx(Nt,{children:t.jsxs(ia,{data:r,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[t.jsx(cs,{strokeDasharray:"3 3"}),t.jsx(ds,{type:"number",allowDecimals:!1}),t.jsx(us,{dataKey:"label",type:"category",width:110}),t.jsx(Vt,{formatter:m=>[m.toLocaleString(),l??u("settings.metricsDashboard.calls",{defaultValue:"Calls"})],labelFormatter:(m,g)=>{var j,x;const d=(x=(j=g==null?void 0:g[0])==null?void 0:j.payload)==null?void 0:x.meta;return d?`${m} · ${d}`:String(m)}}),t.jsx(_s,{dataKey:"count",fill:n,radius:[0,6,6,0],name:l??u("settings.metricsDashboard.calls",{defaultValue:"Calls"})})]})})})]})})},{useToken:uo}=_e,Oa=({summary:e,loading:s})=>{const{t:a}=ne(),{token:n}=uo();if(s)return t.jsx(mt,{active:!0,paragraph:{rows:1}});const r=[{key:"skill-load-calls",title:a("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:a("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:a("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:a("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:a("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:a("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(o=>o.value>0);return r.length===0?null:t.jsx(Ge,{gutter:[n.marginSM,n.marginSM],children:r.map(o=>t.jsx(me,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:o.title,value:o.value,precision:0,formatter:ct,valueStyle:{color:o.color}})})},o.key))})},{Text:wt}=de,{useToken:go}=_e,Na=e=>"date"in e?e.date:e.label,mo=(e,s)=>{if(s<=0||e<=0)return"var(--lotus-heat-0)";const a=e/s;return a>=.8?"var(--lotus-heat-4)":a>=.6?"var(--lotus-heat-3)":a>=.4?"var(--lotus-heat-2)":a>=.2?"var(--lotus-heat-1)":"var(--lotus-heat-0)"},ys=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),a=Math.floor(s/60),n=s%60;if(a>=60){const r=Math.floor(a/60),o=a%60;return`${r}h ${o}m`}return a>0?`${a}m ${n}s`:`${n}s`},Va=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString()},Us=e=>{const s=Object.entries(e??{}).sort((a,n)=>n[1]-a[1]);return s.length===0?"-":s.slice(0,6).map(([a,n])=>`${a}: ${ln(n)}`).join(" • ")},Ks=(e,s=320)=>({width:"100%",display:"grid",gridTemplateColumns:`repeat(auto-fit, minmax(${s}px, 1fr))`,gap:e}),po=()=>{const{t:e}=ne(),{token:s}=go(),a=Cn(h=>h.themeMode)==="dark",[n,r]=i.useState(void 0),[o,l]=i.useState(void 0),[u,m]=i.useState(void 0),[g,d]=i.useState(30),[j,x]=i.useState("daily"),{summary:S,modelMetrics:y,sessions:b,timeline:R,memorySummary:P,memoryTimeline:C,sessionDetail:I,isLoading:p,isRefreshing:k,isSessionDetailLoading:V,error:F,refresh:U,loadSessionDetail:ae,clearSessionDetail:q}=Ii({filters:{startDate:n,endDate:o,model:u,days:g,granularity:j}}),{summary:v,endpointMetrics:T,requests:D,isLoading:A,isRefreshing:ee,error:O,refresh:Q}=Pi({filters:{startDate:n,endDate:o,days:g,model:u}}),{data:W,isLoading:re,isRefreshing:ue,error:be,refresh:c}=Ri({filters:{startDate:n,endDate:o,days:g,model:u}}),E=i.useMemo(()=>R.map(h=>({label:Na(h),promptTokens:h.total_token_usage.prompt_tokens,completionTokens:h.total_token_usage.completion_tokens,totalTokens:h.total_token_usage.total_tokens})),[R]),M=i.useMemo(()=>y.map(h=>({label:h.model,value:h.model})),[y]),G=i.useMemo(()=>{const h=R.map(ve=>({label:Na(ve),sessions:ve.total_sessions,tokens:ve.total_token_usage.total_tokens})),le=h.reduce((ve,$e)=>Math.max(ve,$e.sessions),0);return{points:h,maxSessions:le}},[R]),Z=i.useMemo(()=>{const h=D.map(ve=>ve.duration_ms).filter(ve=>typeof ve=="number"&&ve>0).sort((ve,$e)=>ve-$e);if(h.length===0)return null;const le=Math.ceil(h.length*.95)-1;return h[Math.max(0,Math.min(le,h.length-1))]},[D]),ge=i.useMemo(()=>[{title:e("settings.metricsDashboard.roundColumns.round"),dataIndex:"round_id",key:"round_id",render:h=>`${h.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:h=>ys(h)},{title:e("settings.metricsDashboard.roundColumns.tokens"),key:"tokens",render:(h,le)=>os(le.token_usage.total_tokens)},{title:e("settings.metricsDashboard.roundColumns.toolCalls"),key:"tool_calls",render:(h,le)=>le.tool_calls.length}],[e]),xe=i.useMemo(()=>{const h=(S==null?void 0:S.total_sessions)??0,le=(S==null?void 0:S.total_tokens.total_tokens)??0,ve=(S==null?void 0:S.total_tool_calls)??0,$e=(S==null?void 0:S.active_sessions)??0,Ce=b.reduce((nt,Ls)=>nt+Ls.total_rounds,0),Be=(S==null?void 0:S.total_tokens_saved)??0,bt=(S==null?void 0:S.tool_context_tokens_saved)??0,Es=(S==null?void 0:S.non_tool_compression_tokens_saved)??0,Ps=(S==null?void 0:S.prompt_cached_tool_outputs)??0,Ds=(S==null?void 0:S.total_compression_events)??0,Pt=(v==null?void 0:v.total_requests)??0,$t=(v==null?void 0:v.total_tokens.total_tokens)??0,Bt=(v==null?void 0:v.failed_requests)??0,Is=D.filter(nt=>nt.is_stream).length,Fs=h>0?$e/h*100:0,As=Pt>0?Bt/Pt*100:0,ps=D.length>0?Is/D.length*100:0,Rs=le>0?Number((Be/le*100).toFixed(1)):0,zs=Be>0?Number((bt/Be*100).toFixed(1)):0;return[{title:e("settings.metricsDashboard.compactStats.avgTokensPerSession"),value:h>0?Math.round(le/h):0},{title:e("settings.metricsDashboard.compactStats.savedTokens",{defaultValue:"Saved Tokens"}),value:Be},{title:e("settings.metricsDashboard.compactStats.toolContextSavedTokens",{defaultValue:"Tool Context Saved Tokens"}),value:bt},{title:e("settings.metricsDashboard.compactStats.nonToolCompressionSavedTokens",{defaultValue:"Non-Tool Compression Saved Tokens"}),value:Es},{title:e("settings.metricsDashboard.compactStats.savedTokenRatio",{defaultValue:"Saved / Chat Tokens"}),value:Rs,suffix:"%"},{title:e("settings.metricsDashboard.compactStats.toolSavedShare",{defaultValue:"Tool Share of Saved Tokens"}),value:zs,suffix:"%"},{title:e("settings.metricsDashboard.compactStats.promptCachedToolOutputs",{defaultValue:"Prompt-Cached Tool Outputs"}),value:Ps},{title:e("settings.metricsDashboard.compactStats.compressionEvents",{defaultValue:"Compression Events"}),value:Ds},{title:e("settings.metricsDashboard.compactStats.avgRoundsPerSession"),value:h>0?Number((Ce/h).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.toolCallsPerSession"),value:h>0?Number((ve/h).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.activeSessionRate"),value:Number(Fs.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.avgTokensPerForward"),value:Pt>0?Math.round($t/Pt):0},{title:e("settings.metricsDashboard.compactStats.forwardErrorRate"),value:Number(As.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.streamingRatio"),value:Number(ps.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.p95ForwardLatency"),value:ys(Z)},{title:e("settings.metricsDashboard.compactStats.modelCoverage"),value:y.length},{title:e("settings.metricsDashboard.compactStats.endpointCoverage"),value:T.length}]},[T.length,D,v,y.length,Z,b,S,e]),je=i.useMemo(()=>{const h=(v==null?void 0:v.total_requests)??0,le=(v==null?void 0:v.failed_requests)??0,ve=D.filter(Be=>Be.is_stream).length,$e=D.length>0?ve/D.length*100:0,Ce=h>0?le/h*100:0;return[{title:e("settings.metricsDashboard.forward.performance.p95Latency",{defaultValue:"P95 Latency"}),value:ys(Z)},{title:e("settings.metricsDashboard.forward.performance.errorRate",{defaultValue:"Error Rate"}),value:Number(Ce.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.streamingRatio",{defaultValue:"Streaming Ratio"}),value:Number($e.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.endpointCoverage",{defaultValue:"Endpoint Coverage"}),value:T.length}]},[T.length,D,v,Z,e]),$=i.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(h=>h.count>0):[],[e,W]),Te=i.useMemo(()=>((W==null?void 0:W.top_skills)??[]).map(h=>({label:h.skill_id,count:h.count})),[W]),Xe=i.useMemo(()=>((W==null?void 0:W.top_mcp_servers)??[]).map(h=>({label:h.server_id,count:h.count,meta:e("settings.metricsDashboard.skillsAndMcp.meta.uniqueTools",{defaultValue:"{{count}} tools",count:h.unique_tools})})),[e,W]),Ie=i.useMemo(()=>((W==null?void 0:W.top_mcp_tools)??[]).map(h=>({label:h.tool_name,count:h.count,meta:h.server_id})),[W]),Ve=i.useMemo(()=>((W==null?void 0:W.top_core_tools)??[]).map(h=>({label:h.name,count:h.count})),[W]),Le=I==null?void 0:I.session,Ae=k||ee||ue;return t.jsxs(L,{direction:"vertical",size:s.marginMD,style:{width:"100%"},children:[F?t.jsx(He,{type:"error",showIcon:!0,message:F}):null,O?t.jsx(He,{type:"error",showIcon:!0,message:O}):null,be?t.jsx(He,{type:"error",showIcon:!0,message:be}):null,t.jsx(N,{size:"small",title:e("settings.metricsDashboard.filtersTitle"),extra:t.jsx(z,{icon:t.jsx(Ot,{}),loading:Ae,onClick:()=>{U(),Q(),c()},children:e("settings.metricsDashboard.refresh")}),children:t.jsxs(L,{wrap:!0,children:[t.jsx(va,{placeholder:e("settings.metricsDashboard.startDate"),onChange:h=>{r(h?h.format("YYYY-MM-DD"):void 0)}}),t.jsx(va,{placeholder:e("settings.metricsDashboard.endDate"),onChange:h=>{l(h?h.format("YYYY-MM-DD"):void 0)}}),t.jsx(se,{allowClear:!0,style:{minWidth:180},placeholder:e("settings.metricsDashboard.model"),value:u,options:M,onChange:h=>{m(h)}}),t.jsx(se,{style:{width:120},value:g,options:[7,14,30,90].map(h=>({label:e("settings.metricsDashboard.daysOption",{value:h}),value:h})),onChange:h=>{d(h)}}),t.jsx(se,{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:h=>{x(h)}})]})}),t.jsx(N,{size:"small",title:e("settings.metricsDashboard.dashboardTitle"),children:t.jsx(Ts,{size:"small",destroyInactiveTabPane:!0,items:[{key:"overview",label:e("settings.metricsDashboard.tabs.overview"),children:t.jsxs(L,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(N,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.overviewSections.scaleTitle",{defaultValue:"Scale & Activity"}),extra:t.jsx(wt,{type:"secondary",children:e("settings.metricsDashboard.overviewSections.scaleSubtitle",{defaultValue:"Current usage volume across chat, forward, skills, and memory."})}),children:t.jsxs(L,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(Ra,{summary:S,sessions:b,loading:p}),t.jsx(Fa,{summary:v,loading:A}),t.jsx(Oa,{summary:W,loading:re}),t.jsx(Aa,{summary:P,loading:p})]})}),t.jsxs(N,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.overviewSections.efficiencyTitle",{defaultValue:"Compression & Efficiency Advantage"}),extra:t.jsx(wt,{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:xe.map(h=>t.jsx(me,{xs:24,sm:12,md:8,xl:6,children:t.jsx("div",{style:{borderRadius:s.borderRadiusSM,padding:s.paddingXS,background:a?"rgba(255, 255, 255, 0.05)":"rgba(255, 255, 255, 0.82)",border:a?"1px solid rgba(255,255,255,0.08)":"1px solid rgba(148,163,184,0.18)"},children:t.jsx(Ee,{title:h.title,value:h.value,suffix:h.suffix,formatter:typeof h.value=="number"?ct:void 0,valueStyle:{fontSize:s.fontSizeHeading4}})})},h.title))}),t.jsx(wt,{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(L,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(Ra,{summary:S,sessions:b,loading:p}),t.jsxs("div",{style:Ks(s.marginSM,360),children:[t.jsx(lo,{data:E,loading:p}),t.jsx(Zi,{data:y,loading:p})]}),t.jsxs("div",{style:Ks(s.marginSM,360),children:[t.jsx(io,{breakdown:S==null?void 0:S.sync_mismatch_breakdown,loading:p}),t.jsx(N,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.activityHeatmapTitle"),children:G.points.length===0?t.jsx(wt,{type:"secondary",children:e("settings.metricsDashboard.noActivity")}):t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(72px, 1fr))",gap:s.marginXS},children:G.points.map(h=>t.jsxs("div",{style:{borderRadius:s.borderRadiusSM,padding:s.paddingXS,background:mo(h.sessions,G.maxSessions),minHeight:64,color:h.sessions>0?"var(--lotus-metric-text-strong)":s.colorTextSecondary},children:[t.jsx("div",{style:{fontSize:12,lineHeight:1.2},children:h.label}),t.jsx("div",{style:{fontWeight:600,marginTop:4},children:e("settings.metricsDashboard.sessionsCount",{count:h.sessions})}),t.jsx("div",{style:{fontSize:12},children:e("settings.metricsDashboard.tokensAmount",{value:ca(h.tokens)})})]},h.label))})})]})]})},{key:"skills-and-mcp",label:e("settings.metricsDashboard.tabs.skillsAndMcp",{defaultValue:"Skills & MCP"}),children:t.jsxs(L,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(Oa,{summary:W,loading:re}),t.jsxs("div",{style:Ks(s.marginSM,360),children:[t.jsx(Xt,{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:$,loading:re,color:"var(--lotus-chart-primary)"}),t.jsx(Xt,{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:Te,loading:re,color:"var(--lotus-chart-purple)"}),t.jsx(Xt,{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:Xe,loading:re,color:"var(--lotus-chart-cyan)"}),t.jsx(Xt,{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:Ie,loading:re,color:"var(--lotus-chart-accent)"}),t.jsx(Xt,{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:Ve,loading:re,color:"var(--lotus-chart-secondary)"})]})]})},{key:"forward",label:e("settings.metricsDashboard.tabs.forward",{defaultValue:"Forward"}),children:t.jsxs(L,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(Fa,{summary:v,loading:A}),t.jsx(N,{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:je.map(h=>t.jsx(me,{xs:24,sm:12,xl:6,children:t.jsx("div",{style:{borderRadius:s.borderRadiusSM,padding:s.paddingXS,background:a?"rgba(255, 255, 255, 0.05)":"rgba(255, 255, 255, 0.82)",border:a?"1px solid rgba(255,255,255,0.08)":"1px solid rgba(148,163,184,0.18)"},children:t.jsx(Ee,{title:h.title,value:h.value,suffix:h.suffix,valueStyle:{fontSize:s.fontSizeHeading4}})})},h.title))})}),t.jsx(Li,{data:T,loading:A})]})},{key:"memory",label:e("settings.metricsDashboard.tabs.memory",{defaultValue:"Memory"}),children:t.jsxs(L,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(Aa,{summary:P,loading:p}),t.jsx(Wi,{data:C,loading:p}),t.jsx(N,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.memory.breakdownTitle",{defaultValue:"Memory Breakdown"}),children:t.jsxs(Oe,{size:"small",bordered:!0,column:1,children:[t.jsx(Oe.Item,{label:e("settings.metricsDashboard.memory.byType",{defaultValue:"By Type"}),children:Us(P==null?void 0:P.by_type)}),t.jsx(Oe.Item,{label:e("settings.metricsDashboard.memory.byStatus",{defaultValue:"By Status"}),children:Us(P==null?void 0:P.by_status)}),t.jsx(Oe.Item,{label:e("settings.metricsDashboard.memory.byScope",{defaultValue:"By Scope"}),children:Us(P==null?void 0:P.by_scope)}),t.jsx(Oe.Item,{label:e("settings.metricsDashboard.memory.lastDream",{defaultValue:"Last Dream"}),children:Va(P==null?void 0:P.last_dream_at)}),t.jsx(Oe.Item,{label:e("settings.metricsDashboard.memory.lastReindex",{defaultValue:"Last Reindex"}),children:Va(P==null?void 0:P.last_reindex_at)})]})})]})},{key:"records",label:e("settings.metricsDashboard.tabs.records"),children:t.jsx(Ts,{size:"small",destroyInactiveTabPane:!0,items:[{key:"sessions",label:e("settings.metricsDashboard.sessionsTabLabel",{count:b.length}),children:t.jsx(N,{size:"small",extra:t.jsx(wt,{type:"secondary",children:e("settings.metricsDashboard.sessionsHint")}),children:t.jsx(ao,{sessions:b,loading:p,onSelectSession:h=>{ae(h)}})})},{key:"forward-requests",label:e("settings.metricsDashboard.forwardTabLabel",{count:D.length}),children:t.jsx(N,{size:"small",children:t.jsx(qi,{requests:D,loading:A})})}]})}]})}),t.jsx(Qe,{title:e("settings.metricsDashboard.sessionMetricsTitle"),open:!!I,onCancel:q,onOk:q,width:960,destroyOnClose:!0,children:V?t.jsx(wt,{children:e("settings.metricsDashboard.loadingSessionDetails")}):Le?t.jsxs(L,{direction:"vertical",style:{width:"100%"},size:s.marginMD,children:[t.jsxs(Oe,{size:"small",bordered:!0,column:2,children:[t.jsx(Oe.Item,{label:e("settings.metricsDashboard.sessionDetail.sessionId"),span:2,children:Le.session_id}),t.jsx(Oe.Item,{label:e("settings.metricsDashboard.sessionDetail.model"),children:Le.model}),t.jsx(Oe.Item,{label:e("settings.metricsDashboard.sessionDetail.status"),children:Le.status}),t.jsx(Oe.Item,{label:e("settings.metricsDashboard.sessionDetail.duration"),children:ys(Le.duration_ms)}),t.jsx(Oe.Item,{label:e("settings.metricsDashboard.sessionDetail.messages"),children:Le.message_count}),t.jsx(Oe.Item,{label:e("settings.metricsDashboard.sessionDetail.totalTokens"),children:os(Le.total_token_usage.total_tokens)}),t.jsx(Oe.Item,{label:e("settings.metricsDashboard.sessionDetail.toolCalls"),children:Le.tool_call_count})]}),t.jsx(at,{rowKey:"round_id",size:"small",columns:ge,dataSource:I.rounds,pagination:{pageSize:6,showSizeChanger:!1}})]}):t.jsx(wt,{type:"secondary",children:e("settings.metricsDashboard.noDetail")})})]})},{Text:fs}=de,{useToken:ho}=_e,yo=e=>{const s=e==null?void 0:e.hooks,a=s==null?void 0:s.image_fallback,n=String((a==null?void 0:a.mode)||"placeholder").trim().toLowerCase();return n==="error"||n==="ocr"||n==="vision"?n:"placeholder"},fo=e=>{const s=e==null?void 0:e.hooks,a=s==null?void 0:s.image_fallback,n=a==null?void 0:a.enabled;return typeof n=="boolean"?n:!1},xo=()=>{const{t:e}=ne(),{token:s}=ho(),[a,n]=Lt.useMessage(),[r,o]=i.useState(!1),[l,u]=i.useState(!0),[m,g]=i.useState("placeholder"),d=i.useMemo(()=>[{label:e("settings.hooksTab.mode.placeholder"),value:"placeholder"},{label:e("settings.hooksTab.mode.error"),value:"error"},{label:e("settings.hooksTab.mode.ocr"),value:"ocr"},{label:e("settings.hooksTab.mode.vision"),value:"vision"}],[e]),j=i.useCallback(async()=>{o(!0);try{const b=await ze.getBambooConfig();u(fo(b)),g(yo(b))}catch(b){a.error(b instanceof Error?b.message:e("settings.hooksTab.loadFailed"))}finally{o(!1)}},[a,e]),x=i.useCallback(async(b,R)=>{await ze.setBambooConfig({hooks:{image_fallback:{enabled:b,mode:R}}})},[]),S=i.useCallback(async b=>{o(!0);try{await x(b,m),a.success(e(b?"settings.hooksTab.enabled":"settings.hooksTab.disabled")),await j()}catch(R){a.error(R instanceof Error?R.message:e("settings.hooksTab.updateFailed"))}finally{o(!1)}},[j,m,a,x,e]),y=i.useCallback(async b=>{var R;o(!0);try{await x(l,b),a.success(e("settings.hooksTab.modeUpdated",{mode:((R=d.find(P=>P.value===b))==null?void 0:R.label)??b})),await j()}catch(P){a.error(P instanceof Error?P.message:e("settings.hooksTab.modeUpdateFailed"))}finally{o(!1)}},[l,j,d,a,x,e]);return i.useEffect(()=>{j()},[j]),t.jsxs(X,{vertical:!0,gap:s.marginLG,children:[n,t.jsx(N,{size:"small",loading:r,children:t.jsxs(X,{vertical:!0,gap:s.marginXS,children:[t.jsx(fs,{strong:!0,children:e("settings.hooksTab.title")}),t.jsxs(X,{align:"center",justify:"space-between",children:[t.jsx(fs,{children:e("settings.hooksTab.enableImagePreflight")}),t.jsx(ye,{checked:l,onChange:S})]}),t.jsxs(X,{align:"center",justify:"space-between",children:[t.jsx(fs,{children:e("settings.hooksTab.modeLabel")}),t.jsx(se,{style:{width:180},value:m,options:d,onChange:y,disabled:!l})]}),t.jsx(fs,{type:"secondary",style:{fontSize:s.fontSizeSM},children:e("settings.hooksTab.description")})]})})]})};function De(e){return String(e??"").trim()||void 0}function un(e){return{type:"interval",every_seconds:e}}function bo(e){const s=De(e);if(!s)return{days:[],invalid:!1};const n=s.split(/[\s,]+/).filter(Boolean).map(l=>Number(l)),r=n.some(l=>!Number.isInteger(l)||l<1||l>31);return{days:Array.from(new Set(n.filter(l=>Number.isInteger(l)&&l>=1&&l<=31))),invalid:r}}function $a(e){switch(e.trigger_type){case"interval":{const s=Number(e.interval_seconds||0);return s<=0?{errorKey:"settings.schedulesTab.validation.intervalRequired"}:{trigger:un(s)}}case"daily":{const s=e.daily_hour,a=e.daily_minute;return s==null||a==null?{errorKey:"settings.schedulesTab.validation.triggerRequired"}:{trigger:{type:"daily",hour:s,minute:a,second:0}}}case"weekly":{const s=e.weekly_weekdays||[],a=e.weekly_hour,n=e.weekly_minute;return s.length===0?{errorKey:"settings.schedulesTab.validation.weekdaysRequired"}:a==null||n==null?{errorKey:"settings.schedulesTab.validation.triggerRequired"}:{trigger:{type:"weekly",weekdays:s,hour:a,minute:n,second:0}}}case"monthly":{const{days:s,invalid:a}=bo(e.monthly_days);if(a)return{errorKey:"settings.schedulesTab.validation.invalidMonthDays"};if(s.length===0)return{errorKey:"settings.schedulesTab.validation.monthDaysRequired"};const n=e.monthly_hour,r=e.monthly_minute;return n==null||r==null?{errorKey:"settings.schedulesTab.validation.triggerRequired"}:{trigger:{type:"monthly",days:s,hour:n,minute:r,second:0}}}case"cron":{const s=De(e.cron_expr);return s?{trigger:{type:"cron",expr:s}}:{errorKey:"settings.schedulesTab.validation.cronRequired"}}default:return{errorKey:"settings.schedulesTab.validation.triggerRequired"}}}function Ba(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"}}}const{Text:Fe}=de,it=na.getInstance();function vo(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 jo=[{label:oe.t("settings.schedulesTab.weekdays.mon"),value:"mon"},{label:oe.t("settings.schedulesTab.weekdays.tue"),value:"tue"},{label:oe.t("settings.schedulesTab.weekdays.wed"),value:"wed"},{label:oe.t("settings.schedulesTab.weekdays.thu"),value:"thu"},{label:oe.t("settings.schedulesTab.weekdays.fri"),value:"fri"},{label:oe.t("settings.schedulesTab.weekdays.sat"),value:"sat"},{label:oe.t("settings.schedulesTab.weekdays.sun"),value:"sun"}];function To(e){return(e==null?void 0:e.type)==="interval"?e.every_seconds:null}function _o(e){switch(e.type){case"interval":return oe.t("settings.schedulesTab.triggerLabels.interval",{type:oe.t("settings.schedulesTab.triggerTypes.interval"),seconds:e.every_seconds});case"daily":return oe.t("settings.schedulesTab.triggerLabels.daily",{type:oe.t("settings.schedulesTab.triggerTypes.daily"),time:`${String(e.hour).padStart(2,"0")}:${String(e.minute).padStart(2,"0")}`});case"weekly":return oe.t("settings.schedulesTab.triggerLabels.weekly",{type:oe.t("settings.schedulesTab.triggerTypes.weekly"),weekdays:e.weekdays.join(", ")});case"monthly":return oe.t("settings.schedulesTab.triggerLabels.monthly",{type:oe.t("settings.schedulesTab.triggerTypes.monthly"),days:e.days.join(", ")});case"cron":return oe.t("settings.schedulesTab.triggerLabels.cron",{type:oe.t("settings.schedulesTab.triggerTypes.cron"),expr:e.expr})}}function So(e){switch(e==null?void 0:e.type){case"skip":return oe.t("settings.schedulesTab.misfirePolicyOptions.skip");case"catch_up_all":return oe.t("settings.schedulesTab.misfirePolicyOptions.catchUpAll");case"catch_up_window":return oe.t("settings.schedulesTab.misfirePolicyOptions.catchUpWindow");case"run_once":default:return oe.t("settings.schedulesTab.misfirePolicyOptions.runOnce")}}function ko(e){switch(e){case"allow":return oe.t("settings.schedulesTab.overlapPolicyOptions.allow");case"skip":return oe.t("settings.schedulesTab.overlapPolicyOptions.skip");case"queue_one":default:return oe.t("settings.schedulesTab.overlapPolicyOptions.queueOne")}}function wo(e){var s;return(s=e.state)!=null&&s.next_fire_at?String(e.state.next_fire_at):"-"}function Co(e){var s,a;return(s=e.state)!=null&&s.last_success_at?String(e.state.last_success_at):(a=e.state)!=null&&a.last_finished_at?String(e.state.last_finished_at):"-"}function Mo(e){var s,a,n,r;return((s=e.state)==null?void 0:s.running_run_count)>0?{color:"processing",label:oe.t("settings.schedulesTab.statusLabels.running"),detail:oe.t("settings.schedulesTab.statusDetails.active",{count:e.state.running_run_count})}:(((a=e.state)==null?void 0:a.queued_run_count)||0)>0?{color:"gold",label:oe.t("settings.schedulesTab.statusLabels.queued"),detail:oe.t("settings.schedulesTab.statusDetails.pending",{count:e.state.queued_run_count})}:(((n=e.state)==null?void 0:n.consecutive_failures)||0)>0?{color:"error",label:oe.t("settings.schedulesTab.statusLabels.failing"),detail:oe.t("settings.schedulesTab.statusDetails.consecutiveFailures",{count:e.state.consecutive_failures})}:e.enabled?(r=e.state)!=null&&r.last_success_at?{color:"success",label:oe.t("settings.schedulesTab.statusLabels.healthy"),detail:oe.t("settings.schedulesTab.statusDetails.lastRunSucceeded")}:{color:"default",label:oe.t("settings.schedulesTab.statusLabels.idle")}:{color:"default",label:oe.t("settings.schedulesTab.statusLabels.disabled")}}function Eo(e){var a,n,r,o,l,u,m,g;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:((a=e.misfire_policy)==null?void 0:a.type)||"run_once",overlap_policy:e.overlap_policy||"queue_one",system_prompt:((n=e.run_config)==null?void 0:n.system_prompt)||"",task_message:((r=e.run_config)==null?void 0:r.task_message)||"",model:((o=e.run_config)==null?void 0:o.model)||"",workspace_path:((l=e.run_config)==null?void 0:l.workspace_path)||"",enhance_prompt:((u=e.run_config)==null?void 0:u.enhance_prompt)||"",auto_execute:!!((m=e.run_config)!=null&&m.auto_execute)};switch(((g=e.misfire_policy)==null?void 0:g.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 Ws({hourName:e,minuteName:s}){const{t:a}=ne();return t.jsxs(X,{gap:12,wrap:"wrap",children:[t.jsx(f.Item,{label:a("settings.schedulesTab.form.dailyHour"),name:e,style:{width:180},children:t.jsx(Me,{min:0,max:23,style:{width:"100%"}})}),t.jsx(f.Item,{label:a("settings.schedulesTab.form.dailyMinute"),name:s,style:{width:180},children:t.jsx(Me,{min:0,max:59,style:{width:"100%"}})})]})}function Po(){const{t:e}=ne(),[s,a]=Lt.useMessage(),[n,r]=i.useState(!1),[o,l]=i.useState([]),[u,m]=i.useState({open:!1,scheduleId:null,sessions:[],loading:!1}),[g,d]=i.useState({open:!1,scheduleId:null,runs:[],loading:!1}),[j,x]=i.useState({open:!1,schedule:null,saving:!1}),S=Qs(v=>v.close),[y]=f.useForm(),[b]=f.useForm(),R=f.useWatch("trigger_type",y),P=f.useWatch("misfire_policy",y),C=f.useWatch("trigger_type",b),I=f.useWatch("misfire_policy",b),p=i.useCallback(async()=>{r(!0);try{const v=await it.listSchedules();l(v.schedules||[])}catch(v){console.error("[Schedules] Failed to load schedules:",v),s.error(e("settings.schedulesTab.loadFailed"))}finally{r(!1)}},[s,e]),k=i.useCallback(async(v,T,D)=>{try{await D()}catch(A){console.error(`[Schedules] ${v}:`,A),s.error(e(T))}},[s,e]);i.useEffect(()=>{p()},[p]);const V=[{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")}],F=[{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")}],U=[{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")}],ae=(v,T)=>t.jsxs(t.Fragment,{children:[t.jsxs(X,{gap:12,wrap:"wrap",children:[t.jsx(f.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(H,{})}),t.jsx(f.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(se,{options:V})}),t.jsx(f.Item,{label:e("settings.schedulesTab.form.enabled"),name:"enabled",valuePropName:"checked",style:{width:120},children:t.jsx(ye,{})})]}),v==="interval"?t.jsx(f.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(Me,{min:1,style:{width:"100%"}})}):null,v==="daily"?t.jsx(Ws,{hourName:"daily_hour",minuteName:"daily_minute"}):null,v==="weekly"?t.jsxs(t.Fragment,{children:[t.jsx(f.Item,{label:e("settings.schedulesTab.form.weeklyWeekdays"),name:"weekly_weekdays",style:{minWidth:320},children:t.jsx(se,{mode:"multiple",options:jo})}),t.jsx(Ws,{hourName:"weekly_hour",minuteName:"weekly_minute"})]}):null,v==="monthly"?t.jsxs(t.Fragment,{children:[t.jsx(f.Item,{label:e("settings.schedulesTab.form.monthlyDays"),name:"monthly_days",style:{minWidth:320},children:t.jsx(H,{placeholder:e("settings.schedulesTab.form.monthlyDaysPlaceholder")})}),t.jsx(Ws,{hourName:"monthly_hour",minuteName:"monthly_minute"})]}):null,v==="cron"?t.jsx(f.Item,{label:e("settings.schedulesTab.form.cronExpr"),name:"cron_expr",children:t.jsx(H,{placeholder:e("settings.schedulesTab.form.cronExprPlaceholder")})}):null,t.jsxs(X,{gap:12,wrap:"wrap",children:[t.jsx(f.Item,{label:e("settings.schedulesTab.form.timezone"),name:"timezone",style:{flex:"1 1 240px"},children:t.jsx(H,{placeholder:e("settings.schedulesTab.form.timezonePlaceholder")})}),t.jsx(f.Item,{label:e("settings.schedulesTab.form.startAt"),name:"start_at",style:{flex:"1 1 240px"},children:t.jsx(H,{placeholder:e("settings.schedulesTab.form.datetimePlaceholder")})}),t.jsx(f.Item,{label:e("settings.schedulesTab.form.endAt"),name:"end_at",style:{flex:"1 1 240px"},children:t.jsx(H,{placeholder:e("settings.schedulesTab.form.datetimePlaceholder")})})]}),t.jsxs(X,{gap:12,wrap:"wrap",children:[t.jsx(f.Item,{label:e("settings.schedulesTab.form.misfirePolicy"),name:"misfire_policy",style:{flex:"1 1 240px"},children:t.jsx(se,{options:F})}),t.jsx(f.Item,{label:e("settings.schedulesTab.form.overlapPolicy"),name:"overlap_policy",style:{flex:"1 1 240px"},children:t.jsx(se,{options:U})})]}),T==="catch_up_window"?t.jsxs(X,{gap:12,wrap:"wrap",children:[t.jsx(f.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxRuns"),name:"catch_up_window_max_runs",style:{width:220},children:t.jsx(Me,{min:1,style:{width:"100%"}})}),t.jsx(f.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxLatenessSeconds"),name:"catch_up_window_max_lateness_seconds",style:{width:260},children:t.jsx(Me,{min:1,style:{width:"100%"}})})]}):null,t.jsx(f.Item,{label:e("settings.schedulesTab.form.taskMessage"),name:"task_message",children:t.jsx(H.TextArea,{rows:3,placeholder:e("settings.schedulesTab.form.taskMessagePlaceholder")})}),t.jsx(f.Item,{label:e("settings.schedulesTab.form.systemPrompt"),name:"system_prompt",children:t.jsx(H.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})}),t.jsxs(X,{gap:12,wrap:"wrap",children:[t.jsx(f.Item,{label:e("settings.schedulesTab.form.model"),name:"model",style:{flex:"1 1 240px"},children:t.jsx(H,{placeholder:e("settings.schedulesTab.form.modelPlaceholder")})}),t.jsx(f.Item,{label:e("settings.schedulesTab.form.workspacePath"),name:"workspace_path",style:{flex:"1 1 320px"},children:t.jsx(H,{placeholder:e("settings.schedulesTab.optional")})}),t.jsx(f.Item,{label:e("settings.schedulesTab.form.autoExecute"),name:"auto_execute",valuePropName:"checked",style:{width:160},children:t.jsx(ye,{})})]}),t.jsx(f.Item,{label:e("settings.schedulesTab.form.enhancePrompt"),name:"enhance_prompt",children:t.jsx(H.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})})]}),q=i.useMemo(()=>[{title:e("settings.schedulesTab.columns.name"),key:"name",render:(v,T)=>t.jsxs(X,{vertical:!0,gap:6,children:[t.jsx(Fe,{strong:!0,children:T.name}),t.jsxs(X,{gap:6,wrap:"wrap",children:[t.jsx(ie,{children:_o(T.trigger)}),T.timezone?t.jsx(ie,{color:"blue",children:T.timezone}):null,t.jsx(ie,{children:So(T.misfire_policy)}),t.jsx(ie,{children:ko(T.overlap_policy)})]})]})},{title:e("settings.schedulesTab.columns.status"),key:"status",render:(v,T)=>{const D=Mo(T);return t.jsxs(X,{vertical:!0,gap:4,children:[t.jsx(ie,{color:D.color,children:D.label}),D.detail?t.jsx(Fe,{type:"secondary",children:D.detail}):null]})}},{title:e("settings.schedulesTab.columns.activity"),key:"activity",render:(v,T)=>{var D,A,ee,O;return t.jsxs(X,{vertical:!0,gap:2,children:[t.jsx(Fe,{type:"secondary",children:e("settings.schedulesTab.activityLabels.queued",{count:((D=T.state)==null?void 0:D.queued_run_count)??0})}),t.jsx(Fe,{type:"secondary",children:e("settings.schedulesTab.activityLabels.running",{count:((A=T.state)==null?void 0:A.running_run_count)??0})}),t.jsx(Fe,{type:"secondary",children:e("settings.schedulesTab.activityLabels.ok",{count:((ee=T.state)==null?void 0:ee.total_success_count)??0})}),t.jsx(Fe,{type:"secondary",children:e("settings.schedulesTab.activityLabels.fail",{count:((O=T.state)==null?void 0:O.total_failure_count)??0})})]})}},{title:e("settings.schedulesTab.columns.nextRun"),key:"next_run_at",render:(v,T)=>t.jsx(Fe,{type:"secondary",children:wo(T)})},{title:e("settings.schedulesTab.columns.lastRun"),key:"last_run_at",render:(v,T)=>t.jsx(Fe,{type:"secondary",children:Co(T)})},{title:e("settings.schedulesTab.columns.autoExecute"),key:"auto_execute",render:(v,T)=>{var D,A;return t.jsx(Fe,{type:(D=T.run_config)!=null&&D.auto_execute?void 0:"secondary",children:(A=T.run_config)!=null&&A.auto_execute?e("settings.schedulesTab.yes"):e("settings.schedulesTab.no")})}},{title:e("settings.schedulesTab.columns.model"),key:"model",render:(v,T)=>{var D;return t.jsx(Fe,{type:"secondary",children:(D=T.run_config)!=null&&D.model?String(T.run_config.model):"-"})}},{title:e("settings.schedulesTab.columns.enabled"),key:"enabled",render:(v,T)=>t.jsx(ye,{checked:T.enabled,onChange:async D=>{await k("Failed to toggle","settings.schedulesTab.updateFailed",async()=>{await it.patchSchedule(T.id,{enabled:D}),await p()})}})},{title:e("settings.schedulesTab.columns.actions"),key:"actions",render:(v,T)=>{const D=t.jsx(Me,{min:1,value:To(T.trigger)??void 0,disabled:T.trigger.type!=="interval",onChange:async A=>{const ee=typeof A=="number"?A:null;!ee||ee<=0||await k("Failed to patch interval","settings.schedulesTab.updateFailed",async()=>{await it.patchSchedule(T.id,{trigger:un(ee)}),await p()})}});return t.jsxs(X,{vertical:!0,gap:8,children:[t.jsxs(X,{gap:8,wrap:"wrap",children:[t.jsx(z,{size:"small",onClick:()=>{x({open:!0,schedule:T,saving:!1}),b.setFieldsValue(Eo(T))},children:e("settings.schedulesTab.actions.edit")}),t.jsx(z,{size:"small",onClick:async()=>{await k("Failed to run now","settings.schedulesTab.runNowFailed",async()=>{await it.runScheduleNow(T.id),s.success(e("settings.schedulesTab.enqueuedRun")),await p()})},children:e("settings.schedulesTab.actions.runNow")}),t.jsx(z,{size:"small",onClick:async()=>{m(A=>({...A,open:!0,scheduleId:T.id,loading:!0,sessions:[]}));try{const A=await it.listScheduleSessions(T.id);m(ee=>({...ee,open:!0,scheduleId:T.id,loading:!1,sessions:(A.sessions||[]).map(O=>({id:O.id,title:O.title,updated_at:O.updated_at}))}))}catch(A){console.error("[Schedules] Failed to list sessions:",A),s.error(e("settings.schedulesTab.loadSessionsFailed")),m(ee=>({...ee,loading:!1}))}},children:e("settings.schedulesTab.actions.sessions")}),t.jsx(z,{size:"small",onClick:async()=>{d(A=>({...A,open:!0,scheduleId:T.id,loading:!0,runs:[]}));try{const A=await it.listScheduleRuns(T.id);d(ee=>({...ee,open:!0,scheduleId:T.id,loading:!1,runs:A.runs||[]}))}catch(A){console.error("[Schedules] Failed to list runs:",A),s.error(e("settings.schedulesTab.loadRunsFailed")),d(ee=>({...ee,loading:!1}))}},children:e("settings.schedulesTab.actions.runs")}),t.jsx(z,{danger:!0,size:"small",onClick:async()=>{await k("Failed to delete","settings.schedulesTab.deleteFailed",async()=>{await it.deleteSchedule(T.id),s.success(e("settings.schedulesTab.deleted")),await p()})},children:e("settings.schedulesTab.actions.delete")})]}),t.jsxs(X,{gap:8,align:"center",wrap:"wrap",children:[t.jsx(Fe,{type:"secondary",children:e("settings.schedulesTab.columns.intervalSeconds")}),T.trigger.type==="interval"?D:t.jsx(ke,{title:e("settings.schedulesTab.nonIntervalReadOnly"),children:t.jsx("span",{children:D})})]})]})}}],[b,s,p,k,e]);return t.jsxs(X,{vertical:!0,gap:16,children:[a,t.jsx(N,{title:e("settings.schedulesTab.createTitle"),className:"lotus-settings-card",children:t.jsxs(f,{form:y,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 v=>{try{const T=!!v.auto_execute,D=De(v.task_message),A=De(v.model);if(T&&!D){s.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:ee,errorKey:O}=$a(v);if(!ee){s.error(e(O||"settings.schedulesTab.validation.triggerRequired"));return}await it.createSchedule({name:String(v.name||"").trim(),trigger:ee,timezone:De(v.timezone),start_at:De(v.start_at),end_at:De(v.end_at),misfire_policy:Ba(v),overlap_policy:v.overlap_policy,enabled:!!v.enabled,run_config:{system_prompt:De(v.system_prompt),task_message:D,model:A,workspace_path:De(v.workspace_path),enhance_prompt:De(v.enhance_prompt),auto_execute:T}}),s.success(e("settings.schedulesTab.created")),y.resetFields(),await p()}catch(T){console.error("[Schedules] Failed to create schedule:",T),s.error(e("settings.schedulesTab.createFailed"))}},children:[ae(R,P),t.jsx(z,{type:"primary",htmlType:"submit",children:e("settings.schedulesTab.actions.create")})]})}),t.jsx(N,{title:e("settings.schedulesTab.listTitle"),className:"lotus-settings-card",extra:t.jsx(z,{onClick:()=>void p(),loading:n,children:e("settings.schedulesTab.actions.refresh")}),children:t.jsx(at,{rowKey:"id",columns:q,dataSource:o,loading:n,pagination:{pageSize:10},scroll:{x:1500}})}),t.jsx(Qe,{title:e("settings.schedulesTab.scheduleSessionsTitle"),open:u.open,onCancel:()=>m(v=>({...v,open:!1,scheduleId:null})),footer:null,children:u.loading?t.jsx(Fe,{type:"secondary",children:e("settings.schedulesTab.loading")}):t.jsx(X,{vertical:!0,gap:8,children:u.sessions.length===0?t.jsx(Fe,{type:"secondary",children:e("settings.schedulesTab.noSessionsYet")}):u.sessions.map(v=>t.jsxs(X,{justify:"space-between",align:"center",children:[t.jsxs(X,{vertical:!0,style:{minWidth:0},children:[t.jsx(Fe,{strong:!0,ellipsis:!0,children:v.title}),t.jsxs(Fe,{type:"secondary",ellipsis:!0,children:[v.id," • ",v.updated_at]})]}),t.jsx(z,{size:"small",onClick:()=>{Mn(v.id,{forceRefreshIndex:!0,forceLoadHistory:!0,subscribeIfRunning:!0,forceSubscribe:!0}),S()},children:e("settings.schedulesTab.actions.open")})]},v.id))})}),t.jsx(Qe,{title:e("settings.schedulesTab.scheduleRunsTitle"),open:g.open,onCancel:()=>d(v=>({...v,open:!1,scheduleId:null})),footer:null,width:960,children:g.loading?t.jsx(Fe,{type:"secondary",children:e("settings.schedulesTab.loading")}):g.runs.length===0?t.jsx(Fe,{type:"secondary",children:e("settings.schedulesTab.noRunsYet")}):t.jsx(at,{rowKey:"run_id",pagination:{pageSize:8},dataSource:g.runs,columns:[{title:e("settings.schedulesTab.runHistory.columns.status"),key:"status",render:(v,T)=>t.jsx(ie,{color:vo(T.status),children:T.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:(v,T)=>T.started_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.completedAt"),key:"completed_at",render:(v,T)=>T.completed_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.session"),key:"session_id",render:(v,T)=>T.session_id||"-"},{title:e("settings.schedulesTab.runHistory.columns.duration"),key:"execution_duration_ms",render:(v,T)=>T.execution_duration_ms!=null?`${T.execution_duration_ms}ms`:"-"},{title:e("settings.schedulesTab.runHistory.columns.outcome"),key:"outcome_reason",render:(v,T)=>T.outcome_reason||(T.was_catch_up?"catch-up":"-")}]})}),t.jsx(Qe,{title:e("settings.schedulesTab.editTitle"),open:j.open,onCancel:()=>x({open:!1,schedule:null,saving:!1}),okText:e("settings.schedulesTab.actions.save"),confirmLoading:j.saving,onOk:()=>b.submit(),forceRender:!0,children:t.jsx(f,{form:b,layout:"vertical",onFinish:async v=>{const T=j.schedule;if(!T)return;const D=!!v.auto_execute,A=De(v.task_message),ee=De(v.model);if(D&&!A){s.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:O,errorKey:Q}=$a(v);if(!O){s.error(e(Q||"settings.schedulesTab.validation.triggerRequired"));return}x(W=>({...W,saving:!0}));try{await it.patchSchedule(T.id,{name:String(v.name||"").trim()||void 0,enabled:!!v.enabled,trigger:O,timezone:De(v.timezone),start_at:De(v.start_at),end_at:De(v.end_at),misfire_policy:Ba(v),overlap_policy:v.overlap_policy,run_config:{system_prompt:De(v.system_prompt),task_message:A,model:ee,workspace_path:De(v.workspace_path),enhance_prompt:De(v.enhance_prompt),auto_execute:D}}),s.success(e("settings.schedulesTab.updated")),x({open:!1,schedule:null,saving:!1}),await p()}catch(W){console.error("[Schedules] Failed to patch schedule:",W),s.error(e("settings.schedulesTab.updateFailed")),x(re=>({...re,saving:!1}))}},children:ae(C,I)})})]})}const{Text:Yt}=de,Zt=na.getInstance();function Do(){const{t:e}=ne(),{modal:s,message:a}=gt.useApp(),n=We(y=>y.chats),r=We(y=>y.currentSessionId),o=We(y=>y.refreshChats),l=We(y=>y.loadChats),u=We(y=>y.loadChatHistory),[m,g]=i.useState(!0),[d,j]=i.useState(!1),x=i.useMemo(()=>r?n.find(y=>y.id===r)??null:null,[n,r]),S=async y=>{if(!d){j(!0);try{await y()}finally{j(!1)}}};return t.jsxs(X,{vertical:!0,gap:16,children:[t.jsx(N,{size:"small",title:e("settings.sessionsTab.currentSessionTitle"),children:x?t.jsxs(X,{vertical:!0,gap:4,children:[t.jsx(Yt,{strong:!0,ellipsis:!0,children:x.title}),t.jsxs(Yt,{type:"secondary",ellipsis:!0,children:[e("settings.sessionsTab.id"),": ",x.id," ","•"," ",e("settings.sessionsTab.kind"),": ",x.kind]}),t.jsx(X,{gap:8,wrap:"wrap",style:{marginTop:8},children:t.jsx(z,{danger:!0,loading:d,onClick:()=>{s.confirm({title:e("settings.sessionsTab.clearMessagesTitle"),content:e("settings.sessionsTab.clearMessagesContent"),okText:e("settings.sessionsTab.clear"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await S(async()=>{await Zt.clearSession(x.id),await u(x.id),await o(),a.success(e("settings.sessionsTab.sessionCleared"))})}})},children:e("settings.sessionsTab.clearMessages")})})]}):t.jsx(Yt,{type:"secondary",children:e("settings.sessionsTab.noActiveSession")})}),t.jsxs(N,{size:"small",title:e("settings.sessionsTab.bulkCleanupTitle"),children:[t.jsxs(X,{align:"center",gap:8,style:{marginBottom:12},children:[t.jsx(Yt,{children:e("settings.sessionsTab.keepPinned")}),t.jsx(ye,{checked:m,onChange:g})]}),t.jsxs(X,{gap:8,wrap:"wrap",children:[t.jsx(z,{danger:!0,loading:d,onClick:()=>{s.confirm({title:e("settings.sessionsTab.deleteAllTitle"),content:e(m?"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 Zt.cleanupSessions("all",m),await l(),a.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteAll")}),t.jsx(z,{danger:!0,loading:d,onClick:()=>{s.confirm({title:e("settings.sessionsTab.deleteEmptyTitle"),content:e(m?"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 Zt.cleanupSessions("empty",m),await l(),a.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteEmpty")}),t.jsx(z,{danger:!0,loading:d,onClick:()=>{s.confirm({title:e("settings.sessionsTab.deleteChildrenTitle"),content:e(m?"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 Zt.cleanupSessions("children",m),await l(),a.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteChildren")})]})]}),t.jsxs(N,{size:"small",title:e("settings.sessionsTab.devResetTitle"),children:[t.jsx(Yt,{type:"secondary",children:e("settings.sessionsTab.devResetDescription")}),t.jsx(X,{style:{marginTop:12},children:t.jsx(z,{danger:!0,type:"primary",loading:d,onClick:()=>{s.confirm({title:e("settings.sessionsTab.devResetConfirmTitle"),content:e("settings.sessionsTab.devResetConfirmContent"),okText:e("settings.sessionsTab.reset"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await S(async()=>{await Zt.devResetSessions(),await l(),a.success(e("settings.sessionsTab.devResetDone"))})}})},children:e("settings.sessionsTab.devResetAction")})})]})]})}const gn="notifications/preferences";function mn(e){return{enabled:e.enabled,onClarification:e.on_clarification,onToolApproval:e.on_tool_approval,onContextPressure:e.on_context_pressure,onSubAgentComplete:e.on_subagent_complete,onBackgroundTaskComplete:e.on_background_task_complete}}function Io(e){return{enabled:e.enabled,on_clarification:e.onClarification,on_tool_approval:e.onToolApproval,on_context_pressure:e.onContextPressure,on_subagent_complete:e.onSubAgentComplete,on_background_task_complete:e.onBackgroundTaskComplete}}async function Fo(){const e=await Ye.get(gn);return mn(e)}async function Ao(e){const s=await Ye.put(gn,Io(e));return mn(s)}const{Text:tt}=de,{useToken:Ro}=_e,zo={enabled:!0,onClarification:!0,onToolApproval:!0,onContextPressure:!0,onSubAgentComplete:!0,onBackgroundTaskComplete:!0},Lo=()=>{const{t:e}=ne(),{token:s}=Ro(),{message:a}=gt.useApp(),[n,r]=i.useState(zo),[o,l]=i.useState(!0),u=En();i.useEffect(()=>{let d=!1;return(async()=>{try{const j=await Fo();d||r(j)}catch{d||a.error(e("settings.notificationsTab.loadError","Failed to load notification preferences"))}finally{d||l(!1)}})(),()=>{d=!0}},[a,e]);const m=(d,j)=>{const x=n,S={...n,[d]:j};r(S),Ao(S).then(y=>{r(y)}).catch(()=>{r(x),a.error(e("settings.notificationsTab.saveError","Failed to save notification preferences"))})},g=!u||o;return t.jsx(N,{size:"small",className:"lotus-settings-card",children:t.jsxs(X,{vertical:!0,gap:s.marginMD,children:[!u&&t.jsx(He,{type:"info",showIcon:!0,message:e("settings.notificationsTab.desktopOnly","Desktop notifications are only available in the Bodhi desktop app.")}),t.jsxs(X,{align:"center",gap:s.marginSM,children:[t.jsx(Xn,{}),t.jsx(tt,{strong:!0,children:e("settings.notificationsTab.title","Desktop Notifications")})]}),t.jsx(tt,{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(Ne,{style:{margin:`${s.marginXS}px 0`}}),t.jsxs(X,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(tt,{children:e("settings.notificationsTab.enabled","Enable desktop notifications")}),t.jsx(ye,{"data-testid":"notification-enabled-toggle",checked:n.enabled,onChange:d=>m("enabled",d),disabled:g})]}),t.jsx(Ne,{style:{margin:`${s.marginXS}px 0`}}),t.jsx(tt,{strong:!0,style:{fontSize:s.fontSizeSM,opacity:n.enabled?1:.5},children:e("settings.notificationsTab.events","Notify when:")}),t.jsxs(X,{vertical:!0,gap:s.marginSM,style:{opacity:n.enabled?1:.5,pointerEvents:n.enabled?"auto":"none"},children:[t.jsxs(X,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(tt,{children:e("settings.notificationsTab.onClarification","Agent needs clarification")}),t.jsx(ye,{"data-testid":"notification-clarification-toggle",checked:n.onClarification,onChange:d=>m("onClarification",d),disabled:g})]}),t.jsxs(X,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(tt,{children:e("settings.notificationsTab.onToolApproval","Tool execution needs approval")}),t.jsx(ye,{"data-testid":"notification-tool-approval-toggle",checked:n.onToolApproval,onChange:d=>m("onToolApproval",d),disabled:g})]}),t.jsxs(X,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(tt,{children:e("settings.notificationsTab.onContextPressure","Context window is critically full")}),t.jsx(ye,{"data-testid":"notification-context-pressure-toggle",checked:n.onContextPressure,onChange:d=>m("onContextPressure",d),disabled:g})]}),t.jsxs(X,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(tt,{children:e("settings.notificationsTab.onSubAgentComplete","Background task completes")}),t.jsx(ye,{"data-testid":"notification-subagent-complete-toggle",checked:n.onSubAgentComplete,onChange:d=>m("onSubAgentComplete",d),disabled:g})]}),t.jsxs(X,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(tt,{children:e("settings.notificationsTab.onBackgroundTaskComplete","Background command finishes")}),t.jsx(ye,{"data-testid":"notification-background-task-complete-toggle",checked:n.onBackgroundTaskComplete,onChange:d=>m("onBackgroundTaskComplete",d),disabled:g})]})]}),t.jsx(Ne,{style:{margin:`${s.marginXS}px 0`}}),t.jsxs(X,{align:"center",gap:s.marginSM,children:[t.jsx(Yn,{style:{color:s.colorPrimary}}),t.jsx(tt,{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:xs,Paragraph:Oo}=de,pn=({open:e,onCancel:s,onComplete:a,onCopyCode:n,completingAuth:r,copiedUserCode:o,deviceCodeInfo:l,timeRemaining:u,token:m})=>{const{t:g}=ne();return t.jsx(Qe,{title:g("settings.providerTab.copilotAuthModalTitle"),open:e,onCancel:s,footer:[t.jsx(z,{onClick:s,children:g("settings.providerTab.cancel")},"cancel"),t.jsx(z,{type:"primary",onClick:a,loading:r,children:g("settings.providerTab.completedAuthorization")},"complete")],children:l&&t.jsxs(L,{direction:"vertical",size:"large",style:{width:"100%"},children:[t.jsx(He,{message:g("settings.providerTab.browserOpened"),description:t.jsxs("ol",{children:[t.jsx("li",{children:g("settings.providerTab.authStep1")}),t.jsx("li",{children:g("settings.providerTab.authStep2")}),t.jsx("li",{children:g("settings.providerTab.authStep3")})]}),type:"info"}),t.jsx(N,{size:"small",className:"lotus-settings-card",children:t.jsxs(L,{direction:"vertical",style:{width:"100%"},children:[t.jsx(xs,{type:"secondary",children:g("settings.providerTab.visitUrl")}),t.jsx(L,{children:t.jsx(xs,{copyable:{text:l.verification_uri},children:l.verification_uri})})]})}),t.jsx(N,{style:{textAlign:"center",background:m.colorFillTertiary,borderColor:m.colorBorderSecondary},children:t.jsxs(L,{direction:"vertical",style:{width:"100%"},children:[t.jsx(xs,{type:"secondary",children:g("settings.providerTab.enterCode")}),t.jsxs(L,{children:[t.jsx(xs,{style:{color:m.colorText,fontSize:"32px",fontFamily:"monospace",fontWeight:"bold",letterSpacing:"4px"},children:l.user_code}),t.jsx(z,{icon:o?t.jsx(ea,{}):t.jsx(en,{}),onClick:n,type:o?"default":"primary",children:g(o?"settings.providerTab.copied":"settings.providerTab.copyCode")})]}),t.jsx("div",{style:{marginTop:8},children:t.jsxs(ie,{color:u<60?"error":u<180?"warning":"success",children:[t.jsx(Zn,{style:{marginRight:4}}),"Expires in ",Math.floor(u/60),":",(u%60).toString().padStart(2,"0")]})})]})}),t.jsx(Oo,{type:"secondary",children:g("settings.providerTab.afterContinueHint")})]})})},No=new Set(["id","type","provider_type","label","enabled","api_key_encrypted"]),ks=e=>typeof e=="string"&&e.trim().length>0&&[...e.trim()].every(s=>s==="*"||s==="."),qa=e=>e?Object.fromEntries(Object.entries(e).filter(([s,a])=>!No.has(s)&&!(s==="api_key"&&ks(a)))):{},{Password:Ha}=H,{Text:ht,Paragraph:Gs}=de,Vo=["low","medium","high","xhigh","max"],Qt=(e,s)=>t.jsx(se,{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:Vo.map(a=>t.jsx(se.Option,{value:a,children:e(`chat.input.reasoning.${a}`)},a))}),Ua=e=>t.jsx(f.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(se,{mode:"tags",tokenSeparators:[","," ",`
3
+ `," "],placeholder:e("settings.providerTab.responsesOnlyModelsPlaceholder"),allowClear:!0})}),$o=e=>Array.isArray(e)?e.map(s=>typeof s=="string"?s.trim():"").filter(s=>!!s):[],Bo=({type:e,hasStoredApiKey:s})=>{const{t:a}=ne();if(!e)return null;const n=o=>s?[]:[{required:!0,message:o}],r=o=>s?a("settings.providerTab.apiKeyKeepPlaceholder","Configured — leave empty to keep"):o;switch(e){case"openai":return t.jsxs(t.Fragment,{children:[t.jsx(f.Item,{name:"api_key",label:a("settings.providerTab.openaiApiKey"),rules:n(a("settings.providerTab.openaiApiKeyRequired")),children:t.jsx(H.Password,{placeholder:r(a("settings.providerTab.openaiApiKeyPlaceholder","sk-...")),prefix:t.jsx(xt,{})})}),t.jsx(f.Item,{name:"base_url",label:a("settings.providerTab.baseUrlOptional"),extra:a("settings.providerTab.openaiBaseUrlHelp"),children:t.jsx(H,{placeholder:a("settings.providerTab.openaiBaseUrlPlaceholder","https://api.openai.com/v1")})}),t.jsx(f.Item,{name:"reasoning_effort",label:a("settings.providerTab.reasoningEffortOptional"),extra:a("settings.providerTab.reasoningEffortHelp"),children:Qt(a)}),Ua(a)]});case"anthropic":return t.jsxs(t.Fragment,{children:[t.jsx(f.Item,{name:"api_key",label:a("settings.providerTab.anthropicApiKey"),rules:n(a("settings.providerTab.anthropicApiKeyRequired")),children:t.jsx(Ha,{placeholder:r(a("settings.providerTab.anthropicApiKeyPlaceholder","sk-ant-...")),prefix:t.jsx(xt,{})})}),t.jsx(f.Item,{name:"base_url",label:a("settings.providerTab.baseUrlOptional"),extra:a("settings.providerTab.anthropicBaseUrlHelp"),children:t.jsx(H,{placeholder:a("settings.providerTab.anthropicBaseUrlPlaceholder","https://api.anthropic.com/v1")})}),t.jsx(f.Item,{name:"max_tokens",label:a("settings.providerTab.maxTokensOptional"),extra:a("settings.providerTab.maxTokensHelp"),children:t.jsx(H,{type:"number",placeholder:a("settings.providerTab.maxTokensPlaceholder","4096"),min:1,max:1e5})}),t.jsx(f.Item,{name:"reasoning_effort",label:a("settings.providerTab.reasoningEffortOptional"),extra:a("settings.providerTab.reasoningEffortHelp"),children:Qt(a)})]});case"gemini":return t.jsxs(t.Fragment,{children:[t.jsx(f.Item,{name:"api_key",label:a("settings.providerTab.geminiApiKey"),rules:n(a("settings.providerTab.geminiApiKeyRequired")),children:t.jsx(Ha,{placeholder:r(a("settings.providerTab.geminiApiKeyPlaceholder","AIza...")),prefix:t.jsx(xt,{})})}),t.jsx(f.Item,{name:"base_url",label:a("settings.providerTab.baseUrlOptional"),extra:a("settings.providerTab.geminiBaseUrlHelp"),children:t.jsx(H,{placeholder:a("settings.providerTab.geminiBaseUrlPlaceholder","https://generativelanguage.googleapis.com/v1beta")})}),t.jsx(f.Item,{name:"reasoning_effort",label:a("settings.providerTab.reasoningEffortOptional"),extra:a("settings.providerTab.reasoningEffortHelp"),children:Qt(a)})]});case"copilot":return t.jsxs(t.Fragment,{children:[t.jsx(f.Item,{name:"headless_auth",label:a("settings.providerTab.headlessAuth"),valuePropName:"checked",extra:a("settings.providerTab.headlessAuthHelp"),children:t.jsx(ye,{})}),t.jsx(f.Item,{name:"reasoning_effort",label:a("settings.providerTab.reasoningEffortOptional"),extra:a("settings.providerTab.reasoningEffortHelp"),children:Qt(a)}),Ua(a)]});case"bodhi":return t.jsxs(t.Fragment,{children:[t.jsx(f.Item,{name:"api_key",label:a("settings.providerTab.bodhiApiKey"),rules:n(a("settings.providerTab.apiKeyRequired")),children:t.jsx(H.Password,{placeholder:r(a("settings.providerTab.bodhiApiKeyPlaceholder","bhi_sk_...")),prefix:t.jsx(xt,{})})}),t.jsx(f.Item,{name:"base_url",label:a("settings.providerTab.bodhiBaseUrl"),extra:a("settings.providerTab.bodhiBaseUrlExtra"),children:t.jsx(H,{placeholder:a("settings.providerTab.bodhiBaseUrlPlaceholder","http://localhost:8080")})}),t.jsx(f.Item,{name:"target_provider",label:a("settings.providerTab.targetProvider"),extra:a("settings.providerTab.targetProviderExtra"),children:t.jsxs(se,{placeholder:a("settings.providerTab.targetProviderPlaceholder","openai"),allowClear:!0,children:[t.jsx(se.Option,{value:"openai",children:"OpenAI"}),t.jsx(se.Option,{value:"anthropic",children:"Anthropic"}),t.jsx(se.Option,{value:"gemini",children:"Gemini"})]})}),t.jsx(f.Item,{name:"reasoning_effort",label:a("settings.providerTab.reasoningEffortOptional"),extra:a("settings.providerTab.reasoningEffortHelp"),children:Qt(a)})]});default:return null}},qo=({instances:e,defaultInstanceId:s,onInstancesChanged:a})=>{const{t:n}=ne(),{message:r}=gt.useApp(),{token:o}=_e.useToken(),[l]=f.useForm(),[u,m]=i.useState(!1),[g,d]=i.useState(null),[j,x]=i.useState(!1),[S,y]=i.useState(null),[b,R]=i.useState(void 0),[P,C]=i.useState(null),[I,p]=i.useState(!1),[k,V]=i.useState(!1),[F,U]=i.useState(0),[ae,q]=i.useState(!1),[v,T]=i.useState(!1),[D,A]=i.useState("unknown"),[ee,O]=i.useState(!1),Q=i.useCallback($=>({type:$.type,label:$.label,enabled:$.enabled,...qa($.config)}),[]),W=i.useCallback(()=>{d(null),R(void 0),m(!0)},[]),re=async()=>{try{T(!0);const $=await ce.startCopilotAuth();C($),p(!0),U($.expires_in)}catch($){r.error(n("settings.providerTab.startCopilotAuthFailed","Failed to start Copilot authentication")),console.error("Failed to start Copilot authentication:",$)}finally{T(!1)}},ue=async()=>{if(P)try{V(!0),await ce.completeCopilotAuth({device_code:P.device_code,interval:P.interval||5,expires_in:P.expires_in}),r.success(n("settings.providerTab.copilotAuthSuccess","Copilot authentication successful!")),p(!1),C(null),await c()}catch($){r.error(n("settings.providerTab.completeAuthFailed","Authentication completion failed")),console.error("Authentication completion failed:",$)}finally{V(!1)}},be=async()=>{if(P)try{await ra(P.user_code),q(!0),r.success(n("settings.providerTab.userCodeCopied","User code copied!")),setTimeout(()=>q(!1),2e3)}catch{r.error(n("settings.providerTab.copyCodeFailed","Failed to copy code"))}},c=i.useCallback(async()=>{try{O(!0);const $=await ce.getCopilotAuthStatus();A($.authenticated?"authenticated":"not_authenticated")}catch($){console.error("Failed to check Copilot auth status:",$),A("unknown")}finally{O(!1)}},[]);i.useEffect(()=>{u&&b==="copilot"&&c()},[c,u,b]);const E=i.useCallback($=>{if(!$){l.resetFields();return}if(g){l.setFieldsValue(Q(g)),R(g.type);return}l.setFieldsValue({enabled:!0})},[Q,g,l]),M=($="small")=>t.jsx(N,{size:"small",title:n("settings.providerTab.copilotAuth","GitHub Copilot Authentication"),style:{marginTop:8},children:t.jsxs(L,{direction:"vertical",style:{width:"100%"},children:[t.jsxs(L,{children:[t.jsx(ht,{strong:!0,children:n("settings.providerTab.authStatus","Status:")}),D==="authenticated"?t.jsx(ie,{color:"success",children:n("settings.providerTab.authenticated","Authenticated")}):D==="not_authenticated"?t.jsx(ie,{color:"warning",children:n("settings.providerTab.notAuthenticated","Not Authenticated")}):t.jsx(ie,{children:n("settings.providerTab.unknown","Unknown")}),t.jsx(z,{type:"text",size:"small",onClick:()=>void c(),loading:ee,children:n("settings.providerTab.refreshStatus","Refresh")})]}),t.jsx(Gs,{type:"secondary",style:{marginBottom:8},children:n("settings.providerTab.copilotAuthHelp","Copilot requires OAuth authentication. Click the button below to start the Device Code Flow.")}),t.jsx(z,{type:"primary",icon:t.jsx(tn,{}),onClick:()=>void re(),loading:v,size:$,children:n("settings.providerTab.authenticateCopilot","Authenticate Copilot")})]})}),G=i.useCallback($=>{d($),R($.type),m(!0)},[]),Z=i.useCallback(async()=>{try{const $=await l.validateFields();x(!0);const{type:Te,label:Xe,enabled:Ie,request_overrides_json:Ve,...Le}=$,Ae=qa(Le);if("responses_only_models"in Ae&&(Ae.responses_only_models=$o(Ae.responses_only_models)),typeof Ve=="string"&&Ve.trim()&&(Ae.request_overrides=JSON.parse(Ve)),g&&(typeof Ae.api_key!="string"||!Ae.api_key.trim())&&delete Ae.api_key,g){const h={label:Xe,enabled:Ie,config:Ae};await ce.updateProviderInstance(g.id,h),r.success(n("settings.providerTab.instanceUpdated","Provider instance updated"))}else{const h={type:Te,label:Xe||ft[Te]||Te,enabled:Ie??!0,config:Ae};await ce.createProviderInstance(h),r.success(n("settings.providerTab.instanceCreated","Provider instance created"))}m(!1),await a(),await st.getState().loadProviderInstances()}catch($){(vs($)||$ instanceof Error&&!an($))&&r.error($.message)}finally{x(!1)}},[g,l,r,a,n]),ge=i.useCallback(async $=>{try{y($),await ce.deleteProviderInstance($),r.success(n("settings.providerTab.instanceDeleted","Provider instance deleted")),await a(),await st.getState().loadProviderInstances()}catch(Te){r.error(vs(Te)?Te.message:n("settings.providerTab.instanceDeleteFailed","Failed to delete instance"))}finally{y(null)}},[a,r,n]),xe=i.useCallback(async $=>{try{await ce.setDefaultProviderInstance($),r.success(n("settings.providerTab.defaultInstanceSet","Default provider updated")),await a(),await st.getState().loadProviderInstances()}catch(Te){r.error(vs(Te)?Te.message:n("settings.providerTab.defaultInstanceFailed","Failed to set default"))}},[a,r,n]),je=i.useCallback(async()=>{await a()},[a]);return i.useEffect(()=>{je()},[]),t.jsxs("div",{style:{marginBottom:16},children:[t.jsxs("div",{style:{marginBottom:12,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[t.jsx(ht,{strong:!0,children:n("settings.providerTab.providerInstances","Provider Instances")}),t.jsx(z,{type:"dashed",icon:t.jsx(ut,{}),onClick:W,"data-testid":"add-provider-instance",children:n("settings.providerTab.addInstance","Add Provider")})]}),e.length===0&&t.jsx(Gs,{type:"secondary",children:n("settings.providerTab.noInstances",'No provider instances configured. Click "Add Provider" to create one.')}),t.jsx(ws,{ghost:!0,items:e.map($=>{const Te=$.id===s,Xe=ft[$.type]||$.type;return{key:$.id,label:t.jsxs(L,{size:"small",children:[t.jsx("span",{style:{fontWeight:500},children:$.label||Xe}),t.jsx(ie,{color:"processing",style:{fontSize:11},children:Xe}),Te&&t.jsxs(ie,{color:"gold",style:{fontSize:11},children:[t.jsx(er,{})," ",n("settings.providerTab.default","Default")]}),!$.enabled&&t.jsx(ie,{color:"default",style:{fontSize:11},children:n("settings.providerTab.disabled","Disabled")})]}),extra:t.jsxs(L,{size:4,onClick:Ie=>Ie.stopPropagation(),children:[!Te&&t.jsx(ke,{title:n("settings.providerTab.setDefault","Set as default"),children:t.jsx(z,{type:"text",size:"small",icon:t.jsx(Qn,{}),onClick:()=>void xe($.id)})}),t.jsx(z,{type:"text",size:"small",icon:t.jsx(ls,{}),onClick:()=>G($)}),t.jsx(zt,{title:n("settings.providerTab.confirmDeleteInstance","Delete this provider instance?"),onConfirm:()=>void ge($.id),okText:n("settings.providerTab.delete","Delete"),cancelText:n("settings.providerTab.cancel","Cancel"),children:t.jsx(z,{type:"text",size:"small",danger:!0,icon:t.jsx(Et,{}),loading:S===$.id})})]}),children:t.jsxs("div",{children:[t.jsxs(Gs,{type:"secondary",style:{marginBottom:8},children:["ID: ",t.jsx(ht,{code:!0,children:$.id})," · Type: ",t.jsx(ht,{code:!0,children:$.type})]}),$.config&&Object.keys($.config).length>0&&t.jsx(N,{size:"small",style:{marginBottom:8},children:Object.entries($.config).map(([Ie,Ve])=>Ie==="api_key"?t.jsxs("div",{style:{marginBottom:4},children:[t.jsxs(ht,{type:"secondary",children:[Ie,": "]}),t.jsx(ht,{children:"••••••••"})]},Ie):t.jsxs("div",{style:{marginBottom:4},children:[t.jsxs(ht,{type:"secondary",children:[Ie,": "]}),t.jsx(ht,{children:typeof Ve=="object"?JSON.stringify(Ve):String(Ve)})]},Ie))}),$.type==="copilot"&&M("small")]})}})}),t.jsx(Qe,{open:u,title:g?n("settings.providerTab.editInstance","Edit Provider Instance"):n("settings.providerTab.createInstance","Create Provider Instance"),onCancel:()=>m(!1),onOk:()=>void Z(),afterOpenChange:E,confirmLoading:j,width:560,forceRender:!0,destroyOnClose:!0,children:t.jsxs(f,{form:l,layout:"vertical",preserve:!1,children:[t.jsx(f.Item,{name:"type",label:n("settings.providerTab.providerType","Provider Type"),rules:[{required:!0,message:n("settings.providerTab.typeRequired","Please select a provider type")}],children:t.jsx(se,{disabled:!!g,placeholder:n("settings.providerTab.selectType","Select provider type"),onChange:$=>R($),children:Object.entries(ft).map(([$,Te])=>t.jsx(se.Option,{value:$,children:Te},$))})}),t.jsx(f.Item,{name:"label",label:n("settings.providerTab.instanceLabel","Label"),extra:n("settings.providerTab.labelHelp","A display name for this provider instance"),children:t.jsx(H,{placeholder:n("settings.providerTab.labelPlaceholder","My OpenAI Instance")})}),t.jsx(f.Item,{name:"enabled",label:n("settings.providerTab.enabled","Enabled"),valuePropName:"checked",initialValue:!0,children:t.jsx(ye,{})}),t.jsx(Ne,{children:n("settings.providerTab.instanceConfig","Configuration")}),t.jsx(f.Item,{noStyle:!0,shouldUpdate:!0,children:()=>{var $;return t.jsx(Bo,{form:l,type:b,hasStoredApiKey:!!(g&&ks(($=g.config)==null?void 0:$.api_key))})}}),b==="copilot"&&M("middle")]})}),t.jsx(pn,{open:I,onCancel:()=>p(!1),onComplete:()=>void ue(),onCopyCode:()=>void be(),completingAuth:k,copiedUserCode:ae,deviceCodeInfo:P,timeRemaining:F,token:o})]})},{Password:Ka}=H,{Text:Ze,Paragraph:Js}=de,es=["openai","anthropic","gemini","copilot","bodhi"],It=()=>null,Xs=e=>{var a,n;if(!e||typeof e!="object")return!1;const s=e;return!!((a=s.provider)!=null&&a.trim()&&((n=s.model)!=null&&n.trim()))},Ho=(e,s,a)=>{const n=e;n[s]={...n[s]??{},model:a}},Wa=e=>{var a,n;const s=(n=(a=e.memory)==null?void 0:a.background_model)==null?void 0:n.trim();return s||void 0},Ga=(e,s)=>{var a,n,r;return s||((a=e==null?void 0:e.chat)==null?void 0:a.provider)||((n=e==null?void 0:e.fast)==null?void 0:n.provider)||((r=e==null?void 0:e.memory_background)==null?void 0:r.provider)||void 0},Ja=e=>t.jsxs(L,{direction:"vertical",size:4,children:[t.jsxs(Ze,{type:"secondary",children:[e("settings.providerTab.responsesOnlyHelp1")," ",t.jsx(Ze,{code:!0,children:"/responses"}),"."]}),t.jsx(Ze,{type:"secondary",children:e("settings.providerTab.responsesOnlyHelp2")})]}),Uo=["low","medium","high","xhigh","max"],Ft=(e,s)=>t.jsx(se,{placeholder:e("settings.providerTab.reasoningEffortDefault"),allowClear:!0,value:s==null?void 0:s.value,onChange:s!=null&&s.onChange?a=>{var n;return(n=s.onChange)==null?void 0:n.call(s,a??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:Uo.map(a=>t.jsx(se.Option,{value:a,children:e(`chat.input.reasoning.${a}`)},a))}),Ko=()=>{const{t:e}=ne(),{token:s}=_e.useToken(),{message:a}=gt.useApp(),[n]=f.useForm(),[r,o]=i.useState(!1),[l,u]=i.useState(!1),[m,g]=i.useState("copilot"),[d,j]=i.useState(!1),[x,S]=i.useState(new Set),[y,b]=i.useState(null),[R,P]=i.useState(!1),[C,I]=i.useState(!1),[p,k]=i.useState(null),[V,F]=i.useState(!1),[U,ae]=i.useState(!1),[q,v]=i.useState(0),[T,D]=i.useState(!1),[A,ee]=i.useState([]),[O,Q]=i.useState(!1),[W,re]=i.useState([]),[ue,be]=i.useState(null),[c,E]=i.useState(!1),[M,G]=i.useState([]),[Z,ge]=i.useState("idle"),[xe,je]=i.useState(null),$=i.useCallback((_,w)=>{const Y=_.instances??[],B=Y.reduce((he,te)=>{const we={...te.config};return we.request_overrides&&typeof we.request_overrides=="object"&&(we.request_overrides_json=JSON.stringify(we.request_overrides,null,2)),he[te.id]=we,he},{});let K=_.defaults?{..._.defaults}:void 0;const fe=_.default_provider_instance_id??null,pe=fe?Y.find(he=>he.id===fe):void 0,Se=typeof(pe==null?void 0:pe.config.model)=="string"?pe.config.model.trim():void 0;!Xs(K==null?void 0:K.chat)&&fe&&Se&&(K={...K||{},chat:{provider:fe,model:Se}});const Re=w?Wa(w):void 0,Pe=Ga(K,fe);return Re&&!(K!=null&&K.memory_background)&&Pe&&(K={...K||{},memory_background:{provider:Pe,model:Re}}),{defaults:K,features:_.features,providers:B}},[]),Te=i.useCallback((_,w)=>{re(_.instances??[]),be(_.default_provider_instance_id??null),E(!0),n.setFieldsValue($(_,w)),j(!0)},[$,n]),Xe=i.useCallback(_=>{if(!(_!=null&&_.trim()))return;const w=W.find(Y=>Y.id===_);return w?w.label||ft[w.type]:ft[_]||_},[W]),Ie=i.useCallback((_,w)=>{const Y=new Set;_!=null&&_.trim()&&Y.add(_);for(const B of es){const K=w==null?void 0:w[B];K&&Object.keys(K).length>0&&Y.add(B)}return Array.from(Y)},[]);i.useEffect(()=>{if(Z!=="success")return;const _=setTimeout(()=>{ge("idle"),je(null)},2e3);return()=>clearTimeout(_)},[Z]),i.useEffect(()=>{if(!V||!p){v(0);return}v(p.expires_in);const _=setInterval(()=>{v(w=>w<=1?(clearInterval(_),0):w-1)},1e3);return()=>clearInterval(_)},[V,p]);const Ve=i.useCallback(async()=>{var _;try{o(!0);const[w,Y]=await Promise.all([ce.getProviderConfig(),ot.getInstance().getBambooConfig().catch(()=>({}))]);let B=w.defaults?{...w.defaults}:void 0;if(!((_=B==null?void 0:B.chat)!=null&&_.model)&&w.provider&&w.providers){const he=w.provider,te=w.providers[he],we=te==null?void 0:te.model;we&&(B={...B||{},chat:{provider:he,model:we}})}const K=Wa(Y),fe=Ga(B,w.provider||null);K&&!(B!=null&&B.memory_background)&&fe&&(B={...B||{},memory_background:{provider:fe,model:K}});const pe=Xs(B==null?void 0:B.chat)?B:void 0,Se={provider:w.provider,defaults:pe,providers:w.providers||{},features:w.features};dt("[Provider]","Loaded provider config:",Se);const Re={...Se.providers||{}},Pe=new Set;es.forEach(he=>{const te=Re[he];te&&(ks(te.api_key)&&(Pe.add(he),delete te.api_key),te.request_overrides&&typeof te.request_overrides=="object"&&(te.request_overrides_json=JSON.stringify(te.request_overrides,null,2)))}),S(Pe),g(Se.provider),E(!1),G(Ie(Se.provider,Re)),n.setFieldsValue({...Se,providers:Re,defaults:Se.defaults}),j(!0)}catch(w){a.error(e("settings.providerTab.loadConfigFailed")),console.error("Failed to load provider config:",w)}finally{o(!1)}},[n,Ie,a,e]),Le=i.useCallback(async()=>{try{const _=await ce.getEnvVars();ee(_.entries||[])}catch(_){console.warn("Failed to load env vars for provider overrides:",_)}},[]),Ae=i.useCallback(async()=>{try{const[_,w]=await Promise.all([ce.getProviderInstances(),ot.getInstance().getBambooConfig().catch(()=>({}))]);if(!Array.isArray(_.instances))throw new Error("Provider instances API returned an invalid payload");Te(_,w)}catch{}},[Te]),h=i.useCallback(async()=>{try{P(!0);const _=await ce.getCopilotAuthStatus();b(_)}catch(_){console.error("Failed to check Copilot auth status:",_),b({authenticated:!1,message:e("settings.providerTab.checkStatusFailed")})}finally{P(!1)}},[e]);i.useEffect(()=>{Le(),st.getState().loadCatalog(),h(),(async()=>{try{const[_,w]=await Promise.all([ce.getProviderInstances(),ot.getInstance().getBambooConfig().catch(()=>({}))]);if(!Array.isArray(_.instances))throw new Error("Provider instances API returned an invalid payload");Te(_,w)}catch{await Ve()}})()},[Ve,Le,h,Te]);const le=async()=>{try{I(!0);const _=await ce.startCopilotAuth();k(_),F(!0)}catch(_){a.error(e("settings.providerTab.startCopilotAuthFailed")),console.error("Failed to start Copilot authentication:",_)}finally{I(!1)}},ve=async()=>{if(p)try{ae(!0),await ce.completeCopilotAuth({device_code:p.device_code,interval:p.interval||5,expires_in:p.expires_in}),a.success(e("settings.providerTab.copilotAuthSuccess")),F(!1),k(null),await h()}catch(_){a.error(e("settings.providerTab.completeAuthFailed")),console.error("Authentication completion failed:",_)}finally{ae(!1)}},$e=async()=>{if(p)try{await ra(p.user_code),D(!0),a.success(e("settings.providerTab.userCodeCopied")),setTimeout(()=>D(!1),2e3)}catch{a.error(`${e("settings.providerTab.copyCodeFailedPrefix")} ${p.user_code}`)}},Ce=async()=>{try{I(!0),await ce.logoutCopilot(),a.success(e("settings.providerTab.logoutSuccess")),await h()}catch(_){a.error(e("settings.providerTab.logoutFailed")),console.error("Failed to logout:",_)}finally{I(!1)}},Be=i.useCallback(async()=>{Q(!0);try{const _=await ce.fetchCatalogModels();await st.getState().loadCatalog();const w=_.fetched.filter(B=>B.models&&B.models.length>0).length;_.fetched.filter(B=>B.error).length>0?a.warning(e("settings.providerTab.fetchModelsPartialSuccess",{success:w,total:_.fetched.length})):a.success(e("settings.providerTab.fetchModelsSuccess",{count:w}))}catch{a.error(e("settings.providerTab.fetchModelsFailed"))}finally{Q(!1)}},[a,e]),bt=_=>vs(_)||_ instanceof Error?_.message:e("settings.providerTab.unknownError"),Es=_=>{n.setFields([{name:["provider"],errors:[]},{name:["providers",_,"api_key"],errors:[]},{name:["defaults","chat"],errors:[]}])},Ps=_=>{const w=_.trim();return w?w.includes(".")?w.split(".").filter(Boolean):w==="provider"?["provider"]:w==="provider/providers"?["provider"]:null:null},Ds=(_,w)=>{if(!_.length)return;const Y=_.map(B=>{const K=Ps(B.path);return K?{name:K,errors:[B.message]}:B.message.toLowerCase().includes("api key")?{name:["providers",w,"api_key"],errors:[B.message]}:{name:["provider"],errors:[B.message]}}).filter((B,K,fe)=>fe.findIndex(pe=>JSON.stringify(pe.name)===JSON.stringify(B.name))===K);Y.length&&n.setFields(Y)},Pt=async _=>{var Y;const w=_.provider||m;Es(w);try{const K=await ot.getInstance().validateBambooConfigPatch({provider:_.provider,providers:_.providers||{},defaults:_.defaults,features:{..._.features||{},provider_model_ref:!0}});if(K.valid)return{valid:!0};const fe=((Y=K.errors)==null?void 0:Y.provider)||[];Ds(fe,w);const pe=fe[0];return{valid:!1,message:(pe==null?void 0:pe.message)||e("settings.providerTab.invalidConfig")}}catch(B){return console.warn("Config validation failed, falling back to save:",B),{valid:!0}}},$t=async(_,w)=>{var Y,B;try{o(!0);const K={provider:_.provider,defaults:_.defaults,providers:{..._.providers||{}},features:{..._.features||{},provider_model_ref:!0}},fe=(Y=K.defaults)==null?void 0:Y.chat;if(!Xs(fe)){const he=e("settings.providerTab.selectModelRequired");if(n.setFields([{name:["defaults","chat"],errors:[he]}]),(w==null?void 0:w.showMessage)!==!1&&a.error(he),w!=null&&w.throwOnError)throw new Error(he);return}const pe=K.providers;for(const he of es){const te=pe[he];if(!te)continue;const we=te.request_overrides_json;if(typeof we!="string")continue;const vt=we.trim();if(!vt)delete te.request_overrides;else try{te.request_overrides=JSON.parse(vt)}catch(qt){const Ht=e("settings.providerTab.invalidRequestOverridesJson",{provider:he,error:qt.message});if(n.setFields([{name:["providers",he,"request_overrides_json"],errors:[Ht]}]),(w==null?void 0:w.showMessage)!==!1&&a.error(Ht),w!=null&&w.throwOnError)throw qt;return}delete te.request_overrides_json}for(const he of es){const te=pe[he];if(!te||!("api_key"in te))continue;const we=te.api_key;(typeof we!="string"||!we.trim()||ks(we))&&delete te.api_key}const Se={...K.providers||{}},Re=K.provider,Pe=(B=K.defaults)==null?void 0:B.chat;if(Pe!=null&&Pe.model&&Re&&Ho(Se,Re,Pe.model),c){const he=ot.getInstance(),te={defaults:K.defaults,features:{...K.features||{},provider_model_ref:!0}};dt("[Provider]","Saving instance-mode config:",te),await he.setBambooConfig(te)}else{const te={provider:K.provider||m,defaults:K.defaults,providers:Se,features:K.features},we=await Pt(K);if(!we.valid){const vt=we.message||e("settings.providerTab.invalidConfig");if((w==null?void 0:w.showMessage)!==!1&&a.error(`${e("settings.providerTab.invalidConfigPrefix")}: ${vt}`),w!=null&&w.throwOnError)throw new Error(vt);return}dt("[Provider]","Saving provider config:",te),await ce.saveProviderConfig(te)}(w==null?void 0:w.showMessage)!==!1&&a.success(e("settings.providerTab.saveConfigSuccess"))}catch(K){const fe=bt(K);if((w==null?void 0:w.showMessage)!==!1&&a.error(fe?`${e("settings.providerTab.saveConfigErrorPrefix")}: ${fe}`:e("settings.providerTab.saveConfigFailed")),console.error("Failed to save configuration:",K),w!=null&&w.throwOnError)throw K}finally{o(!1)}},Bt=async _=>{var w,Y,B,K,fe;try{u(!0);const{useProviderStore:pe}=await ta(async()=>{const{useProviderStore:Ut}=await import("./App-BbO6pZGu.js").then(Os=>Os.ak);return{useProviderStore:Ut}},__vite__mapDeps([4,1,2,3,5,6,7,8]),import.meta.url),{useAppStore:Se}=await ta(async()=>{const{useAppStore:Ut}=await import("./App-BbO6pZGu.js").then(Os=>Os.al);return{useAppStore:Ut}},__vite__mapDeps([4,1,2,3,5,6,7,8]),import.meta.url),Re=(w=pe.getState().providerConfig.defaults)==null?void 0:w.chat;c?await pe.getState().loadProviderInstances():await pe.getState().loadProviderConfig();const Pe=(Y=pe.getState().providerConfig.defaults)==null?void 0:Y.chat;pe.getState().setSelectedModelRef(null);const he=Se.getState().currentSessionId,te=he&&Se.getState().chats.find(Ut=>Ut.id===he)||null,we=Re?`${Re.provider}/${Re.model}`:null,vt=Pe?`${Pe.provider}/${Pe.model}`:null,qt=(B=te==null?void 0:te.config)!=null&&B.model_ref?`${te.config.model_ref.provider}/${te.config.model_ref.model}`:null,Ht=((fe=(K=te==null?void 0:te.config)==null?void 0:K.model)==null?void 0:fe.trim())||null;!!(he&&(te!=null&&te.config)&&Pe&&vt!==we&&(!qt||qt===we)&&(!Ht||Ht===(Re==null?void 0:Re.model)))&&he&&(te!=null&&te.config)&&Pe&&Se.getState().updateSession(he,{config:{...te.config,model:Pe.model,model_ref:Pe}}),(_==null?void 0:_.showMessage)!==!1&&a.success(e("settings.providerTab.applyConfigSuccess"))}catch(pe){const Se=bt(pe);if((_==null?void 0:_.showMessage)!==!1&&a.error(Se?`${e("settings.providerTab.applyConfigErrorPrefix")}: ${Se}`:e("settings.providerTab.applyConfigFailed")),console.error("Failed to apply configuration:",pe),_!=null&&_.throwOnError)throw pe}finally{u(!1)}},Is=async _=>{try{const w=n.getFieldsValue(!0);await $t(w,{throwOnError:!0}),await Bt({throwOnError:!0})}catch{}},Fs=async(_,w)=>{if(!(_==="chat"&&!w)&&Z!=="saving"){ge("saving"),je(null);try{const Y=n.getFieldsValue(!0),B=Y.defaults;if(!(B!=null&&B.chat))throw new Error(e("settings.providerTab.selectModelRequired"));Y.defaults={...B,[_]:w},await $t(Y,{showMessage:!1,throwOnError:!0}),await Bt({showMessage:!1,throwOnError:!0}),ge("success"),a.success(e("settings.providerTab.modelUpdated"))}catch(Y){const B=bt(Y);ge("error"),je(B),a.error(B?`${e("settings.providerTab.updateModelErrorPrefix")}: ${B}`:e("settings.providerTab.updateModelFailed"))}}},As=async(_,w)=>{if(Z!=="saving"){ge("saving"),je(null);try{if(c){const Y=W.find(B=>B.id===_);if(!Y)throw new Error(e("settings.providerTab.providerNotConfigured"));await ce.updateProviderInstance(Y.id,{config:{reasoning_effort:w??null}}),await Ae(),await st.getState().loadProviderInstances()}else{const Y=n.getFieldsValue(!0);await $t(Y,{showMessage:!1,throwOnError:!0}),await Bt({showMessage:!1,throwOnError:!0})}ge("success"),a.success(e("settings.providerTab.reasoningEffortUpdated"))}catch(Y){const B=bt(Y);ge("error"),je(B),a.error(B?`${e("settings.providerTab.updateReasoningEffortErrorPrefix")}: ${B}`:e("settings.providerTab.updateReasoningEffortFailed"))}}},ps=(_,w)=>{if(!_)return null;const Y=Xe(_)||_,B=n.getFieldValue(["providers",_,"reasoning_effort"]),K=(w==null?void 0:w.emphasis)==="subtle",fe=(w==null?void 0:w.label)||e("settings.providerTab.reasoningEffortOptional"),pe=(w==null?void 0:w.helperText)||e("settings.providerTab.reasoningEffortHelp");return t.jsx("div",{style:{marginTop:(w==null?void 0:w.marginTop)??8,width:"100%"},children:t.jsxs(L,{direction:"vertical",size:K?6:4,style:{width:"100%"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,flexWrap:"wrap"},children:[t.jsx(Ze,{strong:!K,type:K?"secondary":void 0,style:K?{fontSize:s.fontSizeSM,lineHeight:1.4}:void 0,children:fe}),w!=null&&w.showProviderLabel?t.jsx(Ze,{type:"secondary",style:{fontSize:s.fontSizeSM,lineHeight:1.4},children:Y}):null]}),Ft(e,{value:B,disabled:Z==="saving",size:(w==null?void 0:w.size)??(K?"small":void 0),style:{width:"100%"},"data-testid":w==null?void 0:w.dataTestId,onChange:Se=>{n.setFieldValue(["providers",_,"reasoning_effort"],Se),w!=null&&w.autoSave&&As(_,Se)}}),t.jsx(Ze,{type:"secondary",style:K?{fontSize:s.fontSizeSM,lineHeight:1.5}:void 0,children:pe})]})})},Rs=i.useCallback(_=>{const w=n.getFieldValue(["providers",_]);return w?_==="copilot"?(y==null?void 0:y.authenticated)??!1:!!w.api_key:!1},[n,y]),zs=()=>{const _=Y=>{const B=n.getFieldValue(["defaults",Y]);return t.jsx(Pn,{value:B,dataTestId:`model-preference-${Y}-picker`,appearance:"contrast",disabled:Z==="saving",onChange:K=>{n.setFieldValue(["defaults",Y],K),Fs(Y,K)}})},w=(Y,B,K)=>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(L,{direction:"vertical",size:8,style:{width:"100%"},children:[t.jsx(Ze,{strong:!0,children:B}),_(Y),K?t.jsx(Ze,{type:"secondary",children:K}):null]})}),t.jsx("div",{style:{flex:"0 1 320px",minWidth:280},children:t.jsx(f.Item,{noStyle:!0,shouldUpdate:!0,children:()=>{const fe=n.getFieldValue(["defaults",Y]),pe=fe==null?void 0:fe.provider;return ps(pe,{autoSave:!0,dataTestId:`model-preference-${Y}-reasoning-effort`,label:e("settings.providerTab.reasoningEffortOptional"),helperText:e("settings.providerTab.reasoningEffortHelp"),marginTop:0,size:"small",emphasis:"subtle",showProviderLabel:!!pe})}})})]});return t.jsxs(N,{size:"small",title:e("settings.providerTab.modelPreferences"),style:{marginBottom:16},children:[t.jsx(f.Item,{name:["defaults","chat"],noStyle:!0,preserve:!0,children:t.jsx(It,{})}),t.jsx(f.Item,{name:["defaults","fast"],noStyle:!0,preserve:!0,children:t.jsx(It,{})}),t.jsx(f.Item,{name:["defaults","task_summary"],noStyle:!0,preserve:!0,children:t.jsx(It,{})}),t.jsx(f.Item,{name:["defaults","memory_background"],noStyle:!0,preserve:!0,children:t.jsx(It,{})}),t.jsx(f.Item,{name:["defaults","sub_agent"],noStyle:!0,preserve:!0,children:t.jsx(It,{})}),t.jsx(f.Item,{name:["defaults","vision"],noStyle:!0,preserve:!0,children:t.jsx(It,{})}),t.jsxs(L,{direction:"vertical",size:16,style:{width:"100%"},children:[w("chat",e("settings.providerTab.defaultModel")),w("fast",e("settings.providerTab.fastModel"),e("settings.providerTab.fastModelHelp")),w("task_summary",e("settings.providerTab.taskSummaryModel"),e("settings.providerTab.taskSummaryModelHelp")),w("memory_background",e("settings.providerTab.memoryBackgroundModel"),e("settings.providerTab.memoryBackgroundModelHelp")),w("sub_agent",e("settings.providerTab.subAgentModel"),e("settings.providerTab.subAgentModelHelp")),w("vision",e("settings.providerTab.visionModel"),e("settings.providerTab.visionModelHelp"))]})]})},nt=_=>{const w=A.map(B=>B.name);return t.jsx(f.Item,{name:["providers",_,"request_overrides_json"],label:e("settings.providerTab.advancedRequestOverrides"),extra:t.jsxs(L,{direction:"vertical",size:4,children:[t.jsx(Ze,{type:"secondary",children:e("settings.providerTab.advancedRequestOverridesHelp")}),t.jsxs(Ze,{type:"secondary",children:[e("settings.providerTab.envVarInjection")," ",t.jsx(Ze,{code:!0,children:'{ "type": "env_ref", "name": "YOUR_ENV_NAME" }'})]}),w.length>0&&t.jsx(L,{wrap:!0,size:[6,6],children:w.map(B=>t.jsx(ie,{children:B},B))})]}),children:t.jsx(H.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"}})})},Ls=_=>{const w=x.has(_),Y=K=>w?[]:[{required:!0,message:K}],B=K=>w?e("settings.providerTab.apiKeyKeepPlaceholder","Configured — leave empty to keep"):K;switch(_){case"openai":return t.jsxs(t.Fragment,{children:[t.jsx(f.Item,{name:["providers","openai","api_key"],label:e("settings.providerTab.openaiApiKey"),rules:Y(e("settings.providerTab.openaiApiKeyRequired")),children:t.jsx(H.Password,{"data-testid":"api-key-input",placeholder:B(e("settings.providerTab.openaiApiKeyPlaceholder","sk-...")),prefix:t.jsx(xt,{})})}),t.jsx(f.Item,{name:["providers","openai","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.openaiBaseUrlHelp"),children:t.jsx(H,{placeholder:e("settings.providerTab.openaiBaseUrlPlaceholder","https://api.openai.com/v1")})}),t.jsx(f.Item,{name:["providers","openai","reasoning_effort"],label:e("settings.providerTab.reasoningEffortOptional"),extra:e("settings.providerTab.reasoningEffortHelp"),children:Ft(e)}),t.jsx(f.Item,{name:["providers","openai","responses_only_models"],label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:Ja(e),children:t.jsx(se,{mode:"tags",placeholder:e("settings.providerTab.responsesOnlyModelsPlaceholder",'e.g. "gpt-5.3-codex", "gpt-5*"'),tokenSeparators:[","," ",`
21
+ `," "]})}),t.jsx(Ne,{dashed:!0}),nt("openai")]});case"anthropic":return t.jsxs(t.Fragment,{children:[t.jsx(f.Item,{name:["providers","anthropic","api_key"],label:e("settings.providerTab.anthropicApiKey"),rules:Y(e("settings.providerTab.anthropicApiKeyRequired")),children:t.jsx(Ka,{placeholder:B(e("settings.providerTab.anthropicApiKeyPlaceholder","sk-ant-...")),prefix:t.jsx(xt,{})})}),t.jsx(f.Item,{name:["providers","anthropic","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.anthropicBaseUrlHelp"),children:t.jsx(H,{placeholder:e("settings.providerTab.anthropicBaseUrlPlaceholder","https://api.anthropic.com/v1")})}),t.jsx(f.Item,{name:["providers","anthropic","max_tokens"],label:e("settings.providerTab.maxTokensOptional"),extra:e("settings.providerTab.maxTokensHelp"),children:t.jsx(H,{type:"number",placeholder:e("settings.providerTab.maxTokensPlaceholder","4096"),min:1,max:1e5})}),t.jsx(f.Item,{name:["providers","anthropic","reasoning_effort"],label:e("settings.providerTab.reasoningEffortOptional"),extra:e("settings.providerTab.reasoningEffortHelp"),children:Ft(e)}),t.jsx(Ne,{dashed:!0}),nt("anthropic")]});case"gemini":return t.jsxs(t.Fragment,{children:[t.jsx(f.Item,{name:["providers","gemini","api_key"],label:e("settings.providerTab.geminiApiKey"),rules:Y(e("settings.providerTab.geminiApiKeyRequired")),children:t.jsx(Ka,{placeholder:B(e("settings.providerTab.geminiApiKeyPlaceholder","AIza...")),prefix:t.jsx(xt,{})})}),t.jsx(f.Item,{name:["providers","gemini","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.geminiBaseUrlHelp"),children:t.jsx(H,{placeholder:e("settings.providerTab.geminiBaseUrlPlaceholder","https://generativelanguage.googleapis.com/v1beta")})}),t.jsx(f.Item,{name:["providers","gemini","reasoning_effort"],label:e("settings.providerTab.reasoningEffortOptional"),extra:e("settings.providerTab.reasoningEffortHelp"),children:Ft(e)}),t.jsx(Ne,{dashed:!0}),nt("gemini")]});case"copilot":return t.jsxs(t.Fragment,{children:[t.jsxs(N,{size:"small",style:{marginBottom:16},title:e("settings.providerTab.authStatusTitle"),extra:R?t.jsx(rs,{size:"small"}):y!=null&&y.authenticated?t.jsx(ie,{icon:t.jsx(ea,{}),color:"success",children:e("settings.providerTab.authenticated")}):t.jsx(ie,{icon:t.jsx(ja,{}),color:"error",children:e("settings.providerTab.notAuthenticated")}),children:[(y==null?void 0:y.message)&&t.jsx(Js,{type:"secondary",style:{marginBottom:16},children:y.message}),t.jsxs(L,{children:[y!=null&&y.authenticated?t.jsx(z,{danger:!0,icon:t.jsx(tr,{}),onClick:Ce,loading:C,children:e("settings.providerTab.logoutCopilot")}):t.jsx(z,{type:"primary",icon:t.jsx(tn,{}),onClick:le,loading:C,children:e("settings.providerTab.authenticateCopilot")}),t.jsx(z,{onClick:h,loading:R,children:e("settings.providerTab.refreshStatus")})]})]}),t.jsx(f.Item,{name:["providers","copilot","headless_auth"],label:e("settings.providerTab.headlessAuth"),valuePropName:"checked",extra:e("settings.providerTab.headlessAuthHelp"),children:t.jsx(ye,{})}),t.jsx(f.Item,{name:["providers","copilot","reasoning_effort"],label:e("settings.providerTab.reasoningEffortOptional"),extra:e("settings.providerTab.reasoningEffortHelp"),children:Ft(e)}),t.jsx(f.Item,{name:["providers","copilot","responses_only_models"],label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:Ja(e),children:t.jsx(se,{mode:"tags",placeholder:e("settings.providerTab.responsesOnlyModelsPlaceholder",'e.g. "gpt-5.3-codex", "gpt-5*"'),tokenSeparators:[","," ",`
22
+ `," "]})}),t.jsx(Ne,{dashed:!0}),nt("copilot"),t.jsxs(Js,{type:"secondary",children:[e("settings.providerTab.copilotUsageTitle"),t.jsxs("ul",{style:{marginTop:8,marginBottom:0},children:[t.jsx("li",{children:e("settings.providerTab.copilotUsageStep1")}),t.jsx("li",{children:e("settings.providerTab.copilotUsageStep2")}),t.jsx("li",{children:e("settings.providerTab.copilotUsageStep3")})]})]})]});case"bodhi":return t.jsxs(t.Fragment,{children:[t.jsx(f.Item,{name:["providers","bodhi","api_key"],label:e("settings.providerTab.bodhiApiKey"),rules:Y(e("settings.providerTab.apiKeyRequired")),children:t.jsx(H.Password,{"data-testid":"bodhi-api-key-input",placeholder:B(e("settings.providerTab.bodhiApiKeyPlaceholder","bhi_sk_...")),prefix:t.jsx(xt,{})})}),t.jsx(f.Item,{name:["providers","bodhi","base_url"],label:e("settings.providerTab.bodhiBaseUrl"),extra:e("settings.providerTab.bodhiBaseUrlExtra"),children:t.jsx(H,{placeholder:e("settings.providerTab.bodhiBaseUrlPlaceholder","http://localhost:8080")})}),t.jsx(f.Item,{name:["providers","bodhi","target_provider"],label:e("settings.providerTab.targetProvider"),extra:e("settings.providerTab.targetProviderExtra"),children:t.jsxs(se,{placeholder:e("settings.providerTab.targetProviderPlaceholder","openai"),allowClear:!0,children:[t.jsx(se.Option,{value:"openai",children:"OpenAI"}),t.jsx(se.Option,{value:"anthropic",children:"Anthropic"}),t.jsx(se.Option,{value:"gemini",children:"Gemini"})]})}),t.jsx(f.Item,{name:["providers","bodhi","reasoning_effort"],label:e("settings.providerTab.reasoningEffortOptional"),extra:e("settings.providerTab.reasoningEffortHelp"),children:Ft(e)}),t.jsx(Ne,{dashed:!0}),nt("bodhi")]});default:return null}},hn=_=>{const w=Rs(_),Y=ft[_];return t.jsxs(L,{size:"small",children:[t.jsx("span",{style:{fontWeight:500},children:Y}),w?t.jsx(ie,{color:"success",style:{fontSize:11},children:e("settings.providerTab.authenticated")}):t.jsx(ie,{color:"default",style:{fontSize:11},children:e("settings.providerTab.providerNotConfigured")})]})};return t.jsxs(N,{title:e("settings.providerTab.title"),loading:r&&!d,className:"lotus-settings-card",children:[t.jsx(Js,{type:"secondary",children:e("settings.providerTab.description")}),t.jsx(Ne,{}),t.jsxs(f,{form:n,layout:"vertical",onFinish:Is,disabled:r&&!d,children:[!c&&t.jsxs(t.Fragment,{children:[t.jsx(f.Item,{name:"provider",label:e("settings.providerTab.activeProvider"),rules:[{required:!0,message:e("settings.providerTab.selectProviderRequired")}],children:t.jsx(se,{"data-testid":"provider-select",size:"large",onChange:_=>g(_),children:Object.keys(ft).map(_=>t.jsx(se.Option,{value:_,children:ft[_]},_))})}),t.jsx(f.Item,{noStyle:!0,shouldUpdate:!0,children:()=>ps(n.getFieldValue("provider")||m,{autoSave:!0,size:"middle",marginTop:0,dataTestId:"active-provider-reasoning-effort",label:e("settings.providerTab.activeProviderReasoningEffort"),helperText:e("settings.providerTab.reasoningEffortHelp")})}),t.jsx(Ne,{})]}),t.jsxs("div",{style:{marginBottom:16},children:[t.jsx(z,{icon:t.jsx(Ot,{}),onClick:Be,loading:O,children:e(O?"settings.providerTab.fetchingAllModels":"settings.providerTab.fetchAllModels")}),Z==="saving"&&t.jsx(rs,{size:"small",style:{marginLeft:8}}),Z==="success"&&t.jsx(ea,{style:{color:"var(--lotus-chart-secondary)",marginLeft:8}}),Z==="error"&&t.jsx(ke,{title:xe,children:t.jsx(ja,{style:{color:"var(--lotus-chart-danger)",marginLeft:8}})})]}),zs(),c?t.jsx(qo,{instances:W,defaultInstanceId:ue,onInstancesChanged:Ae}):t.jsx(ws,{activeKey:M,onChange:_=>G(Array.isArray(_)?_.map(String):_?[String(_)]:[]),ghost:!0,style:{marginBottom:16},items:es.map(_=>({key:_,label:hn(_),children:Ls(_)}))}),t.jsx(Ne,{}),t.jsx(L,{size:"middle",children:t.jsx(z,{"data-testid":"save-api-settings",type:"primary",htmlType:"submit",icon:t.jsx(Cs,{}),loading:r||l,size:"large",children:e("settings.providerTab.saveAndApply")})})]}),t.jsx(pn,{open:V,onCancel:()=>F(!1),onComplete:ve,onCopyCode:$e,completingAuth:U,copiedUserCode:T,deviceCodeInfo:p,timeRemaining:q,token:s})]})},{Text:Xa}=de,Wo=({skill:e,disabled:s=!1,busy:a=!1,onToggleDisabled:n})=>{const{t:r}=ne(),{token:o}=_e.useToken();return t.jsx(N,{title:t.jsxs(L,{size:o.marginXS,wrap:!0,style:{width:"100%",justifyContent:"space-between"},children:[t.jsxs(L,{size:o.marginXS,wrap:!0,children:[t.jsx("span",{children:e.name}),s&&t.jsx(ie,{color:"default",children:r("components.skillManager.disabledTag")}),e.license&&t.jsxs(ie,{color:"processing",children:["License: ",e.license]})]}),n&&t.jsx(ye,{checked:!s,loading:a,onChange:l=>n(e.id,!l),checkedChildren:r("components.skillManager.switchEnabled"),unCheckedChildren:r("components.skillManager.switchDisabled")})]}),styles:{body:{padding:o.paddingMD}},style:{opacity:s?.72:1},children:t.jsxs(L,{direction:"vertical",size:o.marginXS,style:{width:"100%"},children:[t.jsx(Xa,{type:"secondary",children:e.description}),e.compatibility&&t.jsxs(Xa,{type:"secondary",children:["Compatibility: ",e.compatibility]}),e.tool_refs.length>0&&t.jsx(L,{size:o.marginXXS,wrap:!0,children:e.tool_refs.map(l=>t.jsx(ie,{style:{background:o.colorFillSecondary,borderColor:o.colorBorderSecondary,color:o.colorText},children:l},l))})]})})},Go=3e4,Jo=()=>{const{t:e}=ne(),{message:s}=gt.useApp(),a=yt(F=>F.config),n=yt(F=>F.loadConfig),r=yt(F=>F.saveConfig),[o,l]=i.useState([]),[u,m]=i.useState(!1),[g,d]=i.useState(null),[j,x]=i.useState(null),[S,y]=i.useState(""),[b,R]=i.useState(new Date),P=i.useMemo(()=>{var F;return new Set((((F=a==null?void 0:a.skills)==null?void 0:F.disabled)??[]).map(U=>U.trim()).filter(Boolean))},[a]),C=i.useCallback(async(F=!0)=>{m(!0),d(null);try{const[U]=await Promise.all([Dn.listSkills({includeDisabled:!0},F),n({force:F})]);l(U.skills),R(new Date)}catch(U){const ae=U instanceof Error?U.message:e("components.skillManager.loadFailed");d(ae)}finally{m(!1)}},[n,e]);i.useEffect(()=>{C(!0);const F=setInterval(()=>{C(!0)},Go);return()=>clearInterval(F)},[C]),i.useEffect(()=>{const F=()=>{C(!0)};return window.addEventListener("focus",F),()=>window.removeEventListener("focus",F)},[C]);const I=i.useCallback(async()=>{await C(!0),s.success(e("components.skillManager.skillsRefreshed"))},[C,s,e]);i.useEffect(()=>{g&&(s.error(g),d(null))},[g,s]);const p=i.useCallback(async(F,U)=>{var ae;x(F);try{const q=await n({force:!0}),v=((ae=q==null?void 0:q.skills)==null?void 0:ae.disabled)??[],T=Array.from(new Set((U?[...v,F]:v.filter(D=>D!==F)).map(D=>D.trim()).filter(Boolean))).sort();await r({...q??{},skills:{...(q==null?void 0:q.skills)??{},disabled:T}}),s.success(e("components.skillManager.skillStateSaved"))}catch(q){s.error(q instanceof Error?q.message:e("components.skillManager.saveFailed"))}finally{x(null)}},[n,s,r,e]),k=o.filter(F=>{const U=S.trim().toLowerCase();return!(U&&![F.name,F.description,F.license??"",F.compatibility??"",...F.tool_refs].join(" ").toLowerCase().includes(U))}),V=()=>{const U=new Date().getTime()-b.getTime(),ae=Math.floor(U/1e3);if(ae<5)return e("components.skillManager.justNow");if(ae<60)return e("components.skillManager.secondsAgo",{count:ae});const q=Math.floor(ae/60);return q<60?e("components.skillManager.minutesAgo",{count:q}):b.toLocaleTimeString()};return t.jsx("div",{style:{padding:"24px"},children:t.jsxs(N,{className:"lotus-settings-card",title:t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[t.jsx("span",{children:e("components.skillManager.title")}),t.jsx(z,{icon:t.jsx(Ot,{spin:u}),onClick:I,loading:u,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:V()})})]}),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(H,{placeholder:e("components.skillManager.searchPlaceholder"),prefix:t.jsx(sr,{}),value:S,onChange:F=>y(F.target.value),allowClear:!0})}),t.jsx(rs,{spinning:u,children:k.length===0?t.jsx(Ue,{description:e(S?"components.skillManager.noMatch":"components.skillManager.noSkillsFound")}):t.jsx(Je,{grid:{gutter:16,xs:1,sm:2,md:3,lg:3,xl:4},dataSource:k,renderItem:F=>t.jsx(Je.Item,{children:t.jsx(Wo,{skill:F,disabled:P.has(F.id),busy:j===F.id,onToggleDisabled:p})})})})]})})},{Title:Xo,Text:bs,Paragraph:Yo}=de,aa="model_limits",Mt={max_context_tokens:1e6,max_output_tokens:128e3,safety_margin:1e4};function ns(e){if(typeof e!="number"||!Number.isFinite(e))return null;const s=Math.floor(e);return s>0?s:null}function Zo(e){const s=Array.isArray(e==null?void 0:e.model_limits)?e.model_limits[0]:void 0;return s?{max_context_tokens:ns(s.max_context_tokens)??Mt.max_context_tokens,max_output_tokens:ns(s.max_output_tokens)??Mt.max_output_tokens,safety_margin:ns(s.safety_margin)??Mt.safety_margin}:Mt}function Qo(e){if(!e||typeof e!="object")return null;const s=e,a=s.model_pattern??s.model;if(typeof a!="string"||!a.trim())return null;const n=ns(s.max_context_tokens??s.maxContextTokens),r=ns(s.max_output_tokens??s.maxOutputTokens);if(n===null||r===null)return null;const o=s.safety_margin??s.safetyMargin,l=typeof o=="number"&&Number.isFinite(o)&&o>=0?Math.floor(o):void 0;return{model_pattern:a.trim(),max_context_tokens:n,max_output_tokens:r,safety_margin:l}}function el(e){const s=e==null?void 0:e[aa];return Array.isArray(s)?s.map(a=>Qo(a)).filter(a=>a!==null):[]}function Ya(e,s,a){const n=new Map(s.map(l=>[l.model_pattern,l])),r=[],o=new Set;for(const l of s)o.has(l.model_pattern)||(o.add(l.model_pattern),r.push(l.model_pattern));for(const l of a){const u=l.trim();u&&!o.has(u)&&(o.add(u),r.push(u))}return r.map(l=>{const u=n.get(l);return{id:l,model_pattern:l,isCustom:!1,customized:!!u,max_context_tokens:(u==null?void 0:u.max_context_tokens)??e.max_context_tokens,max_output_tokens:(u==null?void 0:u.max_output_tokens)??e.max_output_tokens,safety_margin:u==null?void 0:u.safety_margin}})}function tl(e,s){const a=new Set;for(const n of e){const r=n.model_pattern.trim();if(!r)return s("settings.modelLimits.validation.modelPatternEmpty");const o=r.toLowerCase();if(a.has(o))return s("settings.modelLimits.validation.duplicateModelPattern",{pattern:r});if(a.add(o),n.max_context_tokens<1e3)return s("settings.modelLimits.validation.contextWindowMin",{pattern:r});if(n.max_output_tokens<1)return s("settings.modelLimits.validation.maxOutputMin",{pattern:r});if(n.max_output_tokens>n.max_context_tokens)return s("settings.modelLimits.validation.maxOutputExceedsContext",{pattern:r});if(typeof n.safety_margin=="number"){if(n.safety_margin<0)return s("settings.modelLimits.validation.safetyMarginNegative",{pattern:r});if(n.safety_margin>=n.max_context_tokens)return s("settings.modelLimits.validation.safetyMarginTooLarge",{pattern:r})}}return null}const Ys=i.memo(function({value:s,min:a,max:n,step:r,disabled:o,ariaLabel:l,onCommit:u}){const[m,g]=i.useState(s);return i.useEffect(()=>{g(s)},[s]),t.jsx(Me,{"aria-label":l,value:m,min:a,max:n,step:r,disabled:o,onChange:d=>g(typeof d=="number"?d:null),onBlur:()=>{const d=typeof m=="number"&&Number.isFinite(m)?m:s;g(d),d!==s&&u(d)},style:{width:"100%"}})}),sl=i.memo(function({value:s,placeholder:a,ariaLabel:n,onCommit:r}){const[o,l]=i.useState(s);return i.useEffect(()=>{l(s)},[s]),t.jsx(H,{"aria-label":n,value:o,placeholder:a,onChange:u=>l(u.target.value),onBlur:()=>{o!==s&&r(o)}})}),al=()=>{const{t:e}=ne(),[s,a]=i.useState(Mt),[n,r]=i.useState([]),[o,l]=i.useState(!1),[u,m]=Lt.useMessage(),g=i.useRef(!1),d=i.useRef(0),j=i.useCallback(async()=>{l(!0);try{const[p,k]=await Promise.all([ze.getBambooConfig(),ze.getModelLimitDefaults()]),V=Zo(k);a(V),r(Ya(V,el(p),ma()))}catch(p){console.error("Failed to load model limits settings:",p),u.error(e("settings.modelLimits.loadFailed")),a(Mt),r(Ya(Mt,[],ma()))}finally{l(!1)}},[u,e]);i.useEffect(()=>{g.current||(g.current=!0,j())},[j]);const x=i.useCallback((p,k)=>{r(V=>V.map(F=>F.id===p?{...F,...k}:F))},[]),S=i.useCallback(p=>{r(k=>k.map(V=>V.id===p?{...V,customized:!0}:V))},[]),y=i.useCallback(p=>{r(k=>{const V=k.find(F=>F.id===p);return V!=null&&V.isCustom?k.filter(F=>F.id!==p):k.map(F=>F.id===p?{...F,customized:!1,max_context_tokens:s.max_context_tokens,max_output_tokens:s.max_output_tokens,safety_margin:void 0}:F)})},[s]),b=i.useCallback(p=>{r(k=>{const V=k.find(F=>F.id===p);return V&&!V.isCustom&&V.model_pattern.trim()&&In(V.model_pattern),k.filter(F=>F.id!==p)})},[]),R=i.useCallback(()=>{r(p=>[...p,{id:`custom-${d.current++}`,model_pattern:"",isCustom:!0,customized:!0,max_context_tokens:s.max_context_tokens,max_output_tokens:s.max_output_tokens,safety_margin:void 0}])},[s]),P=async()=>{const p=n.filter(V=>V.customized).map(V=>({model_pattern:V.model_pattern.trim(),max_context_tokens:V.max_context_tokens,max_output_tokens:V.max_output_tokens,...typeof V.safety_margin=="number"?{safety_margin:V.safety_margin}:{}})),k=tl(p,e);if(k){u.error(k);return}l(!0);try{await ze.setBambooConfig({[aa]:p}),u.success(e("settings.modelLimits.saveSuccess"))}catch(V){console.error("Failed to save model limits settings:",V),u.error(e("settings.modelLimits.saveFailed"))}finally{l(!1)}},C=async()=>{l(!0);try{await ze.setBambooConfig({[aa]:[]}),r(p=>p.filter(k=>!k.isCustom).map(k=>({...k,customized:!1,max_context_tokens:s.max_context_tokens,max_output_tokens:s.max_output_tokens,safety_margin:void 0}))),u.success(e("settings.modelLimits.resetSuccess"))}catch(p){console.error("Failed to reset model limits settings:",p),u.error(e("settings.modelLimits.resetFailed"))}finally{l(!1)}},I=i.useMemo(()=>[{title:e("settings.modelLimits.columns.model"),dataIndex:"model_pattern",key:"model_pattern",width:240,render:(p,k)=>k.isCustom?t.jsx(sl,{value:p,ariaLabel:`model-${k.id}`,placeholder:e("settings.modelLimits.placeholders.model"),onCommit:V=>x(k.id,{model_pattern:V})}):t.jsx(bs,{strong:!0,children:p})},{title:e("settings.modelLimits.columns.contextWindow"),dataIndex:"max_context_tokens",key:"max_context_tokens",width:170,render:(p,k)=>t.jsx(Ys,{value:p,ariaLabel:`context-${k.id}`,min:1e3,max:5e6,step:1e3,disabled:!k.customized,onCommit:V=>x(k.id,{max_context_tokens:V})})},{title:e("settings.modelLimits.columns.maxOutput"),dataIndex:"max_output_tokens",key:"max_output_tokens",width:150,render:(p,k)=>t.jsx(Ys,{value:p,ariaLabel:`output-${k.id}`,min:1,max:5e6,step:256,disabled:!k.customized,onCommit:V=>x(k.id,{max_output_tokens:V})})},{title:e("settings.modelLimits.columns.safetyMargin"),dataIndex:"safety_margin",key:"safety_margin",width:150,render:(p,k)=>t.jsx(Ys,{value:p??s.safety_margin,ariaLabel:`safety-${k.id}`,min:0,max:1e6,step:100,disabled:!k.customized,onCommit:V=>x(k.id,{safety_margin:V})})},{title:e("settings.modelLimits.columns.status"),key:"status",width:150,render:(p,k)=>k.customized?t.jsx(ie,{color:"blue",children:e("settings.modelLimits.badge.customized")}):t.jsx(ke,{title:e("settings.modelLimits.badge.defaultTooltip"),children:t.jsx(ie,{children:e("settings.modelLimits.badge.default")})})},{title:e("settings.modelLimits.columns.actions"),key:"actions",width:200,render:(p,k)=>t.jsxs(L,{size:"small",children:[!k.customized&&t.jsx(z,{size:"small",type:"link",onClick:()=>S(k.id),children:e("settings.modelLimits.actions.customize")}),k.customized&&!k.isCustom&&t.jsx(z,{size:"small",onClick:()=>y(k.id),children:e("settings.modelLimits.actions.revert")}),t.jsx(z,{size:"small",type:"text",danger:!0,onClick:()=>b(k.id),children:e("settings.modelLimits.actions.remove")})]})}],[e,s.safety_margin,x,S,y,b]);return t.jsxs("div",{className:"model-limits-settings",children:[m,t.jsxs(N,{children:[t.jsx(Xo,{level:4,children:e("settings.modelLimits.title")}),t.jsxs(Yo,{type:"secondary",children:[e("settings.modelLimits.descriptionPrefix")," ",e("settings.modelLimits.descriptionSuffix")]}),t.jsx(Ne,{}),t.jsxs(L,{direction:"vertical",size:"small",style:{width:"100%"},children:[t.jsx(bs,{strong:!0,children:e("settings.modelLimits.defaultsTitle")}),t.jsx(bs,{type:"secondary",children:e("settings.modelLimits.defaultsDescription")}),t.jsx(bs,{type:"secondary",children:e("settings.modelLimits.globalDefault",{context:s.max_context_tokens.toLocaleString(),output:s.max_output_tokens.toLocaleString()})})]}),t.jsx(at,{dataSource:n,columns:I,rowKey:p=>p.id,pagination:!1,size:"small",style:{margin:"16px 0"},scroll:{x:1060},locale:{emptyText:t.jsx(Ue,{description:e("settings.modelLimits.emptyState")})}}),t.jsxs(L,{wrap:!0,children:[t.jsx(z,{icon:t.jsx(ut,{}),onClick:R,children:e("settings.modelLimits.actions.addModel")}),t.jsx(z,{type:"primary",icon:t.jsx(Cs,{}),onClick:()=>void P(),loading:o,children:e("settings.modelLimits.actions.save")}),t.jsx(z,{icon:t.jsx(Ot,{}),onClick:()=>void C(),loading:o,children:e("settings.modelLimits.actions.resetToDefaults")}),t.jsx(z,{onClick:()=>void j(),loading:o,children:e("settings.modelLimits.actions.reload")})]})]})]})},{Text:Zs}=de,{useToken:nl}=_e,rl="bamboo_dark_mode",fl=({themeMode:e,onThemeModeChange:s,locale:a,onLocaleChange:n,onBack:r})=>{const{t:o}=ne(),{token:l}=nl(),{deleteAllChats:u}=mr(),[m,g]=i.useState(!1),[d,j]=Lt.useMessage(),[x,S]=i.useState(""),[y,b]=i.useState(pa()),[R,P]=i.useState(ha()),[C,I]=i.useState(ya()),[p,k]=i.useState(fa()),V=st(c=>c.currentProvider),U=st(c=>c.getProviderType)(V)==="copilot",ae=Qs(c=>c.activeTabKey),q=Qs(c=>c.setActiveTabKey),v=Fn(c=>c.isAdvanced),T=l.paddingSM,D=(c,E)=>({key:c,label:t.jsx(Zs,{style:{color:l.colorTextSecondary,fontSize:12,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em",cursor:"default",userSelect:"none"},children:E}),disabled:!0,children:null}),A=(c,E)=>t.jsx("span",{"data-testid":`settings-tab-${c}`,children:E}),ee=()=>{localStorage.clear(),d.success(o("settings.notifications.localStorageCleared"))},O=async()=>{g(!0);try{await u(),await ze.resetSetupStatus(),await ze.resetBambooConfig(),localStorage.clear(),d.success(o("settings.notifications.resetSuccessReloading")),setTimeout(()=>{window.location.reload()},1500)}catch(c){console.error("Failed to reset application:",c),d.error(c instanceof Error?c.message:o("settings.notifications.resetFailed")),g(!1)}},Q=()=>{zn(x),d.success(o("settings.notifications.promptEnhancementSaved"))},W=c=>{b(c),Nn(c)},re=c=>{P(c),On(c)},ue=c=>{I(c),Ln(c)},be=c=>{k(c),Vn(c),window.dispatchEvent(new Event("lotus-vdi-safe-mode-change")),d.success(c?o("settings.appTab.vdiSafeModeEnabled","Graphics compatibility mode enabled"):o("settings.appTab.vdiSafeModeDisabled","Graphics compatibility mode disabled"))};return i.useEffect(()=>{S(An()),b(pa()),P(ha()),I(ya()),k(fa())},[]),t.jsxs(X,{vertical:!0,role:"region","aria-label":o("settings.page.title"),style:{height:"100vh",overflow:"hidden",background:l.colorBgContainer},children:[j,t.jsxs(X,{align:"center",justify:"space-between",style:{padding:l.padding,paddingTop:l.padding+T,borderBottom:`1px solid ${l.colorBorderSecondary}`},children:[t.jsxs(X,{align:"center",gap:l.marginSM,children:[t.jsx(z,{icon:t.jsx(ar,{}),onClick:r,"aria-label":o("settings.page.back"),children:o("settings.page.back")}),t.jsx(Zs,{strong:!0,"data-testid":"settings-page-title",children:o("settings.page.title")})]}),t.jsxs(Zs,{type:"secondary","data-testid":"settings-page-version",children:[o("settings.appTab.runningVersion","Running version"),": v",Za]})]}),t.jsx(nr.Content,{style:{flex:1,minHeight:0,overflow:"auto",padding:l.padding},children:t.jsx(Ts,{tabPosition:"left",activeKey:ae,onChange:c=>q(c),items:[D("group-ai",o("settings.page.groups.ai")),{key:"provider",label:A("provider",o("settings.page.tabs.provider")),children:t.jsx(Ko,{})},{key:"model-limits",label:A("model-limits",o("settings.page.tabs.modelLimits")),children:t.jsx(al,{})},{key:"prompts",label:A("prompts",o("settings.page.tabs.prompts")),children:t.jsx(Cr,{promptEnhancement:x,onPromptEnhancementChange:S,mermaidEnhancementEnabled:y,taskEnhancementEnabled:R,showCopilotConclusionWithOptionsEnhancement:U,copilotConclusionWithOptionsEnhancementEnabled:C,onMermaidToggle:W,onTaskToggle:re,onCopilotConclusionWithOptionsToggle:ue,onSaveEnhancement:Q})},D("group-tools",o("settings.page.groups.toolsAndExtensions")),{key:"skills",label:A("skills",o("settings.page.tabs.skills")),children:t.jsx(Jo,{})},{key:"mcp",label:A("mcp",o("settings.page.tabs.mcp")),children:t.jsx(Si,{})},{key:"workflows",label:A("workflows",o("settings.page.tabs.workflows")),children:t.jsx(Wr,{})},{key:"hooks",label:A("hooks",o("settings.page.tabs.hooks")),children:t.jsx(xo,{})},D("group-security",o("settings.page.groups.securityAndPrivacy")),{key:"permissions",label:A("permissions",o("settings.page.tabs.permissions")),children:t.jsx(Rr,{})},{key:"masking",label:A("masking",o("settings.page.tabs.masking")),children:t.jsx(Ir,{})},{key:"env-vars",label:A("env-vars",o("settings.page.tabs.envVars")),children:t.jsx(Or,{})},D("group-deployment",o("settings.page.groups.deployment","Deployment")),{key:"clusters",label:A("clusters",o("settings.page.tabs.clusters","Clusters")),children:t.jsx(qr,{})},D("group-monitoring",o("settings.page.groups.monitoring")),{key:"metrics",label:A("metrics",o("settings.page.tabs.metrics")),children:t.jsx(po,{})},{key:"sessions",label:A("sessions",o("settings.page.tabs.sessions")),children:t.jsx(Do,{})},D("group-system",o("settings.page.groups.system")),{key:"config",label:A("config",o("settings.page.tabs.config")),children:t.jsx(jr,{msgApi:d,locale:a,onLocaleChange:n})},{key:"schedules",label:A("schedules",o("settings.page.tabs.schedules")),children:t.jsx(Po,{})},{key:"notifications",label:A("notifications",o("settings.page.tabs.notifications","Notifications")),children:t.jsx(Lo,{})},{key:"app",label:A("app",o("settings.page.tabs.app")),children:t.jsx(Er,{themeMode:e,onThemeModeChange:s,vdiSafeMode:p,onVdiSafeModeToggle:be,onClearLocalStorage:ee,onResetApp:O,isResetting:m,darkModeKey:rl})}].filter(c=>!(!v&&c.key&&Rn.has(c.key)||!v&&(c.key==="group-security"||c.key==="group-deployment"||c.key==="group-monitoring")))})})]})};export{fl as SystemSettingsPage};