@bigduu/lotus 2026.6.13 → 2026.6.15

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