@bigduu/lotus 2026.6.20 → 2026.6.21

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 (64) hide show
  1. package/dist/assets/{App-CG8bbjSe.js → App-BE03KO2t.js} +9 -9
  2. package/dist/assets/{MetricsService-BY057XSj.js → MetricsService-C_09AaLH.js} +1 -1
  3. package/dist/assets/{SubAgentsPanel-TdCKptD-.js → SubAgentsPanel-Bfdx96WN.js} +1 -1
  4. package/dist/assets/{architectureDiagram-3BPJPVTR-BUvShG40.js → architectureDiagram-3BPJPVTR-CFnNIaH9.js} +1 -1
  5. package/dist/assets/{blockDiagram-GPEHLZMM-omczCfAL.js → blockDiagram-GPEHLZMM-DGU1zBz2.js} +1 -1
  6. package/dist/assets/{c4Diagram-AAUBKEIU-D3loFTFR.js → c4Diagram-AAUBKEIU-DzPdW8pi.js} +1 -1
  7. package/dist/assets/{chunk-2J33WTMH-vXnUzqcL.js → chunk-2J33WTMH-C3gWLOQi.js} +1 -1
  8. package/dist/assets/{chunk-4BX2VUAB-Bduc68-M.js → chunk-4BX2VUAB-DwQ_yJZR.js} +1 -1
  9. package/dist/assets/{chunk-55IACEB6-CQurPzzm.js → chunk-55IACEB6-5KcZ5Mg4.js} +1 -1
  10. package/dist/assets/{chunk-727SXJPM-cr42BARz.js → chunk-727SXJPM-CTyFupuz.js} +1 -1
  11. package/dist/assets/{chunk-AQP2D5EJ-DPgkAB9a.js → chunk-AQP2D5EJ-D3TfocFk.js} +1 -1
  12. package/dist/assets/{chunk-FMBD7UC4-DM2eEyUs.js → chunk-FMBD7UC4-BBYX4gAn.js} +1 -1
  13. package/dist/assets/{chunk-ND2GUHAM-BdiRuLUa.js → chunk-ND2GUHAM-PiVQlHJA.js} +1 -1
  14. package/dist/assets/{chunk-QZHKN3VN-AdFyQtzD.js → chunk-QZHKN3VN-C9UTL9tu.js} +1 -1
  15. package/dist/assets/classDiagram-4FO5ZUOK-MIZ51UHT.js +1 -0
  16. package/dist/assets/classDiagram-v2-Q7XG4LA2-MIZ51UHT.js +1 -0
  17. package/dist/assets/{cose-bilkent-S5V4N54A-COuE4psp.js → cose-bilkent-S5V4N54A-C5-z7pIR.js} +1 -1
  18. package/dist/assets/{dagre-BM42HDAG-Ds00sUTy.js → dagre-BM42HDAG-C2EAYn6-.js} +1 -1
  19. package/dist/assets/{diagram-2AECGRRQ-WL9Y87tr.js → diagram-2AECGRRQ-BZsh3U_K.js} +1 -1
  20. package/dist/assets/{diagram-5GNKFQAL-aBrAL8WM.js → diagram-5GNKFQAL-BfkxTDEq.js} +1 -1
  21. package/dist/assets/{diagram-KO2AKTUF-xncsnLEI.js → diagram-KO2AKTUF-Cu8CoWQf.js} +1 -1
  22. package/dist/assets/{diagram-LMA3HP47-BKxHjemY.js → diagram-LMA3HP47-BdZRMnoP.js} +1 -1
  23. package/dist/assets/{diagram-OG6HWLK6-ByznP8cO.js → diagram-OG6HWLK6-qEwmDizB.js} +1 -1
  24. package/dist/assets/{erDiagram-TEJ5UH35-DU5qPROE.js → erDiagram-TEJ5UH35-By7SLdIO.js} +1 -1
  25. package/dist/assets/{flowDiagram-I6XJVG4X-C2F4XnqL.js → flowDiagram-I6XJVG4X-DY2A79PB.js} +1 -1
  26. package/dist/assets/{ganttDiagram-6RSMTGT7-B1faqJNo.js → ganttDiagram-6RSMTGT7-BCFnbnNO.js} +1 -1
  27. package/dist/assets/{gitGraphDiagram-PVQCEYII-cqui4Qfv.js → gitGraphDiagram-PVQCEYII-Dh0JLNiL.js} +1 -1
  28. package/dist/assets/{index-KM7uqSeO.js → index-B9iUdLip.js} +3 -3
  29. package/dist/assets/{index-2n2SNzxw.js → index-BDpQmQcF.js} +1 -1
  30. package/dist/assets/{index-BqUD7qIk.js → index-BHVwy6LC.js} +1 -1
  31. package/dist/assets/{index-CpTnNqu7.js → index-Btfg18vs.js} +1 -1
  32. package/dist/assets/{index-BW_rAoL5.js → index-BwN42ilc.js} +1 -1
  33. package/dist/assets/{index-BnQF9BCm.js → index-C5LikZFS.js} +1 -1
  34. package/dist/assets/{index-CvJxkeFo.js → index-CuoIA2BI.js} +1 -1
  35. package/dist/assets/{index-DhuMOkuR.js → index-CypAYsxn.js} +1 -1
  36. package/dist/assets/{index-BeelmCtF.js → index-DOE29cJ_.js} +1 -1
  37. package/dist/assets/{index-Xinu8DWx.js → index-DfUeAKyS.js} +1 -1
  38. package/dist/assets/{index-bCpdtLdC.js → index-SYbkHxZ5.js} +1 -1
  39. package/dist/assets/{index-Bf7_I7lH.js → index-ywqu1YSt.js} +1 -1
  40. package/dist/assets/{infoDiagram-5YYISTIA-DOvPDrOE.js → infoDiagram-5YYISTIA-BditIGGi.js} +1 -1
  41. package/dist/assets/{ishikawaDiagram-YF4QCWOH-0k0oYtIK.js → ishikawaDiagram-YF4QCWOH-Cq0ZTw82.js} +1 -1
  42. package/dist/assets/{journeyDiagram-JHISSGLW-C8JpdLIs.js → journeyDiagram-JHISSGLW-Hno4e2_P.js} +1 -1
  43. package/dist/assets/{kanban-definition-UN3LZRKU-BF8B3Of4.js → kanban-definition-UN3LZRKU-SFLCIrsL.js} +1 -1
  44. package/dist/assets/{main-Bae5Z9x6.js → main-DE4q1A6J.js} +3 -3
  45. package/dist/assets/{mindmap-definition-RKZ34NQL-BdYqZgSn.js → mindmap-definition-RKZ34NQL-Dv1i0LBZ.js} +1 -1
  46. package/dist/assets/{pieDiagram-4H26LBE5-DslzBdtA.js → pieDiagram-4H26LBE5-DrzipmnN.js} +1 -1
  47. package/dist/assets/{quadrantDiagram-W4KKPZXB-DjLReYd6.js → quadrantDiagram-W4KKPZXB-CbVG7rYB.js} +1 -1
  48. package/dist/assets/{requirementDiagram-4Y6WPE33-DBNIBpnN.js → requirementDiagram-4Y6WPE33-_teUDEd_.js} +1 -1
  49. package/dist/assets/{sankeyDiagram-5OEKKPKP-DBfwCo3t.js → sankeyDiagram-5OEKKPKP-CCwEIiwo.js} +1 -1
  50. package/dist/assets/{sequenceDiagram-3UESZ5HK-BeokAqv3.js → sequenceDiagram-3UESZ5HK-C8AleVLZ.js} +1 -1
  51. package/dist/assets/{stateDiagram-AJRCARHV-D0_29gC_.js → stateDiagram-AJRCARHV-B-1jeSlx.js} +1 -1
  52. package/dist/assets/{stateDiagram-v2-BHNVJYJU-BmoE01-Q.js → stateDiagram-v2-BHNVJYJU-kXIhlS8W.js} +1 -1
  53. package/dist/assets/{timeline-definition-PNZ67QCA-DLJCAk48.js → timeline-definition-PNZ67QCA-BiDTWxYs.js} +1 -1
  54. package/dist/assets/{vendor-charts-C1qs2RDI.js → vendor-charts-DgNVhh9m.js} +1 -1
  55. package/dist/assets/{vendor-mermaid-Cez766TY.js → vendor-mermaid-B53piAPW.js} +3 -3
  56. package/dist/assets/{vendor-pdf-DhHoqANy.js → vendor-pdf-DVpmGfqI.js} +3 -3
  57. package/dist/assets/{vennDiagram-CIIHVFJN-Z5aH7FvY.js → vennDiagram-CIIHVFJN-DlVqGLxi.js} +1 -1
  58. package/dist/assets/{wardley-L42UT6IY-DFiCK17w.js → wardley-L42UT6IY-Bu1lxJJ1.js} +1 -1
  59. package/dist/assets/{wardleyDiagram-YWT4CUSO-Cd2bS0UW.js → wardleyDiagram-YWT4CUSO-CnWKdyBU.js} +1 -1
  60. package/dist/assets/{xychartDiagram-2RQKCTM6-Dy3zXPjx.js → xychartDiagram-2RQKCTM6-B9yWrLfp.js} +1 -1
  61. package/dist/index.html +2 -2
  62. package/package.json +1 -1
  63. package/dist/assets/classDiagram-4FO5ZUOK-C4wtpAwq.js +0 -1
  64. package/dist/assets/classDiagram-v2-Q7XG4LA2-C4wtpAwq.js +0 -1
@@ -1,6 +1,6 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-BW_rAoL5.js","./vendor-markdown-teEfNS9t.js","./vendor-i18n-Dm-c3D_C.js","./vendor-antd-qu012Od4.js","./App-CG8bbjSe.js","./vendor-mermaid-Cez766TY.js","./main-Bae5Z9x6.js","./main-B6snAd4S.css","./App-xovo7L2Z.css"])))=>i.map(i=>d[i]);
2
- var ua=Object.defineProperty;var ga=(e,s,n)=>s in e?ua(e,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[s]=n;var on=(e,s,n)=>ga(e,typeof s!="symbol"?s+"":s,n);import{j as t}from"./vendor-markdown-teEfNS9t.js";import{a as o,u as se,R as ln,i as ae}from"./vendor-i18n-Dm-c3D_C.js";import{J as ma,u as He,b as pa,T as ha,g as fa,U as en,d as et,B as ot,V as ya,W as pt,X as Fe,Y as xa,Z as ba,_ as va,$ as Ta,a0 as Jn,a1 as at,a2 as fe,H as cn,a as Xe,a3 as Xn,G as tn,m as ja,l as Js,q as Sa,a4 as _a,a5 as ht,k as xs,a6 as ka,a7 as wa,a8 as dn,a9 as Ca,aa as un,ab as gn,ac as mn,ad as pn,o as Ma,ae as Ea,A as Da,af as Pa,ag as Ia,ah as Fa,ai as Aa,aj as Ra}from"./App-CG8bbjSe.js";import{U as O,o as R,I as $e,j as ue,a6 as q,B as z,t as ye,a1 as _,a0 as ts,aF as vs,aG as ee,aH as pe,aI as we,J as Je,aJ as Ge,aK as de,D as Te,aL as Ue,aM as za,aD as Re,Q as K,aN as Ss,aO as Oa,a3 as ss,a4 as At,al as La,aP as Na,A as xt,aQ as _s,p as ks,a2 as yt,x as re,aR as hn,aS as ct,a5 as lt,at as Rt,$ as zt,n as It,aT as Va,ak as $a,aU as fn,aV as Ae,Y as Be,as as Yn,aW as Ba,aX as dt,aY as Se,y as qa,aZ as yn,a_ as Ua,a$ as Ha,z as Xs,W as Ka,b0 as Wa,b1 as Ga,b2 as Zn,b3 as ft,b4 as xn,b5 as Ja,ae as Xa,az as Ya,b6 as Za}from"./vendor-antd-qu012Od4.js";import{_ as Ys}from"./vendor-mermaid-Cez766TY.js";import{r as Qa}from"./onboardingStorage-BVcEpmTy.js";import"./main-Bae5Z9x6.js";import{m as Qt}from"./MetricsService-BY057XSj.js";import{R as Ot,B as sn,C as rs,X as is,Y as os,T as Lt,L as nn,a as Ts,b as Qn,c as Ft,P as er,d as tr,e as sr}from"./vendor-charts-C1qs2RDI.js";function nr(e){return e instanceof ma}function ar(){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(pa(w=>({chats:w.chats,currentSessionId:w.currentSessionId,currentChat:ha(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(fa(s)),y=o.useMemo(()=>(n==null?void 0:n.messages)||[],[n]),b=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:y,pinnedChats:b,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 rr(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 y=a.find(D=>D.id===n),b=(y==null?void 0:y.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:b,baseSystemPrompt:(y==null?void 0:y.content)||(a.length>0?((w=a.find(D=>D.id==="general_assistant"))==null?void 0:w.content)||a[0].content:""),lastUsedEnhancedPrompt:null,...et.getState().isProviderModelRefEnabled()?{model_ref:et.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(y=>y.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 ir(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 or=()=>{const e=ar(),s=rr(e),n=ya({sessionId:e.currentSessionId,addMessage:e.addMessage,updateSession:e.updateSession}),a=ir(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:lr}=ye,cr=({httpProxy:e,httpsProxy:s,onHttpProxyChange:n,onHttpsProxyChange:a,onReload:r,onSave:i,isLoading:l})=>{const{t:d}=se(),{token:u}=lr(),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),[y,b]=o.useState({username:"",password:""}),[F,M]=o.useState(!1);o.useEffect(()=>{x()},[x]);const w=async()=>{const m=y.username.trim();if(m){M(!0);try{await h({username:m,password:y.password}),b({username:"",password:""})}catch(T){console.error("Failed to apply proxy auth:",T)}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(O,{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(q,{"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(q,{style:{width:"100%"},value:s,onChange:m=>a(m.target.value),placeholder:d("settings.networkCard.proxyPlaceholder"),disabled:l})]}),t.jsx(O,{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(z,{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(q,{placeholder:d("settings.networkCard.username"),value:y.username,onChange:m=>b(T=>({...T,username:m.target.value}))}),t.jsx(q.Password,{placeholder:d("settings.networkCard.password"),value:y.password,onChange:m=>b(T=>({...T,password:m.target.value}))}),t.jsx(z,{type:"primary",onClick:w,loading:F||c,disabled:!y.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(z,{onClick:()=>Promise.resolve(r()).finally(()=>x({force:!0})),disabled:l,children:d("settings.networkCard.reload")}),t.jsx(z,{"data-testid":"save-proxy-settings",type:"primary",onClick:()=>Promise.resolve(i()).finally(()=>x({force:!0})),disabled:l,children:d("settings.networkCard.save")})]})]})})};function ea(e){return typeof e=="object"&&e!==null&&"errorFields"in e}const{Text:dr}=ue,{useToken:ur}=ye,gr=({msgApi:e})=>{const{t:s}=se(),{token:n}=ur(),[a]=_.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),y=u&&!c,b=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(ea(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(O,{size:"small",className:"lotus-settings-card",title:t.jsx(dr,{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:b}),h?t.jsx($e,{type:"error",showIcon:!0,message:h}):null,t.jsxs(_,{form:a,layout:"vertical",disabled:r||l,children:[y?t.jsx(_.Item,{label:s("settings.configTab.accessPassword.currentPasswordLabel"),name:"currentPassword",rules:[{required:!0,message:s("settings.configTab.accessPassword.validation.currentPasswordRequired")}],children:t.jsx(q.Password,{autoComplete:"current-password"})}):null,t.jsx(_.Item,{label: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(q.Password,{autoComplete:"new-password"})}),t.jsx(_.Item,{label:s("settings.configTab.accessPassword.confirmPasswordLabel"),name:"confirmPassword",dependencies:["newPassword"],rules:[{required:!0,message:s("settings.configTab.accessPassword.validation.confirmPasswordRequired")},({getFieldValue:w})=>({validator(D,m){return!m||w("newPassword")===m?Promise.resolve():Promise.reject(new Error(s("settings.configTab.accessPassword.validation.passwordMismatch")))}})],children:t.jsx(q.Password,{autoComplete:"new-password"})}),t.jsx(z,{type:"primary",loading:l,onClick:()=>void M(),children:s(u?"settings.configTab.accessPassword.updateAction":"settings.configTab.accessPassword.enableAction")})]})]})})},{Text:Ve}=ue,{useToken:mr}=ye,bn="http://127.0.0.1:9562/v1",Yt=e=>[...new Set(e.map(s=>s.trim()).filter(s=>s.length>0))].sort(),pr=e=>{var n;const s=(n=e.tools)==null?void 0:n.disabled;return Array.isArray(s)?Yt(s.filter(a=>typeof a=="string")):[]},hr=({msgApi:e,locale:s,onLocaleChange:n})=>{const{t:a}=se(),{token:r}=mr(),[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,y]=o.useState([]),[b,F]=o.useState(!1),[M,w]=o.useState(!1),D=o.useCallback(async()=>{var A,Z;F(!0);try{const[W,ne]=await Promise.all([Fe.getBambooConfig(),Fe.getBambooTools()]);l({http_proxy:W.http_proxy||"",https_proxy:W.https_proxy||"",memory:{auto_dream_enabled:((A=W.memory)==null?void 0:A.auto_dream_enabled)??!1},subagents:{max_concurrent:(Z=W.subagents)==null?void 0:Z.max_concurrent}});const ie=pr(W);h(ie),y(ie),c(Yt(ne.tools||[]))}catch(W){console.error("Failed to load config:",W),e.error(a("settings.configTab.loadConfigFailed"))}finally{F(!1)}},[e,a]);o.useEffect(()=>{D()},[D]);const m=A=>{l(Z=>({...Z,http_proxy:A}))},T=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}}))},U=async A=>{var Z,W;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 ie=await Fe.validateBambooConfigPatch(ne);if(!ie.valid){const C=((W=(Z=ie.errors)==null?void 0:Z.proxy)==null?void 0:W[0])??Object.values(ie.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 ie=ne instanceof Error&&ne.message.trim()?ne.message:a("settings.configTab.saveConfigFailed");e.error(ie)}finally{F(!1)}},Q=async()=>{e.success(a("settings.configTab.backendSaved"))},N=()=>{u(bn),e.success(a("settings.configTab.backendResetDefault"))},f=(A,Z)=>{h(W=>{const ne=new Set(W);return Z?ne.delete(A):ne.add(A),Yt([...ne])})},j=async()=>{w(!0);try{const A=await Fe.getBambooTools();c(Yt(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=Yt(x);await Fe.setBambooConfig({tools:{disabled:A}}),h(A),y(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(ts,{spinning:b,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(cr,{httpProxy:i.http_proxy,httpsProxy:i.https_proxy,onHttpProxyChange:m,onHttpsProxyChange:T,onReload:D,onSave:()=>U("network"),isLoading:b}),t.jsx(O,{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(O,{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(z,{"data-testid":"save-memory-settings",type:"primary",onClick:()=>U("memory"),loading:b,children:a("settings.configTab.save")})})]})}),t.jsx(O,{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(z,{"data-testid":"save-subagent-settings",type:"primary",onClick:()=>U("subagents"),loading:b,children:a("settings.configTab.save")})})]})}),t.jsx(O,{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(q,{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(z,{"data-testid":"reset-to-defaults",onClick:N,children:a("settings.configTab.resetToDefault")}),t.jsx(z,{"data-testid":"save-api-settings",type:"primary",onClick:Q,children:a("settings.configTab.save")})]})]})}),t.jsx(gr,{msgApi:e})]})},{key:"tools",label:a("settings.configTab.tabs.tools"),children:t.jsx(O,{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(Je,{bordered:!0,dataSource:g,renderItem:A=>t.jsx(Je.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(z,{onClick:j,loading:M,children:a("settings.configTab.reloadTools")}),t.jsx(z,{type:"primary",onClick:E,loading:M,disabled:!I,children:a("settings.configTab.save")})]})]})})}]})})},{Title:fr,Text:zs}=ue,{useToken:yr}=ye,xr=()=>{const{t:e}=se(),{token:s}=yr(),n=xa(),a=ba(),r=va(),[i]=_.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(fr,{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(_,{form:i,layout:"vertical",initialValues:n,onValuesChange:d,children:[t.jsxs(O,{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(_.Item,{name:"theme",label:t.jsxs(R,{children:[e("settings.mermaidTab.themeLabel"),t.jsx(Te,{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(O,{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(_.Item,{name:"fontSize",label:t.jsxs(R,{children:[e("settings.mermaidTab.fontSizeLabel"),t.jsx(Te,{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(_.Item,{name:"defaultScale",label:t.jsxs(R,{children:[e("settings.mermaidTab.defaultZoomLabel"),t.jsx(Te,{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(_.Item,{name:"useMaxWidth",label:t.jsxs(R,{children:[e("settings.mermaidTab.responsiveWidthLabel"),t.jsx(Te,{title:e("settings.mermaidTab.responsiveWidthTooltip"),children:t.jsx(Ue,{style:{color:s.colorTextSecondary}})})]}),valuePropName:"checked",children:t.jsx(pe,{})})]}),t.jsx(O,{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(_.Item,{name:"flowchartNodeSpacing",label:t.jsxs(R,{children:[e("settings.mermaidTab.flowchartNodeSpacingLabel"),t.jsx(Te,{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(_.Item,{name:"flowchartRankSpacing",label:t.jsxs(R,{children:[e("settings.mermaidTab.flowchartRankSpacingLabel"),t.jsx(Te,{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(_.Item,{name:"flowchartCurve",label:t.jsxs(R,{children:[e("settings.mermaidTab.flowchartCurveTypeLabel"),t.jsx(Te,{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(O,{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(_.Item,{name:"sequenceActorMargin",label:t.jsxs(R,{children:[e("settings.mermaidTab.sequenceActorMarginLabel"),t.jsx(Te,{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(_.Item,{name:"sequenceMessageMargin",label:t.jsxs(R,{children:[e("settings.mermaidTab.sequenceMessageMarginLabel"),t.jsx(Te,{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(_.Item,{name:"sequenceWidth",label:t.jsxs(R,{children:[e("settings.mermaidTab.sequenceActorWidthLabel"),t.jsx(Te,{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(_.Item,{name:"sequenceHeight",label:t.jsxs(R,{children:[e("settings.mermaidTab.sequenceActorHeightLabel"),t.jsx(Te,{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(O,{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(_.Item,{name:"ganttBarHeight",label:t.jsxs(R,{children:[e("settings.mermaidTab.ganttBarHeightLabel"),t.jsx(Te,{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(_.Item,{name:"ganttTopPadding",label:t.jsxs(R,{children:[e("settings.mermaidTab.ganttTopPaddingLabel"),t.jsx(Te,{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(z,{icon:t.jsx(za,{}),onClick:u,children:e("settings.mermaidTab.resetToDefaults")})}),t.jsx(Re,{}),t.jsx(O,{title:e("settings.mermaidTab.previewTitle"),styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsx(zs,{type:"secondary",children:e("settings.mermaidTab.previewDescription")})})]})]})},br=o.lazy(()=>Ys(()=>import("./index-BW_rAoL5.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8]),import.meta.url)),{Text:Tt}=ue,{useToken:vr}=ye,Tr=({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}=vr(),h=x.marginLG;return t.jsxs(K,{vertical:!0,gap:h,children:[t.jsx(O,{size:"small",className:"lotus-settings-card",children:t.jsx(o.Suspense,{fallback:t.jsx(ts,{size:"small"}),children:t.jsx(br,{})})}),t.jsx(O,{size:"small",className:"lotus-settings-card",children:t.jsxs(R,{direction:"vertical",size:x.marginXS,style:{width:"100%"},children:[t.jsx(Tt,{strong:!0,children:c("settings.promptsTab.title")}),t.jsxs(K,{align:"center",gap:x.marginSM,children:[t.jsx(Tt,{strong:!0,children:c("settings.promptsTab.mermaidEnhancement")}),t.jsx(pe,{checked:n,onChange:l})]}),t.jsxs(K,{align:"center",gap:x.marginSM,children:[t.jsx(Tt,{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(K,{align:"center",gap:x.marginSM,children:[t.jsx(Tt,{strong:!0,children:c("settings.promptsTab.copilotConclusionWithOptionsBeforeFinish")}),t.jsx(pe,{checked:i,onChange:u})]}),t.jsx(Tt,{type:"secondary",style:{fontSize:x.fontSizeSM},children:c("settings.promptsTab.copilotConclusionWithOptionsBeforeFinishDescription",{defaultValue:Ta()})})]}),t.jsx(q.TextArea,{rows:6,placeholder:c("settings.promptsTab.enhancementPlaceholder"),value:e,onChange:S=>s(S.target.value)}),t.jsx(K,{justify:"flex-end",children:t.jsx(z,{type:"primary",onClick:g,children:c("settings.promptsTab.saveEnhancement")})}),t.jsx(Tt,{type:"secondary",style:{fontSize:x.fontSizeSM},children:c("settings.promptsTab.description")})]})}),n&&t.jsx(Ss,{size:"small",items:[{key:"mermaid",label:t.jsx(Tt,{strong:!0,children:c("settings.mermaidTab.title")}),children:t.jsx(xr,{})}]})]})},{Text:gt}=ue,{useToken:jr}=ye,Sr=({themeMode:e,onThemeModeChange:s,vdiSafeMode:n,onVdiSafeModeToggle:a,onClearLocalStorage:r,onResetApp:i,isResetting:l,darkModeKey:d})=>{const{t:u}=se(),{token:g}=jr();return t.jsx(O,{size:"small",className:"lotus-settings-card",children:t.jsxs(R,{direction:"vertical",size:g.marginSM,style:{width:"100%"},children:[t.jsxs(K,{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",Jn]})]}),t.jsx(gt,{type:"secondary",style:{fontSize:g.fontSizeSM},children:u("settings.appTab.runningVersionDesc","This is the currently running Lotus frontend version.")}),t.jsxs(K,{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(K,{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(z,{block:!0,icon:t.jsx(Oa,{}),onClick:()=>{Qa(),window.location.reload()},children:u("settings.appTab.resetStepReplayGuide")}),t.jsx(ss,{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(z,{danger:!0,block:!0,icon:t.jsx(At,{}),children:u("settings.appTab.clearLocalStorageButton")})}),t.jsx(Re,{style:{margin:`${g.marginSM}px 0`}}),t.jsxs(K,{align:"center",gap:g.marginSM,children:[t.jsx(La,{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(ss,{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(z,{"data-testid":"reset-to-defaults",danger:!0,block:!0,type:"primary",icon:t.jsx(Na,{}),loading:l,children:u("settings.appTab.resetButton")})})]})})},{Text:jt}=ue,{useToken:_r}=ye,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,}"}],kr=(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")}}},wr=()=>{const{t:e}=se(),{message:s}=xt.useApp(),{token:n}=_r(),[a,r]=o.useState([]),[i,l]=o.useState(!1),[d,u]=o.useState(null),[g,c]=o.useState(""),[x,h]=o.useState("exact"),[S,y]=o.useState(!0),[b,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(j){s.error(e("settings.keywordMaskingTab.loadFailed")),console.error(j)}finally{l(!1)}},[s,e]);o.useEffect(()=>{D()},[D]);const m=async j=>{try{const E=at.getInstance(),I=await E.validateKeywordEntries(j);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(j);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}},T=async()=>{const j={pattern:"",match_type:"exact",enabled:!0},E=[...a,j];r(E),u(E.length-1),c(""),h("exact"),y(!0),F(void 0)},L=j=>{const E=a[j];u(j),c(E.pattern),h(E.match_type),y(E.enabled),F(void 0)},P=async()=>{if(d===null)return;if(!g.trim()){s.error(e("settings.keywordMaskingTab.patternRequired"));return}const j=[...a];j[d]={pattern:g.trim(),match_type:x,enabled:S},await m(j)&&u(null)},U=()=>{var j;d!==null&&!((j=a[d])!=null&&j.pattern)&&r(a.filter((E,I)=>I!==d)),u(null)},Q=async j=>{const E=a.filter((I,Y)=>Y!==j);await m(E)},N=async(j,E)=>{const I=[...a];I[j]={...I[j],enabled:E},await m(I)},f=kr(M,g,x);return t.jsx(O,{className:"lotus-settings-card",title:e("settings.keywordMaskingTab.title"),extra:t.jsx(z,{"data-testid":"add-keyword",type:"primary",icon:t.jsx(yt,{}),onClick:T,loading:i,children:e("settings.keywordMaskingTab.addKeyword")}),children:t.jsxs(R,{direction:"vertical",style:{width:"100%"},size:"large",children:[t.jsx(jt,{type:"secondary",children:e("settings.keywordMaskingTab.description")}),t.jsx(Je,{loading:i,dataSource:a,locale:{emptyText:e("settings.keywordMaskingTab.empty")},renderItem:(j,E)=>t.jsx(Je.Item,{style:{backgroundColor:n.colorFillAlter,marginBottom:8,borderRadius:n.borderRadius,padding:12},actions:d===E?[t.jsx(z,{"data-testid":"save-keyword",type:"primary",icon:t.jsx(_s,{}),onClick:P,"aria-label":e("settings.keywordMaskingTab.save")},"save"),t.jsx(z,{onClick:U,children:e("settings.keywordMaskingTab.cancel")},"cancel")]:[t.jsx(z,{icon:t.jsx(ks,{}),onClick:()=>L(E),"aria-label":e("settings.keywordMaskingTab.edit")},"edit"),t.jsx(z,{"data-testid":`delete-keyword-${E}`,danger:!0,icon:t.jsx(At,{}),onClick:()=>Q(E),"aria-label":e("settings.keywordMaskingTab.delete")},"delete")],children:t.jsx(K,{vertical:!0,style:{width:"100%"},gap:8,children:d===E?t.jsxs(t.Fragment,{children:[t.jsx(q,{"data-testid":"keyword-pattern-input",placeholder:e("settings.keywordMaskingTab.patternPlaceholder"),value:g,onChange:I=>c(I.target.value),autoFocus:!0}),t.jsxs(K,{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:b,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:y})]}),t.jsxs(K,{vertical:!0,gap:6,children:[t.jsx(jt,{type:"secondary",children:e("settings.keywordMaskingTab.sampleText")}),t.jsx(q,{placeholder:e("settings.keywordMaskingTab.sampleTextPlaceholder"),value:M,onChange:I=>w(I.target.value)}),t.jsx(jt,{type:"secondary",children:e("settings.keywordMaskingTab.maskedPreview")}),t.jsx(q,{readOnly:!0,value:f.masked,status:f.error?"error":void 0}),f.error&&t.jsx(jt,{type:"danger",children:f.error})]})]}):t.jsxs(K,{justify:"space-between",align:"center",children:[t.jsxs(K,{vertical:!0,gap:4,children:[t.jsx(jt,{strong:!0,children:j.pattern||e("settings.keywordMaskingTab.emptyPattern")}),t.jsxs(K,{gap:8,children:[t.jsx(jt,{type:"secondary",style:{fontSize:12},children:j.match_type==="regex"?e("settings.keywordMaskingTab.regexPattern"):e("settings.keywordMaskingTab.exactMatch")}),!j.enabled&&t.jsx(jt,{type:"warning",style:{fontSize:12},children:e("settings.keywordMaskingTab.disabled")})]})]}),t.jsx(pe,{checked:j.enabled,onChange:I=>N(E,I),size:"small"})]})})})})]})})},{Text:Tn,Paragraph:Cr}=ue,Mr=["Bash(rm -rf *)","Bash(git push *)","Bash(sudo *)","Write(/etc/**)"],Er=()=>{const{t:e}=se(),{message:s}=xt.useApp(),[n,a]=o.useState([]),[r,i]=o.useState(""),[l,d]=o.useState(!1),[u,g]=o.useState(!1),c=o.useCallback(async()=>{try{d(!0),a(await fe.getPermissionAskRules())}catch(y){s.error(e("settings.permissionsTab.loadFailed")),console.error(y)}finally{d(!1)}},[s,e]);o.useEffect(()=>{c()},[c]);const x=o.useCallback(async y=>{try{g(!0);const b=await fe.updatePermissionAskRules(y);return a(b),s.success(e("settings.permissionsTab.saveSuccess")),!0}catch(b){return s.error(b instanceof Error?b.message:e("settings.permissionsTab.saveFailed")),!1}finally{g(!1)}},[s,e]),h=o.useCallback(async y=>{const b=y.trim();if(!b)return;if(n.includes(b)){s.info(e("settings.permissionsTab.duplicate"));return}await x([...n,b])&&i("")},[n,x,s,e]),S=o.useCallback(y=>x(n.filter(b=>b!==y)),[n,x]);return t.jsx(O,{className:"lotus-settings-card",title:e("settings.permissionsTab.title"),extra:t.jsx(z,{type:"primary",icon:t.jsx(yt,{}),loading:u,disabled:!r.trim(),onClick:()=>void h(r),children:e("settings.permissionsTab.add")}),children:t.jsxs(R,{direction:"vertical",style:{width:"100%"},size:"large",children:[t.jsx(Cr,{type:"secondary",style:{marginBottom:0},children:e("settings.permissionsTab.description")}),t.jsx(q,{value:r,onChange:y=>i(y.target.value),onPressEnter:()=>void h(r),placeholder:e("settings.permissionsTab.placeholder"),allowClear:!0}),t.jsxs(K,{gap:8,wrap:"wrap",align:"center",children:[t.jsx(Tn,{type:"secondary",style:{fontSize:12},children:e("settings.permissionsTab.examples")}),Mr.map(y=>t.jsx(re.CheckableTag,{checked:n.includes(y),onChange:()=>{n.includes(y)||h(y)},children:y},y))]}),t.jsx(Je,{loading:l,dataSource:n,locale:{emptyText:e("settings.permissionsTab.empty")},renderItem:y=>t.jsx(Je.Item,{actions:[t.jsx(z,{danger:!0,size:"small",icon:t.jsx(At,{}),loading:u,onClick:()=>void S(y),"aria-label":e("settings.permissionsTab.remove")},"delete")],children:t.jsx(Tn,{code:!0,children:y})})})]})})},{Text:Et,Paragraph:Dr}=ue,Pr=/^[A-Za-z_][A-Za-z0-9_]*$/,Ir=()=>{const{t:e}=se(),{message:s}=xt.useApp(),[n,a]=o.useState([]),[r,i]=o.useState(!1),[l,d]=o.useState(!1),[u,g]=o.useState(null),[c]=_.useForm(),x=o.useCallback(async()=>{i(!0);try{const w=await fe.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 T=await fe.upsertEnvVar(D);a(T.entries),s.success(u?e("settings.envVars.updated","Variable updated"):e("settings.envVars.created","Variable created")),F()}catch(T){s.error((T instanceof Error?T.message:void 0)||e("settings.envVars.saveError","Failed to save variable"))}},S=async w=>{try{const D=await fe.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"))}},y=()=>{g(null),c.resetFields(),c.setFieldsValue({secret:!1}),d(!0)},b=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(re,{color:"warning",icon:t.jsx(hn,{}),children:e("settings.envVars.secret","Secret")}):t.jsx(re,{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(z,{type:"text",size:"small",icon:t.jsx(ks,{}),onClick:()=>b(D),"aria-label":e("settings.envVars.edit","Edit")}),t.jsx(ss,{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(z,{type:"text",size:"small",danger:!0,icon:t.jsx(At,{}),"aria-label":e("settings.envVars.delete","Delete")})})]})}];return t.jsxs("div",{style:{maxWidth:900},children:[t.jsxs(O,{className:"lotus-settings-card",title:e("settings.envVars.title","Environment Variables"),extra:t.jsx(z,{type:"primary",icon:t.jsx(yt,{}),onClick:y,children:e("settings.envVars.addButton","Add Variable")}),children:[t.jsx(Dr,{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(_,{form:c,layout:"vertical",onFinish:h,initialValues:{secret:!1},children:[t.jsx(_.Item,{name:"name",label:e("settings.envVars.name","Name"),rules:[{required:!0,message:e("settings.envVars.nameRequired","Variable name is required")},{pattern:Pr,message:e("settings.envVars.nameInvalid","Must start with a letter or underscore, followed by letters, digits, or underscores")}],children:t.jsx(q,{placeholder:"GITHUB_TOKEN",disabled:u!==null,autoFocus:u===null})}),t.jsx(_.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(q.Password,{placeholder:u?e("settings.envVars.valuePlaceholderEdit","Enter new value or leave empty"):e("settings.envVars.valuePlaceholder","Enter value"),visibilityToggle:!0})}),t.jsx(_.Item,{name:"secret",label:e("settings.envVars.secret","Secret"),valuePropName:"checked",extra:e("settings.envVars.secretHint","Secret variables are encrypted on disk and masked in the UI"),children:t.jsx(pe,{})}),t.jsx(_.Item,{name:"description",label:e("settings.envVars.descriptionField","Description"),children:t.jsx(q,{placeholder:e("settings.envVars.descriptionPlaceholder","Optional description")})})]})})]})},Ct=class Ct{constructor(){}static getInstance(){return Ct.instance||(Ct.instance=new Ct),Ct.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),nr(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(Ct,"instance");let Zs=Ct;const{Text:Os}=ue,{TextArea:Fr}=q,{useToken:Ar}=ye,Rr=e=>!(!e||e.includes("/")||e.includes("\\")||e.includes("..")),zr=()=>{const{t:e}=se(),{token:s}=Ar(),[n,a]=Rt.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),[y,b]=o.useState(""),[F,M]=o.useState(""),[w,D]=o.useState(!1),m=o.useMemo(()=>Zs.getInstance(),[]),T=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(()=>{T()},[T]);const L=o.useCallback(async N=>{S(N),b(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),b(""),M(""),D(!1)},U=o.useCallback(async()=>{if(!Rr(y)){n.error(e("settings.workflowsTab.invalidName"));return}const N=r.some(f=>f.name===y);if(!h&&N){n.error(e("settings.workflowsTab.nameAlreadyExists"));return}x(!0);try{await at.getInstance().saveWorkflow(y,F),n.success(e("settings.workflowsTab.saved")),D(!1);const E=(await T()).find(I=>I.name===y);E&&S(E)}catch(f){n.error(f instanceof Error?f.message:e("settings.workflowsTab.saveFailed"))}finally{x(!1)}},[F,y,T,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 T()}catch(f){n.error(f instanceof Error?f.message:e("settings.workflowsTab.deleteFailed"))}},[T,n,h,e]);return t.jsxs("div",{style:{padding:"24px"},children:[a,t.jsxs(O,{title:e("settings.workflowsTab.title"),extra:t.jsxs(R,{children:[t.jsx(z,{icon:t.jsx(zt,{}),onClick:T,loading:l,children:e("settings.workflowsTab.refresh")}),t.jsx(z,{"data-testid":"create-workflow",icon:t.jsx(yt,{}),onClick:P,children:e("settings.workflowsTab.newWorkflow")}),t.jsx(z,{"data-testid":"save-workflow",type:"primary",icon:t.jsx(_s,{}),onClick:U,loading:c,disabled:!w,children:e("settings.workflowsTab.save")})]}),children:[t.jsx(Os,{type:"secondary",children:e("settings.workflowsTab.description")}),t.jsxs(K,{gap:s.marginLG,style:{marginTop:s.marginLG},children:[t.jsx("div",{style:{width:320,flexShrink:0},children:t.jsx(Je,{loading:l,dataSource:r,locale:{emptyText:e("settings.workflowsTab.empty")},renderItem:N=>t.jsx(Je.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(z,{"data-testid":`delete-workflow-${N.name}`,type:"text",danger:!0,size:"small",icon:t.jsx(At,{}),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(q,{"data-testid":"workflow-name",placeholder:e("settings.workflowsTab.namePlaceholder"),value:y,onChange:N=>{b(N.target.value),D(!0)},disabled:!!h,prefix:t.jsx(ks,{})}),t.jsx(Fr,{"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,ns=2e4,js=1e4,ws=e=>({id:e,enabled:!0,transport:{type:"stdio",command:"",args:[],env:{},startup_timeout_ms:ns},request_timeout_ms:ls,healthcheck_interval_ms:cs,allowed_tools:[],denied_tools:[]}),Or=()=>({status:"stopped",tool_count:0,restart_count:0}),Lr=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},Nr=(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,ns)}},Vr=(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:Nr(a.transport,n.transport)}},$r=e=>{const s=Or(),a=e.runtime??{},r=a.status??e.status;return{status:Lr(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}},Br=e=>{const s=Vr(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:$r(e)}},qr=(e,s)=>`mcp__${e}__${s}`,Ur=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}},Hr=(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"?Ur(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?qr(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 Kr{async getServers(){const s=await Xe.get("mcp/servers");return Array.isArray(s.servers)?s.servers.map(Br):[]}async addServer(s){return Xe.post("mcp/servers",s)}async updateServer(s,n){const a={...n,id:s};return Xe.put(`mcp/servers/${s}`,a)}async deleteServer(s){return Xe.delete(`mcp/servers/${s}`)}async connectServer(s){return Xe.post(`mcp/servers/${s}/connect`)}async disconnectServer(s){return Xe.post(`mcp/servers/${s}/disconnect`)}async refreshTools(s){return Xe.post(`mcp/servers/${s}/refresh`)}async getTools(s){const n=s?`mcp/servers/${s}/tools`:"mcp/tools",a=await Xe.get(n);return(Array.isArray(a.tools)?a.tools:[]).map((i,l)=>Hr(i,s,l)).filter(i=>!!i)}async importServers(s){return Xe.post("mcp/servers/import",s)}}const ta=new Kr,Wr=5e3,tt=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,jn=(e,s)=>`${e}:${s}`,Gr=(e={})=>{const{service:s=ta,autoRefreshMs:n=Wr,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({}),[y,b]=o.useState(!1),[F,M]=o.useState(!1),[w,D]=o.useState(!1),[m,T]=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},[]),U=o.useCallback(async({silent:C=!1}={})=>{C||b(!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}),T(null)}catch(G){throw T(tt(G,"Failed to load MCP servers")),G}finally{C||b(!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})),T(null),X}catch(X){throw T(tt(X,"Failed to load MCP tools")),X}finally{x(X=>({...X,[C]:!1}))}},[s,u]),N=o.useCallback((C,G,X)=>{const te=jn(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 U()}catch(G){throw T(tt(G,"Failed to add MCP server")),G}finally{M(!1)}},[U,s]),j=o.useCallback(async(C,G)=>{M(!0);try{const X={...G,id:C};await s.updateServer(C,X),L.current[C]=X,await U()}catch(X){throw T(tt(X,"Failed to update MCP server")),X}finally{M(!1)}},[U,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 U()}catch(G){throw T(tt(G,"Failed to delete MCP server")),G}finally{N(C,"delete",!1)}},[U,s,N]),I=o.useCallback(async C=>{N(C,"connect",!0);try{await s.connectServer(C),await U({silent:!0})}catch(G){throw T(tt(G,"Failed to connect MCP server")),G}finally{N(C,"connect",!1)}},[U,s,N]),Y=o.useCallback(async C=>{N(C,"disconnect",!0);try{await s.disconnectServer(C),await U({silent:!0})}catch(G){throw T(tt(G,"Failed to disconnect MCP server")),G}finally{N(C,"disconnect",!1)}},[U,s,N]),A=o.useCallback(async C=>{N(C,"refresh",!0);try{await s.refreshTools(C),await Q(C,!0),await U({silent:!0})}catch(G){throw T(tt(G,"Failed to refresh MCP tools")),G}finally{N(C,"refresh",!1)}},[Q,U,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 U(),l&&await Q(l,!0)}catch(C){throw T(tt(C,"Failed to refresh MCP status")),C}finally{D(!1)}},[Q,U,l,r,s]),W=o.useCallback(C=>{d(C)},[]),ne=o.useCallback((C,G)=>!!h[jn(C,G)],[h]),ie=o.useMemo(()=>l?u[l]??[]:[],[l,u]),Ce=o.useMemo(()=>l?!!c[l]:!1,[l,c]);return o.useEffect(()=>{U().catch(()=>{})},[U]),o.useEffect(()=>{if(!a||n<=0)return;const C=window.setInterval(()=>{U({silent:!0}).catch(()=>{})},n);return()=>{window.clearInterval(C)}},[a,n,U]),o.useEffect(()=>{l&&Q(l).catch(()=>{})},[Q,l]),{servers:r,selectedServerId:l,selectedServerTools:ie,isLoadingServers:y,isMutatingConfig:F,isRefreshingAll:w,isSelectedServerToolsLoading:Ce,error:m,setSelectedServerId:W,refreshServers:U,addServer:f,updateServer:j,deleteServer:E,connectServer:I,disconnectServer:Y,refreshServerTools:A,refreshAll:Z,isServerActionLoading:ne}},Jr={[B.Connecting]:"blue",[B.Ready]:"green",[B.Degraded]:"orange",[B.Stopped]:"default",[B.Error]:"red"},Xr=e=>e===B.Connecting||e===B.Ready||e===B.Degraded,Yr=e=>{if(!e)return;const s=e.replace(/\s+/g," ").trim();if(s)return s.length>180?`${s.slice(0,180)}...`:s},Zr=({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}=ye.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:(y,b)=>b.name||b.id},{key:"transport",title:c("settings.mcpServerTable.columns.transportType"),render:(y,b)=>b.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:(y,b)=>{var m,T;const F=((m=b.runtime)==null?void 0:m.status)??B.Stopped,M=Yr((T=b.runtime)==null?void 0:T.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(Te,{title:M?`${w} ${c("settings.mcpTab.statusLastError",{error:M})}`:w,children:t.jsx(re,{color:F===B.Stopped?void 0:Jr[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:(y,b)=>{var F;return((F=b.runtime)==null?void 0:F.tool_count)??0},width:100},{key:"actions",title:c("settings.mcpServerTable.columns.actions"),width:360,render:(y,b)=>{var w;const F=((w=b.runtime)==null?void 0:w.status)??B.Stopped,M=Xr(F);return t.jsxs(R,{size:x.marginXS,children:[t.jsx(z,{size:"small",onClick:D=>{D.stopPropagation(),r==null||r(b)},children:c("settings.mcpServerTable.actions.edit")}),t.jsx(ss,{title:c("settings.mcpServerTable.deleteTitle"),description:c("settings.mcpServerTable.deleteDescription",{name:b.name||b.id}),onConfirm:()=>i==null?void 0:i(b),okText:c("settings.mcpServerTable.actions.delete"),okButtonProps:{danger:!0,loading:g==null?void 0:g(b.id,"delete")},children:t.jsx(z,{size:"small",danger:!0,loading:g==null?void 0:g(b.id,"delete"),onClick:D=>D.stopPropagation(),children:c("settings.mcpServerTable.actions.delete")})}),M?t.jsx(z,{size:"small",onClick:D=>{D.stopPropagation(),d==null||d(b)},loading:g==null?void 0:g(b.id,"disconnect"),children:c("settings.mcpServerTable.actions.disconnect")}):t.jsx(z,{size:"small",type:"primary",ghost:!0,onClick:D=>{D.stopPropagation(),l==null||l(b)},loading:g==null?void 0:g(b.id,"connect"),children:c("settings.mcpServerTable.actions.connect")}),t.jsx(z,{size:"small",onClick:D=>{D.stopPropagation(),u==null||u(b)},loading:g==null?void 0:g(b.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:y=>({onClick:()=>a==null?void 0:a(y.id),style:{cursor:a?"pointer":"default",backgroundColor:n===y.id?x.colorFillSecondary:void 0}})})},{Text:Sn}=ue,{TextArea:Qr}=q,_n=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||[]}},ei=e=>e.reduce((s,n)=>{var r;const a=(r=n.key)==null?void 0:r.trim();return a&&(s[a]=n.value??""),s},{}),ti=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??""}}),kn=(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:ti(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:ei(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??ns:ns};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}},wn=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(y=>{if(!y||typeof y!="object")return null;const b=y,F=typeof b.name=="string"?b.name:"",M=typeof b.value=="string"?b.value:"";return F.trim()?{name:F,value:M}:null}).filter(y=>!!y):x&&typeof x=="object"?Object.entries(x).filter(([y])=>y.trim()).map(([y,b])=>({name:y,value:typeof b=="string"?b:""})):[],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(b=>typeof b=="string"):[],h=a.env,S=h&&typeof h=="object"?Object.entries(h).reduce((b,[F,M])=>(typeof M=="string"&&(b[F]=M),b),{}):{},y=typeof a.startup_timeout_ms=="number"?a.startup_timeout_ms:ns;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:y},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")})}}},si=({open:e,mode:s,initialConfig:n,confirmLoading:a=!1,onCancel:r,onSubmit:i})=>{const{t:l}=se(),[d]=_.useForm(),[u,g]=o.useState("form"),[c,x]=o.useState(""),[h,S]=o.useState(null),y=o.useMemo(()=>_n(n),[n]),b=_.useWatch("transportType",d)??"stdio";o.useEffect(()=>{e&&(d.setFieldsValue(y),x(wn(n)),S(null),g("form"))},[d,y,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(T){console.error("MCP server JSON submission error:",T)}return}try{const m=await d.validateFields(),T=kn(m,s,n);await i(T),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 T=d.getFieldsValue(),L=kn(T,s,n);x(JSON.stringify(L,null,2))}catch{x(wn(n))}else{const T=Ls(c,l);T.valid&&d.setFieldsValue(_n(T.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(Va,{})," ",l("settings.mcpServerForm.modeForm")]}),t.jsxs(It.Button,{value:"json",children:[t.jsx($a,{})," ",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(Qr,{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(_,{layout:"vertical",form:d,preserve:!0,initialValues:y,children:[t.jsx(_.Item,{name:"id",label:l("settings.mcpServerForm.serverId"),rules:[{required:!0,message:l("settings.mcpServerForm.serverIdRequired")},{pattern:/^[a-zA-Z0-9_-]+$/,message:l("settings.mcpServerForm.serverIdPatternError")}],children:t.jsx(q,{placeholder:"filesystem",disabled:s==="edit",autoComplete:"off"})}),t.jsx(_.Item,{name:"name",label:l("settings.mcpServerForm.displayName"),children:t.jsx(q,{placeholder:"Filesystem MCP",autoComplete:"off"})}),t.jsx(_.Item,{name:"enabled",label:l("settings.mcpServerForm.enabled"),valuePropName:"checked",extra:l("settings.mcpServerForm.enabledHelp"),children:t.jsx(pe,{})}),t.jsx(_.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"}]})}),b==="stdio"?t.jsxs(t.Fragment,{children:[t.jsx(_.Item,{name:"command",label:l("settings.mcpServerForm.command"),rules:[{required:!0,message:l("settings.mcpServerForm.commandRequired")}],children:t.jsx(q,{placeholder:"npx",autoComplete:"off"})}),t.jsx(_.Item,{name:"args",label:l("settings.mcpServerForm.arguments"),children:t.jsx(ee,{mode:"tags",tokenSeparators:[","],placeholder:l("settings.mcpServerForm.argumentsPlaceholder"),open:!1})}),t.jsx(_.List,{name:"envEntries",children:(m,{add:T,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(Sn,{strong:!0,children:l("settings.mcpServerForm.envVars")}),t.jsx(z,{icon:t.jsx(yt,{}),onClick:()=>T({key:"",value:""}),type:"dashed",children:l("settings.mcpServerForm.addEnv")})]}),m.map(P=>t.jsxs(R,{align:"baseline",style:{display:"flex"},children:[t.jsx(_.Item,{...P,name:[P.name,"key"],rules:[{required:!0,message:l("settings.mcpServerForm.keyRequired")}],children:t.jsx(q,{placeholder:"MCP_ROOT",autoComplete:"off"})}),t.jsx(_.Item,{...P,name:[P.name,"value"],children:t.jsx(q,{placeholder:"/Users/me/workspace",autoComplete:"off"})}),t.jsx(z,{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(_.Item,{name:"url",label:l("settings.mcpServerForm.sseUrl"),rules:[{required:!0,message:l("settings.mcpServerForm.sseUrlRequired")},{validator:async(m,T)=>{if(T)try{new URL(T)}catch{throw new Error(l("settings.mcpServerForm.validUrlRequired"))}}}],children:t.jsx(q,{placeholder:"http://localhost:4000/sse",autoComplete:"off"})}),t.jsx(_.List,{name:"headerEntries",children:(m,{add:T,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(Sn,{strong:!0,children:l("settings.mcpServerForm.headers")}),t.jsx(z,{icon:t.jsx(yt,{}),onClick:()=>T({name:"",value:""}),type:"dashed",children:l("settings.mcpServerForm.addHeader")})]}),m.map(P=>t.jsxs(R,{align:"baseline",style:{display:"flex"},children:[t.jsx(_.Item,{...P,name:[P.name,"name"],rules:[{required:!0,message:l("settings.mcpServerForm.headerNameRequired")}],children:t.jsx(q,{placeholder:"Authorization",autoComplete:"off"})}),t.jsx(_.Item,{...P,name:[P.name,"value"],children:t.jsx(q,{placeholder:"Bearer token",autoComplete:"off"})}),t.jsx(z,{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),St=(e,s)=>{const n=e[s];return typeof n=="string"?n:void 0},Cn=(e,s)=>{const n=e[s];return typeof n=="boolean"?n:void 0},ni=(e,s)=>{const n=e[s];return Array.isArray(n)?n:void 0},Zt=e=>{if(!bs(e))return"any";const s=e.type;if(typeof s=="string"){if(s==="array"){const i=e.items;return`array<${Zt(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(Zt).join(" | ")||"any";const a=Array.isArray(e.anyOf)?e.anyOf:null;if(a)return a.map(Zt).join(" | ")||"any";const r=Array.isArray(e.allOf)?e.allOf:null;return r&&r.map(Zt).join(" & ")||"any"},ai=e=>{if(!bs(e))return null;const s=e.properties;if(!bs(s))return{schemaUri:St(e,"$schema"),title:St(e,"title"),description:St(e,"description"),additionalProperties:Cn(e,"additionalProperties"),fields:[]};const n=new Set((ni(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:Zt(i),required:n.has(r),description:l?St(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:St(e,"$schema"),title:St(e,"title"),description:St(e,"description"),additionalProperties:Cn(e,"additionalProperties"),fields:a}},{Text:Qe}=ue,ri=e=>e===void 0?"":e===null?"null":typeof e=="string"?e:Xn(e,0),ii=({schema:e})=>{const{token:s}=ye.useToken(),{t:n}=se(),a=o.useMemo(()=>ai(e),[e]);if(!a)return t.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:Xn(e,2)});const r=[{title:n("components.jsonSchema.field"),dataIndex:"name",key:"name",width:180,render:l=>t.jsx(Qe,{code:!0,children:l})},{title:n("components.jsonSchema.type"),dataIndex:"type",key:"type",width:140,render:l=>t.jsx(Qe,{children:l})},{title:n("components.jsonSchema.required"),dataIndex:"required",key:"required",width:110,render:l=>l?t.jsx(Qe,{strong:!0,style:{color:s.colorError},children:n("components.jsonSchema.yes")}):t.jsx(Qe,{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(Qe,{type:"secondary",children:"-"}):t.jsx(Qe,{children:ri(l)})},{title:n("components.jsonSchema.description"),dataIndex:"description",key:"description",render:l=>l?t.jsx(Qe,{style:{whiteSpace:"pre-wrap"},children:l}):t.jsx(Qe,{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(Qe,{code:!0,children:a.schemaUri})}:null,typeof a.additionalProperties=="boolean"?{key:"additionalProperties",label:"additionalProperties",children:t.jsx(Qe,{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:Ut}=ue,oi=(e,s)=>`mcp__${e}__${s}`,li=({server:e,tools:s,loading:n=!1})=>{const{t:a}=se();return t.jsx(O,{title:a("settings.mcpToolList.title"),size:"small",children:e?t.jsx(Je,{loading:n,dataSource:s,locale:{emptyText:a("settings.mcpToolList.empty")},renderItem:r=>{const i=oi(r.server_id,r.original_name);return t.jsx(Je.Item,{children:t.jsxs(R,{direction:"vertical",size:2,style:{width:"100%"},children:[t.jsx(Ut,{strong:!0,children:r.original_name}),t.jsx(Ut,{type:"secondary",children:r.description||a("settings.mcpToolList.noDescription")}),t.jsx(Ut,{code:!0,children:r.alias}),t.jsxs(Ut,{type:"secondary",children:[a("settings.mcpToolList.aliasMapping"),": ",t.jsx(Ut,{code:!0,children:i})]}),r.parameters!==void 0&&t.jsx(Ss,{size:"small",items:[{key:"schema",label:a("settings.mcpToolList.parametersSchema"),children:t.jsx(ii,{schema:r.parameters})}]})]})})}}):t.jsx(Be,{image:Be.PRESENTED_IMAGE_SIMPLE,description:a("settings.mcpToolList.selectServerHint")})})},{Text:Ht}=ue,{useToken:ci}=ye,{TextArea:di}=q,Mn={[B.Connecting]:"processing",[B.Ready]:"success",[B.Degraded]:"warning",[B.Stopped]:"default",[B.Error]:"error"},ui=()=>({[B.Connecting]:0,[B.Ready]:0,[B.Degraded]:0,[B.Stopped]:0,[B.Error]:0}),_t=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,gi=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 y=(a=S.name)==null?void 0:a.trim();y&&(x[y]=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}},mi=()=>{const{t:e}=se(),{token:s}=ci(),[n,a]=Rt.useMessage(),{servers:r,selectedServerId:i,selectedServerTools:l,isLoadingServers:d,isMutatingConfig:u,isRefreshingAll:g,isSelectedServerToolsLoading:c,error:x,setSelectedServerId:h,addServer:S,updateServer:y,deleteServer:b,connectServer:F,disconnectServer:M,refreshServerTools:w,refreshAll:D,isServerActionLoading:m}=Gr(),T=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,U]=o.useState(!1),[Q,N]=o.useState("create"),[f,j]=o.useState(null),[E,I]=o.useState(!1),[Y,A]=o.useState("merge"),[Z,W]=o.useState(""),[ne,ie]=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=ui();let le=0;return r.forEach(he=>{var xe,Le;const Oe=((xe=he.runtime)==null?void 0:xe.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 b(p.id),n.success(e("settings.mcpTab.serverDeleted"))}catch(le){n.error(_t(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(_t(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(_t(le,e("settings.mcpTab.disconnectServerFailed")))}},Ze=async p=>{try{await w(p.id),n.success(e("settings.mcpTab.toolsRefreshedFor",{name:p.name||p.id}))}catch(le){n.error(_t(le,e("settings.mcpTab.refreshToolsFailed")))}},$=async()=>{try{await D(),n.success(e("settings.mcpTab.statusRefreshed"))}catch(p){n.error(_t(p,e("settings.mcpTab.refreshStatusFailed")))}},ve=()=>{j(null),N("create"),U(!0)},Ke=p=>{j(p),N("edit"),U(!0)},Me=async p=>{try{if(Q==="edit"){if(!f){n.error(e("settings.mcpTab.noServerForEditing"));return}await y(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}));U(!1),j(null)}catch(le){n.error(_t(le,e("settings.mcpTab.saveServerFailed")))}},ze=()=>{I(!0),ie(null),A("merge"),W("")},_e=async()=>{const p=gi(r),le=JSON.stringify(p,null,2);try{await tn(le),n.success(e("settings.mcpTab.copiedConfig"))}catch{I(!0),ie(null),A("merge"),W(le),n.warning(e("settings.mcpTab.clipboardUnavailable"))}},We=async()=>{var Oe;ie(null);let p;try{p=JSON.parse(Z)}catch(xe){ie(`${e("settings.mcpTab.invalidJsonPrefix")}: ${xe instanceof Error?xe.message:e("settings.mcpTab.unknownError")}`);return}if(!p||typeof p!="object"){ie(e("settings.mcpTab.jsonMustBeObject"));return}const he=p.mcpServers;if(!he||typeof he!="object"){ie(e("settings.mcpTab.missingMcpServers"));return}C(!0);try{const xe=await ta.importServers({mcpServers:he,mode:Y}),Le=((Oe=xe.start_errors)==null?void 0:Oe.length)??0;n.success(e("settings.mcpTab.importSummary",{count:xe.server_ids.length,added:xe.added,updated:xe.updated,removed:xe.removed,failed:Le})),Le&&n.warning(e("settings.mcpTab.importStartFailures")),I(!1),W(""),await $()}catch(xe){ie(_t(xe,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(O,{size:"small",title:e("settings.mcpTab.overviewTitle"),children:t.jsxs(R,{direction:"vertical",size:s.marginXS,style:{width:"100%"},children:[t.jsx(Ht,{type:"secondary",children:e("settings.mcpTab.overviewDescription")}),t.jsxs(R,{wrap:!0,children:[t.jsx(re,{style:te,children:e("settings.mcpTab.totalServers",{count:X.totalServers})}),t.jsx(re,{style:te,children:e("settings.mcpTab.totalTools",{count:X.totalTools})}),Object.values(B).map(p=>t.jsx(Te,{title:L[p],children:t.jsxs(re,{color:p===B.Stopped?void 0:Mn[p],style:{cursor:"help",...p===B.Stopped?te:void 0},children:[T[p],": ",X.byStatus[p]]})},p))]}),t.jsx(Ht,{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(Ht,{type:"secondary",children:[t.jsx(re,{color:p===B.Stopped?void 0:Mn[p],style:{marginInlineEnd:8,...p===B.Stopped?te:void 0},children:T[p]}),L[p]]},`guide-${p}`))})]})}),t.jsx(O,{size:"small",title:e("settings.mcpTab.serversTitle"),extra:t.jsxs(R,{children:[t.jsx(z,{type:"primary",onClick:ve,children:e("settings.mcpTab.addServer")}),t.jsx(z,{icon:t.jsx(zt,{}),loading:g,onClick:()=>{$()},children:e("settings.mcpTab.refreshAll")}),t.jsx(z,{icon:t.jsx(Yn,{}),onClick:()=>void _e(),children:e("settings.mcpTab.export")}),t.jsx(z,{icon:t.jsx(Ba,{}),onClick:ze,children:e("settings.mcpTab.import")})]}),children:t.jsx(Zr,{servers:r,loading:d,selectedServerId:i,onSelectServer:h,onEditServer:Ke,onDeleteServer:De,onConnectServer:Pe,onDisconnectServer:qe,onRefreshTools:Ze,isServerActionLoading:m})}),t.jsx(li,{server:G,tools:l,loading:c}),t.jsx(si,{open:P,mode:Q,initialConfig:(f==null?void 0:f.config)??null,confirmLoading:u,onCancel:()=>{u||(U(!1),j(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),ie(null))},width:800,destroyOnClose:!1,children:t.jsxs(R,{direction:"vertical",style:{width:"100%"},size:"middle",children:[t.jsxs(Ht,{type:"secondary",children:[e("settings.mcpTab.importHint"),t.jsx("br",{}),t.jsx(Ht,{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(di,{value:Z,onChange:p=>W(p.target.value),rows:14,placeholder:'{"mcpServers": { "filesystem": { "command": "...", "args": [], "env": {} } }}',spellCheck:!1})]})})]})},sa=1,pi=365,na=e=>Number.isFinite(e)?Math.min(pi,Math.max(sa,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},Kt=e=>e.toISOString().slice(0,10),hi=(e,s)=>{const n=new Date(e.getTime());return n.setUTCDate(n.getUTCDate()+s),n},fi=(e,s)=>{const n=s.getTime()-e.getTime(),a=Math.floor(n/864e5)+1;return na(a)},an=(e,s=new Date)=>{const n=na(e.days),a=Kt(s),r=Ns(e.endDate)??Ns(a);if(!r)return{startDate:a,endDate:a,days:sa};const i=Ns(e.startDate);if(i){const d=r<i?i:r;return{startDate:Kt(i),endDate:Kt(d),days:fi(i,d)}}const l=hi(r,-(n-1));return{startDate:Kt(l),endDate:Kt(r),days:n}},yi=15e3,xi=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,bi=(e={})=>{const{filters:s,autoRefreshMs:n=yi}=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,y]=o.useState(!1),[b,F]=o.useState(null),M=o.useCallback(async D=>{D?h(!0):y(!0);try{const m={startDate:r.startDate,endDate:r.endDate,endpoint:a.endpoint,model:a.model,limit:a.limit},[T,L,P]=await Promise.all([Qt.getForwardSummary(m),Qt.getForwardByEndpoint(m),Qt.getForwardRequests(m)]);l(T),u(L),c(P),F(null)}catch(m){F(xi(m,"Failed to load forward metrics"))}finally{D?h(!1):y(!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:b,refresh:w}},vi=15e3,En=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,Ti=(e={})=>{const{filters:s,autoRefreshMs:n=vi,service:a=Qt}=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([]),[y,b]=o.useState(null),[F,M]=o.useState([]),[w,D]=o.useState(null),[m,T]=o.useState(!1),[L,P]=o.useState(!1),[U,Q]=o.useState(!1),[N,f]=o.useState(null),j=o.useCallback(async A=>{A?P(!0):Q(!0);try{const Z=a.getMemorySummary?a.getMemorySummary().catch(()=>null):Promise.resolve(null),W=a.getMemoryTimeline?a.getMemoryTimeline({days:i.days,endDate:i.endDate,granularity:r.granularity}).catch(()=>[]):Promise.resolve([]),[ne,ie,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,W]);d(ne),g(ie),x(Ce),S(C),b(G),M(X),f(null)}catch(Z){f(En(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 j(!1)},[j]),I=o.useCallback(async A=>{T(!0);try{const Z=await a.getSessionDetail(A);D(Z)}catch(Z){f(En(Z,"Failed to load session detail"))}finally{T(!1)}},[a]),Y=o.useCallback(()=>{D(null)},[]);return o.useEffect(()=>{j(!0)},[j]),o.useEffect(()=>{if(n<=0)return;const A=window.setInterval(()=>{j(!1)},n);return()=>{window.clearInterval(A)}},[n,j]),{summary:l,modelMetrics:u,sessions:c,timeline:h,memorySummary:y,memoryTimeline:F,sessionDetail:w,isLoading:L,isRefreshing:U,isSessionDetailLoading:m,error:N,refresh:E,loadSessionDetail:I,clearSessionDetail:Y}},ji=15e3,Si=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,_i=(e={})=>{const{filters:s,autoRefreshMs:n=ji}=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 b=>{b?u(!0):c(!0);try{const F=await Qt.getUsageBreakdown({startDate:r.startDate,endDate:r.endDate,model:a.model});l(F),h(null)}catch(F){h(Si(F,"Failed to load usage breakdown"))}finally{b?u(!1):c(!1)}},[a.model,r.endDate,r.startDate]),y=o.useCallback(async()=>{await S(!1)},[S]);return o.useEffect(()=>{S(!0)},[S]),o.useEffect(()=>{if(n<=0)return;const b=window.setInterval(()=>{S(!1)},n);return()=>{window.clearInterval(b)}},[n,S]),{data:i,isLoading:d,isRefreshing:g,error:x,refresh:y}},{useToken:ki}=ye,wi=({data:e,loading:s})=>{const{t:n}=se(),{token:a}=ki();if(s)return t.jsx(O,{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(O,{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(O,{size:"small",className:"lotus-metric-card",title:n("settings.charts.endpointDistribution"),children:t.jsx("div",{style:{width:"100%",height:240},children:t.jsx(Ot,{children:t.jsxs(sn,{data:r,children:[t.jsx(rs,{strokeDasharray:"3 3"}),t.jsx(is,{dataKey:"endpoint"}),t.jsx(os,{}),t.jsx(Lt,{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$/,""),aa=e=>e.toLocaleString(),ra=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 aa(e)},Ci=e=>Number.isFinite(e)&&Math.abs(e)>=1e3,ia=e=>ra(e),as=e=>{if(!Number.isFinite(e))return String(e);const s=rn(e);return Ci(e)?t.jsx(Te,{title:t.jsx("div",{children:ra(e)}),children:t.jsx("span",{children:s})}):s},it=e=>{const s=Number(e??0);return Number.isFinite(s)?as(s):e==null?"-":String(e)},{useToken:Mi}=ye,Ei=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`},Dn=({summary:e,loading:s})=>{const{t:n}=se(),{token:a}=Mi();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(O,{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(O,{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(O,{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(O,{size:"small",className:"lotus-metric-card",children:t.jsx(Se,{title:n("settings.forwardMetricsCards.avgResponseTime"),value:Ei(e==null?void 0:e.avg_duration_ms),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:kt}=ue,Di=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`},Pi=e=>new Date(e).toLocaleString(),Ii=({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(kt,{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(re,{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(re,{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(qa,{status:l,text:i.status_code?t.jsxs("span",{children:[i.status,t.jsxs(kt,{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(kt,{children:as(i.token_usage.total_tokens)}):t.jsx(kt,{type:"secondary",children:"-"})},{title:n("settings.metricsTable.forward.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",width:100,render:r=>Di(r)},{title:n("settings.metricsTable.forward.columns.started"),dataIndex:"started_at",key:"started_at",width:160,render:r=>t.jsx(kt,{type:"secondary",style:{fontSize:12},children:Pi(r)})},{title:n("settings.metricsTable.forward.columns.error"),dataIndex:"error",key:"error",width:200,render:r=>r?t.jsx(kt,{type:"danger",ellipsis:!0,style:{maxWidth:180},children:r}):t.jsx(kt,{type:"secondary",children:"-"})}];return t.jsx(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:Fi}=ye,Ai=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString()},Pn=({summary:e,loading:s})=>{const{t:n}=se(),{token:a}=Fi();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(O,{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(O,{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(O,{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(O,{size:"small",className:"lotus-metric-card",children:t.jsx(Se,{title:n("settings.unifiedMetricsCards.lastReindex"),value:Ai(e==null?void 0:e.last_reindex_at),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:Ri}=ue,zi=({data:e,loading:s})=>{const{t:n}=se();return s?t.jsx(O,{size:"small",className:"lotus-metric-card",title:n("settings.charts.memoryTrendTitle"),children:t.jsx(dt,{active:!0,paragraph:{rows:5}})}):t.jsx(O,{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(Ri,{type:"secondary",children:n("settings.charts.memoryTrendDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(Ot,{children:t.jsxs(Qn,{data:e,children:[t.jsx(rs,{strokeDasharray:"3 3"}),t.jsx(is,{dataKey:"label",minTickGap:24}),t.jsx(os,{allowDecimals:!1}),t.jsx(Lt,{}),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:Oi}=ye,Li=e=>{const s=Math.floor(e/1e3),n=Math.floor(s/60),a=s%60;return n>0?`${n}m ${a}s`:`${a}s`},Ni=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)},In=({summary:e,sessions:s,loading:n})=>{const{t:a}=se(),{token:r}=Oi();if(n)return t.jsx(dt,{active:!0,paragraph:{rows:1}});const i=Ni(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(O,{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(O,{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(O,{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(O,{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(O,{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(O,{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(O,{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(O,{size:"small",className:"lotus-metric-card",children:t.jsx(Se,{title:a("settings.metricsCards.avgSessionDuration"),value:i>0?Li(i):"-",valueStyle:{color:"var(--lotus-chart-accent)"}})})})]})},{Text:Vi}=ue,Fn=["var(--lotus-chart-primary)","var(--lotus-chart-secondary)","var(--lotus-chart-accent)","var(--lotus-chart-purple)","var(--lotus-chart-cyan)"],$i=({data:e,loading:s})=>{const{t:n}=se();if(s)return t.jsx(O,{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(O,{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(Vi,{type:"secondary",children:n("settings.charts.modelDistributionDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(Ot,{children:t.jsxs(er,{children:[t.jsx(tr,{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(sr,{fill:Fn[i%Fn.length]},`${r.name}-${i}`))}),t.jsx(Lt,{formatter:r=>ia(r)})]})})})]})})},Bi=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?"-":s.toLocaleString()},qi=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`},Ui=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"}},Hi=(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}},Ki=({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(Te,{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(re,{color:Ui(i),children:Hi(i,a)})},{title:a("settings.metricsTable.session.columns.started"),dataIndex:"started_at",key:"started_at",render:i=>Bi(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=>qi(i),width:120},{title:a("settings.metricsTable.session.columns.tokens"),key:"tokens",render:(i,l)=>as(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(z,{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:Wi}=ue,An={message_count:"Message Count",last_message_id:"Last Message",pending_question:"Pending Question"},Gi=e=>An[e]?An[e]:e.split("_").map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "),Ji=({breakdown:e,loading:s})=>{const{t:n}=se();if(s)return t.jsx(O,{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:Gi(r)}),count:i})).sort((r,i)=>i.count-r.count);return t.jsx(O,{size:"small",className:"lotus-metric-card",title:n("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),extra:t.jsx(Wi,{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(Ot,{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(Lt,{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:Xi}=ue,Yi=({data:e,loading:s})=>{const{t:n}=se();return s?t.jsx(O,{size:"small",className:"lotus-metric-card",title:n("settings.charts.tokenUsageOverTime"),children:t.jsx(dt,{active:!0,paragraph:{rows:5}})}):t.jsx(O,{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(Xi,{type:"secondary",children:n("settings.charts.tokenUsageDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(Ot,{children:t.jsxs(Qn,{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(Lt,{formatter:a=>ia(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:Zi}=ue,Wt=({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(O,{size:"small",className:"lotus-metric-card",title:e,children:t.jsx(dt,{active:!0,paragraph:{rows:5}})}):t.jsx(O,{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(Zi,{type:"secondary",children:s}):null,t.jsx("div",{style:{width:"100%",minWidth:0,height:280,marginTop:s?12:0},children:t.jsx(Ot,{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(Lt,{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:Qi}=ye,Rn=({summary:e,loading:s})=>{const{t:n}=se(),{token:a}=Qi();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(O,{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:wt}=ue,{useToken:eo}=ye,zn=e=>"date"in e?e.date:e.label,to=(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`},On=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}: ${aa(a)}`).join(" • ")},Bs=(e,s=320)=>({width:"100%",display:"grid",gridTemplateColumns:`repeat(auto-fit, minmax(${s}px, 1fr))`,gap:e}),so=()=>{const{t:e}=se(),{token:s}=eo(),n=ja(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:y,sessions:b,timeline:F,memorySummary:M,memoryTimeline:w,sessionDetail:D,isLoading:m,isRefreshing:T,isSessionDetailLoading:L,error:P,refresh:U,loadSessionDetail:Q,clearSessionDetail:N}=Ti({filters:{startDate:a,endDate:i,model:d,days:g,granularity:x}}),{summary:f,endpointMetrics:j,requests:E,isLoading:I,isRefreshing:Y,error:A,refresh:Z}=bi({filters:{startDate:a,endDate:i,days:g,model:d}}),{data:W,isLoading:ne,isRefreshing:ie,error:Ce,refresh:C}=_i({filters:{startDate:a,endDate:i,days:g,model:d}}),G=o.useMemo(()=>F.map(p=>({label:zn(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(()=>y.map(p=>({label:p.model,value:p.model})),[y]),te=o.useMemo(()=>{const p=F.map(he=>({label:zn(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)=>as(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,xe=b.reduce((Vt,v)=>Vt+v.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,Nt=(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(Vt=>Vt.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,bt=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:bt,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:Nt},{title:e("settings.metricsDashboard.compactStats.avgRoundsPerSession"),value:p>0?Number((xe/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:y.length},{title:e("settings.metricsDashboard.compactStats.endpointCoverage"),value:j.length}]},[j.length,E,f,y.length,De,b,S,e]),Ze=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,xe=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(xe.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:j.length}]},[j.length,E,f,De,e]),$=o.useMemo(()=>W?[{label:e("settings.metricsDashboard.skillsAndMcp.mix.coreTools",{defaultValue:"Core Tools"}),count:W.core_tool_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.skillLoads",{defaultValue:"Skill Loads"}),count:W.skill_load_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.mcpCalls",{defaultValue:"MCP Calls"}),count:W.mcp_calls}].filter(p=>p.count>0):[],[e,W]),ve=o.useMemo(()=>((W==null?void 0:W.top_skills)??[]).map(p=>({label:p.skill_id,count:p.count})),[W]),Ke=o.useMemo(()=>((W==null?void 0:W.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,W]),Me=o.useMemo(()=>((W==null?void 0:W.top_mcp_tools)??[]).map(p=>({label:p.tool_name,count:p.count,meta:p.server_id})),[W]),ze=o.useMemo(()=>((W==null?void 0:W.top_core_tools)??[]).map(p=>({label:p.name,count:p.count})),[W]),_e=D==null?void 0:D.session,We=T||Y||ie;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(O,{size:"small",title:e("settings.metricsDashboard.filtersTitle"),extra:t.jsx(z,{icon:t.jsx(zt,{}),loading:We,onClick:()=>{U(),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(O,{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(O,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.overviewSections.scaleTitle",{defaultValue:"Scale & Activity"}),extra:t.jsx(wt,{type:"secondary",children:e("settings.metricsDashboard.overviewSections.scaleSubtitle",{defaultValue:"Current usage volume across chat, forward, skills, and memory."})}),children:t.jsxs(R,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(In,{summary:S,sessions:b,loading:m}),t.jsx(Dn,{summary:f,loading:I}),t.jsx(Rn,{summary:W,loading:ne}),t.jsx(Pn,{summary:M,loading:m})]})}),t.jsxs(O,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.overviewSections.efficiencyTitle",{defaultValue:"Compression & Efficiency Advantage"}),extra:t.jsx(wt,{type:"secondary",children:e("settings.metricsDashboard.overviewSections.efficiencySubtitle",{defaultValue:"Real savings from context compression, especially around tool-heavy workflows."})}),children:[t.jsx(Ge,{gutter:[s.marginSM,s.marginSM],children: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(wt,{type:"secondary",style:{display:"block",marginTop:s.marginXS},children:e("settings.metricsDashboard.efficiencyHint",{defaultValue:"这些指标优先使用真实运行统计:总节约 Tokens、工具上下文压缩节约、非工具压缩节约、压缩事件数,以及会话 / Forward 的平均负载与质量指标。"})})]})]})},{key:"chat",label:e("settings.metricsDashboard.tabs.chat",{defaultValue:"Chat"}),children:t.jsxs(R,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(In,{summary:S,sessions:b,loading:m}),t.jsxs("div",{style:Bs(s.marginSM,360),children:[t.jsx(Yi,{data:G,loading:m}),t.jsx($i,{data:y,loading:m})]}),t.jsxs("div",{style:Bs(s.marginSM,360),children:[t.jsx(Ji,{breakdown:S==null?void 0:S.sync_mismatch_breakdown,loading:m}),t.jsx(O,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.activityHeatmapTitle"),children:te.points.length===0?t.jsx(wt,{type:"secondary",children:e("settings.metricsDashboard.noActivity")}):t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(72px, 1fr))",gap:s.marginXS},children:te.points.map(p=>t.jsxs("div",{style:{borderRadius:s.borderRadiusSM,padding:s.paddingXS,background:to(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(Rn,{summary:W,loading:ne}),t.jsxs("div",{style:Bs(s.marginSM,360),children:[t.jsx(Wt,{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(Wt,{title:e("settings.metricsDashboard.skillsAndMcp.topSkillsTitle",{defaultValue:"Top Skills"}),subtitle:e("settings.metricsDashboard.skillsAndMcp.topSkillsSubtitle",{defaultValue:"Counted from load_skill calls during matching sessions."}),emptyText:e("settings.metricsDashboard.skillsAndMcp.noSkills",{defaultValue:"No skills were loaded in this range."}),data:ve,loading:ne,color:"var(--lotus-chart-purple)"}),t.jsx(Wt,{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(Wt,{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(Wt,{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(Dn,{summary:f,loading:I}),t.jsx(O,{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:Ze.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(wi,{data:j,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(Pn,{summary:M,loading:m}),t.jsx(zi,{data:w,loading:m}),t.jsx(O,{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:On(M==null?void 0:M.last_dream_at)}),t.jsx(Ae.Item,{label:e("settings.metricsDashboard.memory.lastReindex",{defaultValue:"Last Reindex"}),children:On(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:b.length}),children:t.jsx(O,{size:"small",extra:t.jsx(wt,{type:"secondary",children:e("settings.metricsDashboard.sessionsHint")}),children:t.jsx(Ki,{sessions:b,loading:m,onSelectSession:p=>{Q(p)}})})},{key:"forward-requests",label:e("settings.metricsDashboard.forwardTabLabel",{count:E.length}),children:t.jsx(O,{size:"small",children:t.jsx(Ii,{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(wt,{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:as(_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(wt,{type:"secondary",children:e("settings.metricsDashboard.noDetail")})})]})},{Text:ps}=ue,{useToken:no}=ye,ao=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"},ro=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},io=()=>{const{t:e}=se(),{token:s}=no(),[n,a]=Rt.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 b=await Fe.getBambooConfig();d(ro(b)),g(ao(b))}catch(b){n.error(b instanceof Error?b.message:e("settings.hooksTab.loadFailed"))}finally{i(!1)}},[n,e]),h=o.useCallback(async(b,F)=>{await Fe.setBambooConfig({hooks:{image_fallback:{enabled:b,mode:F}}})},[]),S=o.useCallback(async b=>{i(!0);try{await h(b,u),n.success(e(b?"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]),y=o.useCallback(async b=>{var F;i(!0);try{await h(l,b),n.success(e("settings.hooksTab.modeUpdated",{mode:((F=c.find(M=>M.value===b))==null?void 0:F.label)??b})),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(K,{vertical:!0,gap:s.marginLG,children:[a,t.jsx(O,{size:"small",loading:r,children:t.jsxs(K,{vertical:!0,gap:s.marginXS,children:[t.jsx(ps,{strong:!0,children:e("settings.hooksTab.title")}),t.jsxs(K,{align:"center",justify:"space-between",children:[t.jsx(ps,{children:e("settings.hooksTab.enableImagePreflight")}),t.jsx(pe,{checked:l,onChange:S})]}),t.jsxs(K,{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:y,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 oa(e){return{type:"interval",every_seconds:e}}function oo(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 Ln(e){switch(e.trigger_type){case"interval":{const s=Number(e.interval_seconds||0);return s<=0?{errorKey:"settings.schedulesTab.validation.intervalRequired"}:{trigger:oa(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}=oo(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 Nn(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 lo(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 co=[{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 uo(e){return(e==null?void 0:e.type)==="interval"?e.every_seconds:null}function go(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 mo(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 po(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 ho(e){var s;return(s=e.state)!=null&&s.next_fire_at?String(e.state.next_fire_at):"-"}function fo(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 yo(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 xo(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(K,{gap:12,wrap:"wrap",children:[t.jsx(_.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(_.Item,{label:n("settings.schedulesTab.form.dailyMinute"),name:s,style:{width:180},children:t.jsx(we,{min:0,max:59,style:{width:"100%"}})})]})}function bo(){const{t:e}=se(),[s,n]=Rt.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),[y]=_.useForm(),[b]=_.useForm(),F=_.useWatch("trigger_type",y),M=_.useWatch("misfire_policy",y),w=_.useWatch("trigger_type",b),D=_.useWatch("misfire_policy",b),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]),T=o.useCallback(async(f,j,E)=>{try{await E()}catch(I){console.error(`[Schedules] ${f}:`,I),s.error(e(j))}},[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")}],U=[{value:"queue_one",label:e("settings.schedulesTab.overlapPolicyOptions.queueOne")},{value:"skip",label:e("settings.schedulesTab.overlapPolicyOptions.skip")},{value:"allow",label:e("settings.schedulesTab.overlapPolicyOptions.allow")}],Q=(f,j)=>t.jsxs(t.Fragment,{children:[t.jsxs(K,{gap:12,wrap:"wrap",children:[t.jsx(_.Item,{label:e("settings.schedulesTab.form.name"),name:"name",rules:[{required:!0,message:e("settings.schedulesTab.validation.nameRequired")}],style:{flex:"1 1 260px"},children:t.jsx(q,{})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.triggerType"),name:"trigger_type",rules:[{required:!0,message:e("settings.schedulesTab.validation.triggerRequired")}],style:{width:220},children:t.jsx(ee,{options:L})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.enabled"),name:"enabled",valuePropName:"checked",style:{width:120},children:t.jsx(pe,{})})]}),f==="interval"?t.jsx(_.Item,{label:e("settings.schedulesTab.form.intervalSeconds"),name:"interval_seconds",rules:[{required:!0,message:e("settings.schedulesTab.validation.intervalRequired")}],style:{width:220},children:t.jsx(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(_.Item,{label:e("settings.schedulesTab.form.weeklyWeekdays"),name:"weekly_weekdays",style:{minWidth:320},children:t.jsx(ee,{mode:"multiple",options:co})}),t.jsx(qs,{hourName:"weekly_hour",minuteName:"weekly_minute"})]}):null,f==="monthly"?t.jsxs(t.Fragment,{children:[t.jsx(_.Item,{label:e("settings.schedulesTab.form.monthlyDays"),name:"monthly_days",style:{minWidth:320},children:t.jsx(q,{placeholder:e("settings.schedulesTab.form.monthlyDaysPlaceholder")})}),t.jsx(qs,{hourName:"monthly_hour",minuteName:"monthly_minute"})]}):null,f==="cron"?t.jsx(_.Item,{label:e("settings.schedulesTab.form.cronExpr"),name:"cron_expr",children:t.jsx(q,{placeholder:e("settings.schedulesTab.form.cronExprPlaceholder")})}):null,t.jsxs(K,{gap:12,wrap:"wrap",children:[t.jsx(_.Item,{label:e("settings.schedulesTab.form.timezone"),name:"timezone",style:{flex:"1 1 240px"},children:t.jsx(q,{placeholder:e("settings.schedulesTab.form.timezonePlaceholder")})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.startAt"),name:"start_at",style:{flex:"1 1 240px"},children:t.jsx(q,{placeholder:e("settings.schedulesTab.form.datetimePlaceholder")})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.endAt"),name:"end_at",style:{flex:"1 1 240px"},children:t.jsx(q,{placeholder:e("settings.schedulesTab.form.datetimePlaceholder")})})]}),t.jsxs(K,{gap:12,wrap:"wrap",children:[t.jsx(_.Item,{label:e("settings.schedulesTab.form.misfirePolicy"),name:"misfire_policy",style:{flex:"1 1 240px"},children:t.jsx(ee,{options:P})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.overlapPolicy"),name:"overlap_policy",style:{flex:"1 1 240px"},children:t.jsx(ee,{options:U})})]}),j==="catch_up_window"?t.jsxs(K,{gap:12,wrap:"wrap",children:[t.jsx(_.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxRuns"),name:"catch_up_window_max_runs",style:{width:220},children:t.jsx(we,{min:1,style:{width:"100%"}})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxLatenessSeconds"),name:"catch_up_window_max_lateness_seconds",style:{width:260},children:t.jsx(we,{min:1,style:{width:"100%"}})})]}):null,t.jsx(_.Item,{label:e("settings.schedulesTab.form.taskMessage"),name:"task_message",children:t.jsx(q.TextArea,{rows:3,placeholder:e("settings.schedulesTab.form.taskMessagePlaceholder")})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.systemPrompt"),name:"system_prompt",children:t.jsx(q.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})}),t.jsxs(K,{gap:12,wrap:"wrap",children:[t.jsx(_.Item,{label:e("settings.schedulesTab.form.model"),name:"model",style:{flex:"1 1 240px"},children:t.jsx(q,{placeholder:e("settings.schedulesTab.form.modelPlaceholder")})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.workspacePath"),name:"workspace_path",style:{flex:"1 1 320px"},children:t.jsx(q,{placeholder:e("settings.schedulesTab.optional")})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.autoExecute"),name:"auto_execute",valuePropName:"checked",style:{width:160},children:t.jsx(pe,{})})]}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.enhancePrompt"),name:"enhance_prompt",children:t.jsx(q.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})})]}),N=o.useMemo(()=>[{title:e("settings.schedulesTab.columns.name"),key:"name",render:(f,j)=>t.jsxs(K,{vertical:!0,gap:6,children:[t.jsx(Ee,{strong:!0,children:j.name}),t.jsxs(K,{gap:6,wrap:"wrap",children:[t.jsx(re,{children:go(j.trigger)}),j.timezone?t.jsx(re,{color:"blue",children:j.timezone}):null,t.jsx(re,{children:mo(j.misfire_policy)}),t.jsx(re,{children:po(j.overlap_policy)})]})]})},{title:e("settings.schedulesTab.columns.status"),key:"status",render:(f,j)=>{const E=yo(j);return t.jsxs(K,{vertical:!0,gap:4,children:[t.jsx(re,{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,j)=>{var E,I,Y,A;return t.jsxs(K,{vertical:!0,gap:2,children:[t.jsx(Ee,{type:"secondary",children:e("settings.schedulesTab.activityLabels.queued",{count:((E=j.state)==null?void 0:E.queued_run_count)??0})}),t.jsx(Ee,{type:"secondary",children:e("settings.schedulesTab.activityLabels.running",{count:((I=j.state)==null?void 0:I.running_run_count)??0})}),t.jsx(Ee,{type:"secondary",children:e("settings.schedulesTab.activityLabels.ok",{count:((Y=j.state)==null?void 0:Y.total_success_count)??0})}),t.jsx(Ee,{type:"secondary",children:e("settings.schedulesTab.activityLabels.fail",{count:((A=j.state)==null?void 0:A.total_failure_count)??0})})]})}},{title:e("settings.schedulesTab.columns.nextRun"),key:"next_run_at",render:(f,j)=>t.jsx(Ee,{type:"secondary",children:ho(j)})},{title:e("settings.schedulesTab.columns.lastRun"),key:"last_run_at",render:(f,j)=>t.jsx(Ee,{type:"secondary",children:fo(j)})},{title:e("settings.schedulesTab.columns.autoExecute"),key:"auto_execute",render:(f,j)=>{var E,I;return t.jsx(Ee,{type:(E=j.run_config)!=null&&E.auto_execute?void 0:"secondary",children:(I=j.run_config)!=null&&I.auto_execute?e("settings.schedulesTab.yes"):e("settings.schedulesTab.no")})}},{title:e("settings.schedulesTab.columns.model"),key:"model",render:(f,j)=>{var E;return t.jsx(Ee,{type:"secondary",children:(E=j.run_config)!=null&&E.model?String(j.run_config.model):"-"})}},{title:e("settings.schedulesTab.columns.enabled"),key:"enabled",render:(f,j)=>t.jsx(pe,{checked:j.enabled,onChange:async E=>{await T("Failed to toggle","settings.schedulesTab.updateFailed",async()=>{await st.patchSchedule(j.id,{enabled:E}),await m()})}})},{title:e("settings.schedulesTab.columns.actions"),key:"actions",render:(f,j)=>{const E=t.jsx(we,{min:1,value:uo(j.trigger)??void 0,disabled:j.trigger.type!=="interval",onChange:async I=>{const Y=typeof I=="number"?I:null;!Y||Y<=0||await T("Failed to patch interval","settings.schedulesTab.updateFailed",async()=>{await st.patchSchedule(j.id,{trigger:oa(Y)}),await m()})}});return t.jsxs(K,{vertical:!0,gap:8,children:[t.jsxs(K,{gap:8,wrap:"wrap",children:[t.jsx(z,{size:"small",onClick:()=>{h({open:!0,schedule:j,saving:!1}),b.setFieldsValue(xo(j))},children:e("settings.schedulesTab.actions.edit")}),t.jsx(z,{size:"small",onClick:async()=>{await T("Failed to run now","settings.schedulesTab.runNowFailed",async()=>{await st.runScheduleNow(j.id),s.success(e("settings.schedulesTab.enqueuedRun")),await m()})},children:e("settings.schedulesTab.actions.runNow")}),t.jsx(z,{size:"small",onClick:async()=>{u(I=>({...I,open:!0,scheduleId:j.id,loading:!0,sessions:[]}));try{const I=await st.listScheduleSessions(j.id);u(Y=>({...Y,open:!0,scheduleId:j.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(z,{size:"small",onClick:async()=>{c(I=>({...I,open:!0,scheduleId:j.id,loading:!0,runs:[]}));try{const I=await st.listScheduleRuns(j.id);c(Y=>({...Y,open:!0,scheduleId:j.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(z,{danger:!0,size:"small",onClick:async()=>{await T("Failed to delete","settings.schedulesTab.deleteFailed",async()=>{await st.deleteSchedule(j.id),s.success(e("settings.schedulesTab.deleted")),await m()})},children:e("settings.schedulesTab.actions.delete")})]}),t.jsxs(K,{gap:8,align:"center",wrap:"wrap",children:[t.jsx(Ee,{type:"secondary",children:e("settings.schedulesTab.columns.intervalSeconds")}),j.trigger.type==="interval"?E:t.jsx(Te,{title:e("settings.schedulesTab.nonIntervalReadOnly"),children:t.jsx("span",{children:E})})]})]})}}],[b,s,m,T,e]);return t.jsxs(K,{vertical:!0,gap:16,children:[n,t.jsx(O,{title:e("settings.schedulesTab.createTitle"),className:"lotus-settings-card",children:t.jsxs(_,{form:y,layout:"vertical",initialValues:{name:e("settings.schedulesTab.defaultName"),trigger_type:"interval",interval_seconds:3600,daily_hour:9,daily_minute:0,weekly_weekdays:["mon"],weekly_hour:9,weekly_minute:0,monthly_days:"1",monthly_hour:9,monthly_minute:0,cron_expr:"",timezone:"",start_at:"",end_at:"",enabled:!1,task_message:"",model:"",auto_execute:!0,misfire_policy:"run_once",overlap_policy:"queue_one",catch_up_window_max_runs:1,catch_up_window_max_lateness_seconds:60},onFinish:async f=>{try{const j=!!f.auto_execute,E=ke(f.task_message),I=ke(f.model);if(j&&!E){s.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:Y,errorKey:A}=Ln(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:Nn(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:j}}),s.success(e("settings.schedulesTab.created")),y.resetFields(),await m()}catch(j){console.error("[Schedules] Failed to create schedule:",j),s.error(e("settings.schedulesTab.createFailed"))}},children:[Q(F,M),t.jsx(z,{type:"primary",htmlType:"submit",children:e("settings.schedulesTab.actions.create")})]})}),t.jsx(O,{title:e("settings.schedulesTab.listTitle"),className:"lotus-settings-card",extra:t.jsx(z,{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(K,{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(K,{justify:"space-between",align:"center",children:[t.jsxs(K,{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(z,{size:"small",onClick:()=>{Sa(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,j)=>t.jsx(re,{color:lo(j.status),children:j.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,j)=>j.started_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.completedAt"),key:"completed_at",render:(f,j)=>j.completed_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.session"),key:"session_id",render:(f,j)=>j.session_id||"-"},{title:e("settings.schedulesTab.runHistory.columns.duration"),key:"execution_duration_ms",render:(f,j)=>j.execution_duration_ms!=null?`${j.execution_duration_ms}ms`:"-"},{title:e("settings.schedulesTab.runHistory.columns.outcome"),key:"outcome_reason",render:(f,j)=>j.outcome_reason||(j.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:()=>b.submit(),forceRender:!0,children:t.jsx(_,{form:b,layout:"vertical",onFinish:async f=>{const j=x.schedule;if(!j)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}=Ln(f);if(!A){s.error(e(Z||"settings.schedulesTab.validation.triggerRequired"));return}h(W=>({...W,saving:!0}));try{await st.patchSchedule(j.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:Nn(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(W){console.error("[Schedules] Failed to patch schedule:",W),s.error(e("settings.schedulesTab.updateFailed")),h(ne=>({...ne,saving:!1}))}},children:Q(w,D)})})]})}const{Text:Gt}=ue,Jt=en.getInstance();function vo(){const{t:e}=se(),{modal:s,message:n}=xt.useApp(),a=He(y=>y.chats),r=He(y=>y.currentSessionId),i=He(y=>y.refreshChats),l=He(y=>y.loadChats),d=He(y=>y.loadChatHistory),[u,g]=o.useState(!0),[c,x]=o.useState(!1),h=o.useMemo(()=>r?a.find(y=>y.id===r)??null:null,[a,r]),S=async y=>{if(!c){x(!0);try{await y()}finally{x(!1)}}};return t.jsxs(K,{vertical:!0,gap:16,children:[t.jsx(O,{size:"small",title:e("settings.sessionsTab.currentSessionTitle"),children:h?t.jsxs(K,{vertical:!0,gap:4,children:[t.jsx(Gt,{strong:!0,ellipsis:!0,children:h.title}),t.jsxs(Gt,{type:"secondary",ellipsis:!0,children:[e("settings.sessionsTab.id"),": ",h.id," ","•"," ",e("settings.sessionsTab.kind"),": ",h.kind]}),t.jsx(K,{gap:8,wrap:"wrap",style:{marginTop:8},children:t.jsx(z,{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 Jt.clearSession(h.id),await d(h.id),await i(),n.success(e("settings.sessionsTab.sessionCleared"))})}})},children:e("settings.sessionsTab.clearMessages")})})]}):t.jsx(Gt,{type:"secondary",children:e("settings.sessionsTab.noActiveSession")})}),t.jsxs(O,{size:"small",title:e("settings.sessionsTab.bulkCleanupTitle"),children:[t.jsxs(K,{align:"center",gap:8,style:{marginBottom:12},children:[t.jsx(Gt,{children:e("settings.sessionsTab.keepPinned")}),t.jsx(pe,{checked:u,onChange:g})]}),t.jsxs(K,{gap:8,wrap:"wrap",children:[t.jsx(z,{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 Jt.cleanupSessions("all",u),await l(),n.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteAll")}),t.jsx(z,{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 Jt.cleanupSessions("empty",u),await l(),n.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteEmpty")}),t.jsx(z,{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 Jt.cleanupSessions("children",u),await l(),n.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteChildren")})]})]}),t.jsxs(O,{size:"small",title:e("settings.sessionsTab.devResetTitle"),children:[t.jsx(Gt,{type:"secondary",children:e("settings.sessionsTab.devResetDescription")}),t.jsx(K,{style:{marginTop:12},children:t.jsx(z,{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 Jt.devResetSessions(),await l(),n.success(e("settings.sessionsTab.devResetDone"))})}})},children:e("settings.sessionsTab.devResetAction")})})]})]})}const la="notifications/preferences";function ca(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 To(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 jo(){const e=await Xe.get(la);return ca(e)}async function So(e){const s=await Xe.put(la,To(e));return ca(s)}const{Text:nt}=ue,{useToken:_o}=ye,ko={enabled:!0,onClarification:!0,onToolApproval:!0,onContextPressure:!0,onSubAgentComplete:!0},wo=()=>{const{t:e}=se(),{token:s}=_o(),{message:n}=xt.useApp(),[a,r]=o.useState(ko),[i,l]=o.useState(!0),d=_a();o.useEffect(()=>{let c=!1;return(async()=>{try{const x=await jo();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),So(S).then(y=>{r(y)}).catch(()=>{r(h),n.error(e("settings.notificationsTab.saveError","Failed to save notification preferences"))})},g=!d||i;return t.jsx(O,{size:"small",className:"lotus-settings-card",children:t.jsxs(K,{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(K,{align:"center",gap:s.marginSM,children:[t.jsx(Ua,{}),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(K,{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(K,{vertical:!0,gap:s.marginSM,style:{opacity:a.enabled?1:.5,pointerEvents:a.enabled?"auto":"none"},children:[t.jsxs(K,{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(K,{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(K,{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(K,{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(K,{align:"center",gap:s.marginSM,children:[t.jsx(Ha,{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:Co}=ue,da=({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(z,{onClick:s,children:g("settings.providerTab.cancel")},"cancel"),t.jsx(z,{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(O,{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(O,{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(z,{icon:i?t.jsx(Xs,{}):t.jsx(Yn,{}),onClick:a,type:i?"default":"primary",children:g(i?"settings.providerTab.copied":"settings.providerTab.copyCode")})]}),t.jsx("div",{style:{marginTop:8},children:t.jsxs(re,{color:d<60?"error":d<180?"warning":"success",children:[t.jsx(Ka,{style:{marginRight:4}}),"Expires in ",Math.floor(d/60),":",(d%60).toString().padStart(2,"0")]})})]})}),t.jsx(Co,{type:"secondary",children:g("settings.providerTab.afterContinueHint")})]})})},Mo=new Set(["id","type","provider_type","label","enabled","api_key_encrypted"]),Vn=e=>e?Object.fromEntries(Object.entries(e).filter(([s])=>!Mo.has(s))):{},{Password:$n}=q,{Text:mt,Paragraph:Us}=ue,Eo=["low","medium","high","xhigh","max"],Xt=(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:Eo.map(n=>t.jsx(ee.Option,{value:n,children:e(`chat.input.reasoning.${n}`)},n))}),Bn=e=>t.jsx(_.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})}),Do=e=>Array.isArray(e)?e.map(s=>typeof s=="string"?s.trim():"").filter(s=>!!s):[],Po=({type:e})=>{const{t:s}=se();if(!e)return null;switch(e){case"openai":return t.jsxs(t.Fragment,{children:[t.jsx(_.Item,{name:"api_key",label:s("settings.providerTab.openaiApiKey"),rules:[{required:!0,message:s("settings.providerTab.openaiApiKeyRequired")}],children:t.jsx(q.Password,{placeholder:s("settings.providerTab.openaiApiKeyPlaceholder","sk-..."),prefix:t.jsx(ft,{})})}),t.jsx(_.Item,{name:"base_url",label:s("settings.providerTab.baseUrlOptional"),extra:s("settings.providerTab.openaiBaseUrlHelp"),children:t.jsx(q,{placeholder:s("settings.providerTab.openaiBaseUrlPlaceholder","https://api.openai.com/v1")})}),t.jsx(_.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Xt(s)}),Bn(s)]});case"anthropic":return t.jsxs(t.Fragment,{children:[t.jsx(_.Item,{name:"api_key",label:s("settings.providerTab.anthropicApiKey"),rules:[{required:!0,message:s("settings.providerTab.anthropicApiKeyRequired")}],children:t.jsx($n,{placeholder:s("settings.providerTab.anthropicApiKeyPlaceholder","sk-ant-..."),prefix:t.jsx(ft,{})})}),t.jsx(_.Item,{name:"base_url",label:s("settings.providerTab.baseUrlOptional"),extra:s("settings.providerTab.anthropicBaseUrlHelp"),children:t.jsx(q,{placeholder:s("settings.providerTab.anthropicBaseUrlPlaceholder","https://api.anthropic.com/v1")})}),t.jsx(_.Item,{name:"max_tokens",label:s("settings.providerTab.maxTokensOptional"),extra:s("settings.providerTab.maxTokensHelp"),children:t.jsx(q,{type:"number",placeholder:s("settings.providerTab.maxTokensPlaceholder","4096"),min:1,max:1e5})}),t.jsx(_.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Xt(s)})]});case"gemini":return t.jsxs(t.Fragment,{children:[t.jsx(_.Item,{name:"api_key",label:s("settings.providerTab.geminiApiKey"),rules:[{required:!0,message:s("settings.providerTab.geminiApiKeyRequired")}],children:t.jsx($n,{placeholder:s("settings.providerTab.geminiApiKeyPlaceholder","AIza..."),prefix:t.jsx(ft,{})})}),t.jsx(_.Item,{name:"base_url",label:s("settings.providerTab.baseUrlOptional"),extra:s("settings.providerTab.geminiBaseUrlHelp"),children:t.jsx(q,{placeholder:s("settings.providerTab.geminiBaseUrlPlaceholder","https://generativelanguage.googleapis.com/v1beta")})}),t.jsx(_.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Xt(s)})]});case"copilot":return t.jsxs(t.Fragment,{children:[t.jsx(_.Item,{name:"headless_auth",label:s("settings.providerTab.headlessAuth"),valuePropName:"checked",extra:s("settings.providerTab.headlessAuthHelp"),children:t.jsx(pe,{})}),t.jsx(_.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Xt(s)}),Bn(s)]});case"bodhi":return t.jsxs(t.Fragment,{children:[t.jsx(_.Item,{name:"api_key",label:s("settings.providerTab.bodhiApiKey"),rules:[{required:!0,message:s("settings.providerTab.apiKeyRequired")}],children:t.jsx(q.Password,{placeholder:s("settings.providerTab.bodhiApiKeyPlaceholder","bhi_sk_..."),prefix:t.jsx(ft,{})})}),t.jsx(_.Item,{name:"base_url",label:s("settings.providerTab.bodhiBaseUrl"),extra:s("settings.providerTab.bodhiBaseUrlExtra"),children:t.jsx(q,{placeholder:s("settings.providerTab.bodhiBaseUrlPlaceholder","http://localhost:8080")})}),t.jsx(_.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(_.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Xt(s)})]});default:return null}},Io=({instances:e,defaultInstanceId:s,onInstancesChanged:n})=>{const{t:a}=se(),{message:r}=xt.useApp(),{token:i}=ye.useToken(),[l]=_.useForm(),[d,u]=o.useState(!1),[g,c]=o.useState(null),[x,h]=o.useState(!1),[S,y]=o.useState(null),[b,F]=o.useState(void 0),[M,w]=o.useState(null),[D,m]=o.useState(!1),[T,L]=o.useState(!1),[P,U]=o.useState(0),[Q,N]=o.useState(!1),[f,j]=o.useState(!1),[E,I]=o.useState("unknown"),[Y,A]=o.useState(!1),Z=o.useCallback($=>({type:$.type,label:$.label,enabled:$.enabled,...Vn($.config)}),[]),W=o.useCallback(()=>{c(null),F(void 0),u(!0)},[]),ne=async()=>{try{j(!0);const $=await fe.startCopilotAuth();w($),m(!0),U($.expires_in)}catch($){r.error(a("settings.providerTab.startCopilotAuthFailed","Failed to start Copilot authentication")),console.error("Failed to start Copilot authentication:",$)}finally{j(!1)}},ie=async()=>{if(M)try{L(!0),await fe.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 fe.getCopilotAuthStatus();I($.authenticated?"authenticated":"not_authenticated")}catch($){console.error("Failed to check Copilot auth status:",$),I("unknown")}finally{A(!1)}},[]);o.useEffect(()=>{d&&b==="copilot"&&C()},[C,d,b]);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(O,{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(re,{color:"success",children:a("settings.providerTab.authenticated","Authenticated")}):E==="not_authenticated"?t.jsx(re,{color:"warning",children:a("settings.providerTab.notAuthenticated","Not Authenticated")}):t.jsx(re,{children:a("settings.providerTab.unknown","Unknown")}),t.jsx(z,{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(z,{type:"primary",icon:t.jsx(Zn,{}),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:ve,label:Ke,enabled:Me,request_overrides_json:ze,..._e}=$,We=Vn(_e);if("responses_only_models"in We&&(We.responses_only_models=Do(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 fe.updateProviderInstance(g.id,p),r.success(a("settings.providerTab.instanceUpdated","Provider instance updated"))}else{const p={type:ve,label:Ke||ht[ve]||ve,enabled:Me??!0,config:We};await fe.createProviderInstance(p),r.success(a("settings.providerTab.instanceCreated","Provider instance created"))}u(!1),await n(),await et.getState().loadProviderInstances()}catch($){(xs($)||$ instanceof Error&&!ea($))&&r.error($.message)}finally{h(!1)}},[g,l,r,n,a]),Pe=o.useCallback(async $=>{try{y($),await fe.deleteProviderInstance($),r.success(a("settings.providerTab.instanceDeleted","Provider instance deleted")),await n(),await et.getState().loadProviderInstances()}catch(ve){r.error(xs(ve)?ve.message:a("settings.providerTab.instanceDeleteFailed","Failed to delete instance"))}finally{y(null)}},[n,r,a]),qe=o.useCallback(async $=>{try{await fe.setDefaultProviderInstance($),r.success(a("settings.providerTab.defaultInstanceSet","Default provider updated")),await n(),await et.getState().loadProviderInstances()}catch(ve){r.error(xs(ve)?ve.message:a("settings.providerTab.defaultInstanceFailed","Failed to set default"))}},[n,r,a]),Ze=o.useCallback(async()=>{await n()},[n]);return o.useEffect(()=>{Ze()},[]),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(z,{type:"dashed",icon:t.jsx(yt,{}),onClick:W,"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 ve=$.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(re,{color:"processing",style:{fontSize:11},children:Ke}),ve&&t.jsxs(re,{color:"gold",style:{fontSize:11},children:[t.jsx(Ga,{})," ",a("settings.providerTab.default","Default")]}),!$.enabled&&t.jsx(re,{color:"default",style:{fontSize:11},children:a("settings.providerTab.disabled","Disabled")})]}),extra:t.jsxs(R,{size:4,onClick:Me=>Me.stopPropagation(),children:[!ve&&t.jsx(Te,{title:a("settings.providerTab.setDefault","Set as default"),children:t.jsx(z,{type:"text",size:"small",icon:t.jsx(Wa,{}),onClick:()=>void qe($.id)})}),t.jsx(z,{type:"text",size:"small",icon:t.jsx(ks,{}),onClick:()=>te($)}),t.jsx(ss,{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(z,{type:"text",size:"small",danger:!0,icon:t.jsx(At,{}),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(O,{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(_,{form:l,layout:"vertical",preserve:!1,children:[t.jsx(_.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(([$,ve])=>t.jsx(ee.Option,{value:$,children:ve},$))})}),t.jsx(_.Item,{name:"label",label:a("settings.providerTab.instanceLabel","Label"),extra:a("settings.providerTab.labelHelp","A display name for this provider instance"),children:t.jsx(q,{placeholder:a("settings.providerTab.labelPlaceholder","My OpenAI Instance")})}),t.jsx(_.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(_.Item,{noStyle:!0,shouldUpdate:!0,children:()=>t.jsx(Po,{form:l,type:b})}),b==="copilot"&&X("middle")]})}),t.jsx(da,{open:D,onCancel:()=>m(!1),onComplete:()=>void ie(),onCopyCode:()=>void Ce(),completingAuth:T,copiedUserCode:Q,deviceCodeInfo:M,timeRemaining:P,token:i})]})},{Password:qn}=q,{Text:Ye,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()))},Fo=(e,s,n)=>{const a=e;a[s]={...a[s]??{},model:n}},Un=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},Hn=(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},Kn=e=>t.jsxs(R,{direction:"vertical",size:4,children:[t.jsxs(Ye,{type:"secondary",children:[e("settings.providerTab.responsesOnlyHelp1")," ",t.jsx(Ye,{code:!0,children:"/responses"}),"."]}),t.jsx(Ye,{type:"secondary",children:e("settings.providerTab.responsesOnlyHelp2")})]}),Ao=["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:Ao.map(n=>t.jsx(ee.Option,{value:n,children:e(`chat.input.reasoning.${n}`)},n))}),Ro=()=>{const{t:e}=se(),{token:s}=ye.useToken(),{message:n}=xt.useApp(),[a]=_.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),[y,b]=o.useState(!1),[F,M]=o.useState(!1),[w,D]=o.useState(null),[m,T]=o.useState(!1),[L,P]=o.useState(!1),[U,Q]=o.useState(0),[N,f]=o.useState(!1),[j,E]=o.useState([]),[I,Y]=o.useState(!1),[A,Z]=o.useState([]),[W,ne]=o.useState(null),[ie,Ce]=o.useState(!1),[C,G]=o.useState([]),[X,te]=o.useState("idle"),[De,Pe]=o.useState(null),qe=o.useCallback((v,k)=>{const J=v.instances??[],V=J.reduce((ce,oe)=>{const Ne={...oe.config};return Ne.request_overrides&&typeof Ne.request_overrides=="object"&&(Ne.request_overrides_json=JSON.stringify(Ne.request_overrides,null,2)),ce[oe.id]=Ne,ce},{});let H=v.defaults?{...v.defaults}:void 0;const me=v.default_provider_instance_id??null,ge=me?J.find(ce=>ce.id===me):void 0,be=typeof(ge==null?void 0:ge.config.model)=="string"?ge.config.model.trim():void 0;!Ks(H==null?void 0:H.chat)&&me&&be&&(H={...H||{},chat:{provider:me,model:be}});const Ie=k?Un(k):void 0,je=Hn(H,me);return Ie&&!(H!=null&&H.memory_background)&&je&&(H={...H||{},memory_background:{provider:je,model:Ie}}),{defaults:H,features:v.features,providers:V}},[]),Ze=o.useCallback((v,k)=>{Z(v.instances??[]),ne(v.default_provider_instance_id??null),Ce(!0),a.setFieldsValue(qe(v,k)),x(!0)},[qe,a]),$=o.useCallback(v=>{if(!(v!=null&&v.trim()))return;const k=A.find(J=>J.id===v);return k?k.label||ht[k.type]:ht[v]||v},[A]),ve=o.useCallback((v,k)=>{const J=new Set;v!=null&&v.trim()&&J.add(v);for(const V of fs){const H=k==null?void 0:k[V];H&&Object.keys(H).length>0&&J.add(V)}return Array.from(J)},[]);o.useEffect(()=>{if(X!=="success")return;const v=setTimeout(()=>{te("idle"),Pe(null)},2e3);return()=>clearTimeout(v)},[X]),o.useEffect(()=>{if(!m||!w){Q(0);return}Q(w.expires_in);const v=setInterval(()=>{Q(k=>k<=1?(clearInterval(v),0):k-1)},1e3);return()=>clearInterval(v)},[m,w]);const Ke=o.useCallback(async()=>{var v;try{i(!0);const[k,J]=await Promise.all([fe.getProviderConfig(),at.getInstance().getBambooConfig().catch(()=>({}))]);let V=k.defaults?{...k.defaults}:void 0;if(!((v=V==null?void 0:V.chat)!=null&&v.model)&&k.provider&&k.providers){const je=k.provider,ce=k.providers[je],oe=ce==null?void 0:ce.model;oe&&(V={...V||{},chat:{provider:je,model:oe}})}const H=Un(J),me=Hn(V,k.provider||null);H&&!(V!=null&&V.memory_background)&&me&&(V={...V||{},memory_background:{provider:me,model:H}});const ge=Ks(V==null?void 0:V.chat)?V:void 0,be={provider:k.provider,defaults:ge,providers:k.providers||{},features:k.features};ot("[Provider]","Loaded provider config:",be);const Ie={...be.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(be.provider),Ce(!1),G(ve(be.provider,Ie)),a.setFieldsValue({...be,providers:Ie,defaults:be.defaults}),x(!0)}catch(k){n.error(e("settings.providerTab.loadConfigFailed")),console.error("Failed to load provider config:",k)}finally{i(!1)}},[a,ve,n,e]),Me=o.useCallback(async()=>{try{const v=await fe.getEnvVars();E(v.entries||[])}catch(v){console.warn("Failed to load env vars for provider overrides:",v)}},[]),ze=o.useCallback(async()=>{try{const[v,k]=await Promise.all([fe.getProviderInstances(),at.getInstance().getBambooConfig().catch(()=>({}))]);if(!Array.isArray(v.instances))throw new Error("Provider instances API returned an invalid payload");Ze(v,k)}catch{}},[Ze]),_e=o.useCallback(async()=>{try{b(!0);const v=await fe.getCopilotAuthStatus();S(v)}catch(v){console.error("Failed to check Copilot auth status:",v),S({authenticated:!1,message:e("settings.providerTab.checkStatusFailed")})}finally{b(!1)}},[e]);o.useEffect(()=>{Me(),et.getState().loadCatalog(),_e(),(async()=>{try{const[v,k]=await Promise.all([fe.getProviderInstances(),at.getInstance().getBambooConfig().catch(()=>({}))]);if(!Array.isArray(v.instances))throw new Error("Provider instances API returned an invalid payload");Ze(v,k)}catch{await Ke()}})()},[Ke,Me,_e,Ze]);const We=async()=>{try{M(!0);const v=await fe.startCopilotAuth();D(v),T(!0)}catch(v){n.error(e("settings.providerTab.startCopilotAuthFailed")),console.error("Failed to start Copilot authentication:",v)}finally{M(!1)}},p=async()=>{if(w)try{P(!0),await fe.completeCopilotAuth({device_code:w.device_code,interval:w.interval||5,expires_in:w.expires_in}),n.success(e("settings.providerTab.copilotAuthSuccess")),T(!1),D(null),await _e()}catch(v){n.error(e("settings.providerTab.completeAuthFailed")),console.error("Authentication completion failed:",v)}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 fe.logoutCopilot(),n.success(e("settings.providerTab.logoutSuccess")),await _e()}catch(v){n.error(e("settings.providerTab.logoutFailed")),console.error("Failed to logout:",v)}finally{M(!1)}},Oe=o.useCallback(async()=>{Y(!0);try{const v=await fe.fetchCatalogModels();await et.getState().loadCatalog();const k=v.fetched.filter(V=>V.models&&V.models.length>0).length;v.fetched.filter(V=>V.error).length>0?n.warning(e("settings.providerTab.fetchModelsPartialSuccess",{success:k,total:v.fetched.length})):n.success(e("settings.providerTab.fetchModelsSuccess",{count:k}))}catch{n.error(e("settings.providerTab.fetchModelsFailed"))}finally{Y(!1)}},[n,e]),xe=v=>xs(v)||v instanceof Error?v.message:e("settings.providerTab.unknownError"),Le=v=>{a.setFields([{name:["provider"],errors:[]},{name:["providers",v,"api_key"],errors:[]},{name:["defaults","chat"],errors:[]}])},ds=v=>{const k=v.trim();return k?k.includes(".")?k.split(".").filter(Boolean):k==="provider"?["provider"]:k==="provider/providers"?["provider"]:null:null},Cs=(v,k)=>{if(!v.length)return;const J=v.map(V=>{const H=ds(V.path);return H?{name:H,errors:[V.message]}:V.message.toLowerCase().includes("api key")?{name:["providers",k,"api_key"],errors:[V.message]}:{name:["provider"],errors:[V.message]}}).filter((V,H,me)=>me.findIndex(ge=>JSON.stringify(ge.name)===JSON.stringify(V.name))===H);J.length&&a.setFields(J)},Ms=async v=>{var J;const k=v.provider||u;Le(k);try{const H=await at.getInstance().validateBambooConfigPatch({provider:v.provider,providers:v.providers||{},defaults:v.defaults,features:{...v.features||{},provider_model_ref:!0}});if(H.valid)return{valid:!0};const me=((J=H.errors)==null?void 0:J.provider)||[];Cs(me,k);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}}},Nt=async(v,k)=>{var J,V;try{i(!0);const H={provider:v.provider,defaults:v.defaults,providers:{...v.providers||{}},features:{...v.features||{},provider_model_ref:!0}},me=(J=H.defaults)==null?void 0:J.chat;if(!Ks(me)){const ce=e("settings.providerTab.selectModelRequired");if(a.setFields([{name:["defaults","chat"],errors:[ce]}]),(k==null?void 0:k.showMessage)!==!1&&n.error(ce),k!=null&&k.throwOnError)throw new Error(ce);return}const ge=H.providers;for(const ce of fs){const oe=ge[ce];if(!oe)continue;const Ne=oe.request_overrides_json;if(typeof Ne!="string")continue;const vt=Ne.trim();if(!vt)delete oe.request_overrides;else try{oe.request_overrides=JSON.parse(vt)}catch($t){const Bt=e("settings.providerTab.invalidRequestOverridesJson",{provider:ce,error:$t.message});if(a.setFields([{name:["providers",ce,"request_overrides_json"],errors:[Bt]}]),(k==null?void 0:k.showMessage)!==!1&&n.error(Bt),k!=null&&k.throwOnError)throw $t;return}delete oe.request_overrides_json}const be={...H.providers||{}},Ie=H.provider,je=(V=H.defaults)==null?void 0:V.chat;if(je!=null&&je.model&&Ie&&Fo(be,Ie,je.model),ie){const ce=at.getInstance(),oe={defaults:H.defaults,features:{...H.features||{},provider_model_ref:!0}};ot("[Provider]","Saving instance-mode config:",oe),await ce.setBambooConfig(oe)}else{const oe={provider:H.provider||u,defaults:H.defaults,providers:be,features:H.features},Ne=await Ms(H);if(!Ne.valid){const vt=Ne.message||e("settings.providerTab.invalidConfig");if((k==null?void 0:k.showMessage)!==!1&&n.error(`${e("settings.providerTab.invalidConfigPrefix")}: ${vt}`),k!=null&&k.throwOnError)throw new Error(vt);return}ot("[Provider]","Saving provider config:",oe),await fe.saveProviderConfig(oe)}(k==null?void 0:k.showMessage)!==!1&&n.success(e("settings.providerTab.saveConfigSuccess"))}catch(H){const me=xe(H);if((k==null?void 0:k.showMessage)!==!1&&n.error(me?`${e("settings.providerTab.saveConfigErrorPrefix")}: ${me}`:e("settings.providerTab.saveConfigFailed")),console.error("Failed to save configuration:",H),k!=null&&k.throwOnError)throw H}finally{i(!1)}},ut=async v=>{var k,J,V,H,me;try{d(!0);const{useProviderStore:ge}=await Ys(async()=>{const{useProviderStore:qt}=await import("./App-CG8bbjSe.js").then(Rs=>Rs.ak);return{useProviderStore:qt}},__vite__mapDeps([4,1,2,3,5,6,7,8]),import.meta.url),{useAppStore:be}=await Ys(async()=>{const{useAppStore:qt}=await import("./App-CG8bbjSe.js").then(Rs=>Rs.al);return{useAppStore:qt}},__vite__mapDeps([4,1,2,3,5,6,7,8]),import.meta.url),Ie=(k=ge.getState().providerConfig.defaults)==null?void 0:k.chat;ie?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=be.getState().currentSessionId,oe=ce&&be.getState().chats.find(qt=>qt.id===ce)||null,Ne=Ie?`${Ie.provider}/${Ie.model}`:null,vt=je?`${je.provider}/${je.model}`:null,$t=(V=oe==null?void 0:oe.config)!=null&&V.model_ref?`${oe.config.model_ref.provider}/${oe.config.model_ref.model}`:null,Bt=((me=(H=oe==null?void 0:oe.config)==null?void 0:H.model)==null?void 0:me.trim())||null;!!(ce&&(oe!=null&&oe.config)&&je&&vt!==Ne&&(!$t||$t===Ne)&&(!Bt||Bt===(Ie==null?void 0:Ie.model)))&&ce&&(oe!=null&&oe.config)&&je&&be.getState().updateSession(ce,{config:{...oe.config,model:je.model,model_ref:je}}),(v==null?void 0:v.showMessage)!==!1&&n.success(e("settings.providerTab.applyConfigSuccess"))}catch(ge){const be=xe(ge);if((v==null?void 0:v.showMessage)!==!1&&n.error(be?`${e("settings.providerTab.applyConfigErrorPrefix")}: ${be}`:e("settings.providerTab.applyConfigFailed")),console.error("Failed to apply configuration:",ge),v!=null&&v.throwOnError)throw ge}finally{d(!1)}},Es=async v=>{try{const k=a.getFieldsValue(!0);await Nt(k,{throwOnError:!0}),await ut({throwOnError:!0})}catch{}},Ds=async(v,k)=>{if(!(v==="chat"&&!k)&&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,[v]:k},await Nt(J,{showMessage:!1,throwOnError:!0}),await ut({showMessage:!1,throwOnError:!0}),te("success"),n.success(e("settings.providerTab.modelUpdated"))}catch(J){const V=xe(J);te("error"),Pe(V),n.error(V?`${e("settings.providerTab.updateModelErrorPrefix")}: ${V}`:e("settings.providerTab.updateModelFailed"))}}},Ps=async(v,k)=>{if(X!=="saving"){te("saving"),Pe(null);try{if(ie){const J=A.find(V=>V.id===v);if(!J)throw new Error(e("settings.providerTab.providerNotConfigured"));await fe.updateProviderInstance(J.id,{config:{reasoning_effort:k??null}}),await ze(),await et.getState().loadProviderInstances()}else{const J=a.getFieldsValue(!0);await Nt(J,{showMessage:!1,throwOnError:!0}),await ut({showMessage:!1,throwOnError:!0})}te("success"),n.success(e("settings.providerTab.reasoningEffortUpdated"))}catch(J){const V=xe(J);te("error"),Pe(V),n.error(V?`${e("settings.providerTab.updateReasoningEffortErrorPrefix")}: ${V}`:e("settings.providerTab.updateReasoningEffortFailed"))}}},us=(v,k)=>{if(!v)return null;const J=$(v)||v,V=a.getFieldValue(["providers",v,"reasoning_effort"]),H=(k==null?void 0:k.emphasis)==="subtle",me=(k==null?void 0:k.label)||e("settings.providerTab.reasoningEffortOptional"),ge=(k==null?void 0:k.helperText)||e("settings.providerTab.reasoningEffortHelp");return t.jsx("div",{style:{marginTop:(k==null?void 0:k.marginTop)??8,width:"100%"},children:t.jsxs(R,{direction:"vertical",size:H?6:4,style:{width:"100%"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,flexWrap:"wrap"},children:[t.jsx(Ye,{strong:!H,type:H?"secondary":void 0,style:H?{fontSize:s.fontSizeSM,lineHeight:1.4}:void 0,children:me}),k!=null&&k.showProviderLabel?t.jsx(Ye,{type:"secondary",style:{fontSize:s.fontSizeSM,lineHeight:1.4},children:J}):null]}),Pt(e,{value:V,disabled:X==="saving",size:(k==null?void 0:k.size)??(H?"small":void 0),style:{width:"100%"},"data-testid":k==null?void 0:k.dataTestId,onChange:be=>{a.setFieldValue(["providers",v,"reasoning_effort"],be),k!=null&&k.autoSave&&Ps(v,be)}}),t.jsx(Ye,{type:"secondary",style:H?{fontSize:s.fontSizeSM,lineHeight:1.5}:void 0,children:ge})]})})},Is=o.useCallback(v=>{const k=a.getFieldValue(["providers",v]);return k?v==="copilot"?(h==null?void 0:h.authenticated)??!1:!!k.api_key:!1},[a,h]),Fs=()=>{const v=J=>{const V=a.getFieldValue(["defaults",J]);return t.jsx(ka,{value:V,dataTestId:`model-preference-${J}-picker`,appearance:"contrast",disabled:X==="saving",onChange:H=>{a.setFieldValue(["defaults",J],H),Ds(J,H)}})},k=(J,V,H)=>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(Ye,{strong:!0,children:V}),v(J),H?t.jsx(Ye,{type:"secondary",children:H}):null]})}),t.jsx("div",{style:{flex:"0 1 320px",minWidth:280},children:t.jsx(_.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(O,{size:"small",title:e("settings.providerTab.modelPreferences"),style:{marginBottom:16},children:[t.jsx(_.Item,{name:["defaults","chat"],noStyle:!0,preserve:!0,children:t.jsx(Dt,{})}),t.jsx(_.Item,{name:["defaults","fast"],noStyle:!0,preserve:!0,children:t.jsx(Dt,{})}),t.jsx(_.Item,{name:["defaults","task_summary"],noStyle:!0,preserve:!0,children:t.jsx(Dt,{})}),t.jsx(_.Item,{name:["defaults","memory_background"],noStyle:!0,preserve:!0,children:t.jsx(Dt,{})}),t.jsx(_.Item,{name:["defaults","sub_agent"],noStyle:!0,preserve:!0,children:t.jsx(Dt,{})}),t.jsx(_.Item,{name:["defaults","vision"],noStyle:!0,preserve:!0,children:t.jsx(Dt,{})}),t.jsxs(R,{direction:"vertical",size:16,style:{width:"100%"},children:[k("chat",e("settings.providerTab.defaultModel")),k("fast",e("settings.providerTab.fastModel"),e("settings.providerTab.fastModelHelp")),k("task_summary",e("settings.providerTab.taskSummaryModel"),e("settings.providerTab.taskSummaryModelHelp")),k("memory_background",e("settings.providerTab.memoryBackgroundModel"),e("settings.providerTab.memoryBackgroundModelHelp")),k("sub_agent",e("settings.providerTab.subAgentModel"),e("settings.providerTab.subAgentModelHelp")),k("vision",e("settings.providerTab.visionModel"),e("settings.providerTab.visionModelHelp"))]})]})},bt=v=>{const k=j.map(V=>V.name);return t.jsx(_.Item,{name:["providers",v,"request_overrides_json"],label:e("settings.providerTab.advancedRequestOverrides"),extra:t.jsxs(R,{direction:"vertical",size:4,children:[t.jsx(Ye,{type:"secondary",children:e("settings.providerTab.advancedRequestOverridesHelp")}),t.jsxs(Ye,{type:"secondary",children:[e("settings.providerTab.envVarInjection")," ",t.jsx(Ye,{code:!0,children:'{ "type": "env_ref", "name": "YOUR_ENV_NAME" }'})]}),k.length>0&&t.jsx(R,{wrap:!0,size:[6,6],children:k.map(V=>t.jsx(re,{children:V},V))})]}),children:t.jsx(q.TextArea,{autoSize:{minRows:8,maxRows:20},placeholder:`{
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-BwN42ilc.js","./vendor-markdown-teEfNS9t.js","./vendor-i18n-Dm-c3D_C.js","./vendor-antd-qu012Od4.js","./App-BE03KO2t.js","./vendor-mermaid-B53piAPW.js","./main-DE4q1A6J.js","./main-B6snAd4S.css","./App-xovo7L2Z.css"])))=>i.map(i=>d[i]);
2
+ var ua=Object.defineProperty;var ga=(e,s,n)=>s in e?ua(e,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[s]=n;var on=(e,s,n)=>ga(e,typeof s!="symbol"?s+"":s,n);import{j as t}from"./vendor-markdown-teEfNS9t.js";import{a as o,u as se,R as ln,i as ae}from"./vendor-i18n-Dm-c3D_C.js";import{J as ma,u as He,b as pa,T as ha,g as fa,U as en,d as et,B as ot,V as ya,W as pt,X as Fe,Y as xa,Z as ba,_ as va,$ as Ta,a0 as Jn,a1 as at,a2 as fe,H as cn,a as Xe,a3 as Xn,G as tn,m as ja,l as Js,q as Sa,a4 as _a,a5 as ht,k as xs,a6 as ka,a7 as wa,a8 as dn,a9 as Ca,aa as un,ab as gn,ac as mn,ad as pn,o as Ma,ae as Ea,A as Da,af as Pa,ag as Ia,ah as Fa,ai as Aa,aj as Ra}from"./App-BE03KO2t.js";import{U as O,o as R,I as $e,j as ue,a6 as q,B as z,t as ye,a1 as _,a0 as ts,aF as vs,aG as ee,aH as pe,aI as we,J as Je,aJ as Ge,aK as de,D as Te,aL as Ue,aM as za,aD as Re,Q as K,aN as Ss,aO as Oa,a3 as ss,a4 as At,al as La,aP as Na,A as xt,aQ as _s,p as ks,a2 as yt,x as re,aR as hn,aS as ct,a5 as lt,at as Rt,$ as zt,n as It,aT as Va,ak as $a,aU as fn,aV as Ae,Y as Be,as as Yn,aW as Ba,aX as dt,aY as Se,y as qa,aZ as yn,a_ as Ua,a$ as Ha,z as Xs,W as Ka,b0 as Wa,b1 as Ga,b2 as Zn,b3 as ft,b4 as xn,b5 as Ja,ae as Xa,az as Ya,b6 as Za}from"./vendor-antd-qu012Od4.js";import{_ as Ys}from"./vendor-mermaid-B53piAPW.js";import{r as Qa}from"./onboardingStorage-BVcEpmTy.js";import"./main-DE4q1A6J.js";import{m as Qt}from"./MetricsService-C_09AaLH.js";import{R as Ot,B as sn,C as rs,X as is,Y as os,T as Lt,L as nn,a as Ts,b as Qn,c as Ft,P as er,d as tr,e as sr}from"./vendor-charts-DgNVhh9m.js";function nr(e){return e instanceof ma}function ar(){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(pa(w=>({chats:w.chats,currentSessionId:w.currentSessionId,currentChat:ha(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(fa(s)),y=o.useMemo(()=>(n==null?void 0:n.messages)||[],[n]),b=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:y,pinnedChats:b,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 rr(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 y=a.find(D=>D.id===n),b=(y==null?void 0:y.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:b,baseSystemPrompt:(y==null?void 0:y.content)||(a.length>0?((w=a.find(D=>D.id==="general_assistant"))==null?void 0:w.content)||a[0].content:""),lastUsedEnhancedPrompt:null,...et.getState().isProviderModelRefEnabled()?{model_ref:et.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(y=>y.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 ir(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 or=()=>{const e=ar(),s=rr(e),n=ya({sessionId:e.currentSessionId,addMessage:e.addMessage,updateSession:e.updateSession}),a=ir(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:lr}=ye,cr=({httpProxy:e,httpsProxy:s,onHttpProxyChange:n,onHttpsProxyChange:a,onReload:r,onSave:i,isLoading:l})=>{const{t:d}=se(),{token:u}=lr(),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),[y,b]=o.useState({username:"",password:""}),[F,M]=o.useState(!1);o.useEffect(()=>{x()},[x]);const w=async()=>{const m=y.username.trim();if(m){M(!0);try{await h({username:m,password:y.password}),b({username:"",password:""})}catch(T){console.error("Failed to apply proxy auth:",T)}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(O,{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(q,{"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(q,{style:{width:"100%"},value:s,onChange:m=>a(m.target.value),placeholder:d("settings.networkCard.proxyPlaceholder"),disabled:l})]}),t.jsx(O,{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(z,{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(q,{placeholder:d("settings.networkCard.username"),value:y.username,onChange:m=>b(T=>({...T,username:m.target.value}))}),t.jsx(q.Password,{placeholder:d("settings.networkCard.password"),value:y.password,onChange:m=>b(T=>({...T,password:m.target.value}))}),t.jsx(z,{type:"primary",onClick:w,loading:F||c,disabled:!y.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(z,{onClick:()=>Promise.resolve(r()).finally(()=>x({force:!0})),disabled:l,children:d("settings.networkCard.reload")}),t.jsx(z,{"data-testid":"save-proxy-settings",type:"primary",onClick:()=>Promise.resolve(i()).finally(()=>x({force:!0})),disabled:l,children:d("settings.networkCard.save")})]})]})})};function ea(e){return typeof e=="object"&&e!==null&&"errorFields"in e}const{Text:dr}=ue,{useToken:ur}=ye,gr=({msgApi:e})=>{const{t:s}=se(),{token:n}=ur(),[a]=_.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),y=u&&!c,b=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(ea(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(O,{size:"small",className:"lotus-settings-card",title:t.jsx(dr,{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:b}),h?t.jsx($e,{type:"error",showIcon:!0,message:h}):null,t.jsxs(_,{form:a,layout:"vertical",disabled:r||l,children:[y?t.jsx(_.Item,{label:s("settings.configTab.accessPassword.currentPasswordLabel"),name:"currentPassword",rules:[{required:!0,message:s("settings.configTab.accessPassword.validation.currentPasswordRequired")}],children:t.jsx(q.Password,{autoComplete:"current-password"})}):null,t.jsx(_.Item,{label: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(q.Password,{autoComplete:"new-password"})}),t.jsx(_.Item,{label:s("settings.configTab.accessPassword.confirmPasswordLabel"),name:"confirmPassword",dependencies:["newPassword"],rules:[{required:!0,message:s("settings.configTab.accessPassword.validation.confirmPasswordRequired")},({getFieldValue:w})=>({validator(D,m){return!m||w("newPassword")===m?Promise.resolve():Promise.reject(new Error(s("settings.configTab.accessPassword.validation.passwordMismatch")))}})],children:t.jsx(q.Password,{autoComplete:"new-password"})}),t.jsx(z,{type:"primary",loading:l,onClick:()=>void M(),children:s(u?"settings.configTab.accessPassword.updateAction":"settings.configTab.accessPassword.enableAction")})]})]})})},{Text:Ve}=ue,{useToken:mr}=ye,bn="http://127.0.0.1:9562/v1",Yt=e=>[...new Set(e.map(s=>s.trim()).filter(s=>s.length>0))].sort(),pr=e=>{var n;const s=(n=e.tools)==null?void 0:n.disabled;return Array.isArray(s)?Yt(s.filter(a=>typeof a=="string")):[]},hr=({msgApi:e,locale:s,onLocaleChange:n})=>{const{t:a}=se(),{token:r}=mr(),[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,y]=o.useState([]),[b,F]=o.useState(!1),[M,w]=o.useState(!1),D=o.useCallback(async()=>{var A,Z;F(!0);try{const[W,ne]=await Promise.all([Fe.getBambooConfig(),Fe.getBambooTools()]);l({http_proxy:W.http_proxy||"",https_proxy:W.https_proxy||"",memory:{auto_dream_enabled:((A=W.memory)==null?void 0:A.auto_dream_enabled)??!1},subagents:{max_concurrent:(Z=W.subagents)==null?void 0:Z.max_concurrent}});const ie=pr(W);h(ie),y(ie),c(Yt(ne.tools||[]))}catch(W){console.error("Failed to load config:",W),e.error(a("settings.configTab.loadConfigFailed"))}finally{F(!1)}},[e,a]);o.useEffect(()=>{D()},[D]);const m=A=>{l(Z=>({...Z,http_proxy:A}))},T=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}}))},U=async A=>{var Z,W;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 ie=await Fe.validateBambooConfigPatch(ne);if(!ie.valid){const C=((W=(Z=ie.errors)==null?void 0:Z.proxy)==null?void 0:W[0])??Object.values(ie.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 ie=ne instanceof Error&&ne.message.trim()?ne.message:a("settings.configTab.saveConfigFailed");e.error(ie)}finally{F(!1)}},Q=async()=>{e.success(a("settings.configTab.backendSaved"))},N=()=>{u(bn),e.success(a("settings.configTab.backendResetDefault"))},f=(A,Z)=>{h(W=>{const ne=new Set(W);return Z?ne.delete(A):ne.add(A),Yt([...ne])})},j=async()=>{w(!0);try{const A=await Fe.getBambooTools();c(Yt(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=Yt(x);await Fe.setBambooConfig({tools:{disabled:A}}),h(A),y(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(ts,{spinning:b,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(cr,{httpProxy:i.http_proxy,httpsProxy:i.https_proxy,onHttpProxyChange:m,onHttpsProxyChange:T,onReload:D,onSave:()=>U("network"),isLoading:b}),t.jsx(O,{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(O,{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(z,{"data-testid":"save-memory-settings",type:"primary",onClick:()=>U("memory"),loading:b,children:a("settings.configTab.save")})})]})}),t.jsx(O,{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(z,{"data-testid":"save-subagent-settings",type:"primary",onClick:()=>U("subagents"),loading:b,children:a("settings.configTab.save")})})]})}),t.jsx(O,{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(q,{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(z,{"data-testid":"reset-to-defaults",onClick:N,children:a("settings.configTab.resetToDefault")}),t.jsx(z,{"data-testid":"save-api-settings",type:"primary",onClick:Q,children:a("settings.configTab.save")})]})]})}),t.jsx(gr,{msgApi:e})]})},{key:"tools",label:a("settings.configTab.tabs.tools"),children:t.jsx(O,{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(Je,{bordered:!0,dataSource:g,renderItem:A=>t.jsx(Je.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(z,{onClick:j,loading:M,children:a("settings.configTab.reloadTools")}),t.jsx(z,{type:"primary",onClick:E,loading:M,disabled:!I,children:a("settings.configTab.save")})]})]})})}]})})},{Title:fr,Text:zs}=ue,{useToken:yr}=ye,xr=()=>{const{t:e}=se(),{token:s}=yr(),n=xa(),a=ba(),r=va(),[i]=_.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(fr,{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(_,{form:i,layout:"vertical",initialValues:n,onValuesChange:d,children:[t.jsxs(O,{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(_.Item,{name:"theme",label:t.jsxs(R,{children:[e("settings.mermaidTab.themeLabel"),t.jsx(Te,{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(O,{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(_.Item,{name:"fontSize",label:t.jsxs(R,{children:[e("settings.mermaidTab.fontSizeLabel"),t.jsx(Te,{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(_.Item,{name:"defaultScale",label:t.jsxs(R,{children:[e("settings.mermaidTab.defaultZoomLabel"),t.jsx(Te,{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(_.Item,{name:"useMaxWidth",label:t.jsxs(R,{children:[e("settings.mermaidTab.responsiveWidthLabel"),t.jsx(Te,{title:e("settings.mermaidTab.responsiveWidthTooltip"),children:t.jsx(Ue,{style:{color:s.colorTextSecondary}})})]}),valuePropName:"checked",children:t.jsx(pe,{})})]}),t.jsx(O,{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(_.Item,{name:"flowchartNodeSpacing",label:t.jsxs(R,{children:[e("settings.mermaidTab.flowchartNodeSpacingLabel"),t.jsx(Te,{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(_.Item,{name:"flowchartRankSpacing",label:t.jsxs(R,{children:[e("settings.mermaidTab.flowchartRankSpacingLabel"),t.jsx(Te,{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(_.Item,{name:"flowchartCurve",label:t.jsxs(R,{children:[e("settings.mermaidTab.flowchartCurveTypeLabel"),t.jsx(Te,{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(O,{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(_.Item,{name:"sequenceActorMargin",label:t.jsxs(R,{children:[e("settings.mermaidTab.sequenceActorMarginLabel"),t.jsx(Te,{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(_.Item,{name:"sequenceMessageMargin",label:t.jsxs(R,{children:[e("settings.mermaidTab.sequenceMessageMarginLabel"),t.jsx(Te,{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(_.Item,{name:"sequenceWidth",label:t.jsxs(R,{children:[e("settings.mermaidTab.sequenceActorWidthLabel"),t.jsx(Te,{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(_.Item,{name:"sequenceHeight",label:t.jsxs(R,{children:[e("settings.mermaidTab.sequenceActorHeightLabel"),t.jsx(Te,{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(O,{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(_.Item,{name:"ganttBarHeight",label:t.jsxs(R,{children:[e("settings.mermaidTab.ganttBarHeightLabel"),t.jsx(Te,{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(_.Item,{name:"ganttTopPadding",label:t.jsxs(R,{children:[e("settings.mermaidTab.ganttTopPaddingLabel"),t.jsx(Te,{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(z,{icon:t.jsx(za,{}),onClick:u,children:e("settings.mermaidTab.resetToDefaults")})}),t.jsx(Re,{}),t.jsx(O,{title:e("settings.mermaidTab.previewTitle"),styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsx(zs,{type:"secondary",children:e("settings.mermaidTab.previewDescription")})})]})]})},br=o.lazy(()=>Ys(()=>import("./index-BwN42ilc.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8]),import.meta.url)),{Text:Tt}=ue,{useToken:vr}=ye,Tr=({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}=vr(),h=x.marginLG;return t.jsxs(K,{vertical:!0,gap:h,children:[t.jsx(O,{size:"small",className:"lotus-settings-card",children:t.jsx(o.Suspense,{fallback:t.jsx(ts,{size:"small"}),children:t.jsx(br,{})})}),t.jsx(O,{size:"small",className:"lotus-settings-card",children:t.jsxs(R,{direction:"vertical",size:x.marginXS,style:{width:"100%"},children:[t.jsx(Tt,{strong:!0,children:c("settings.promptsTab.title")}),t.jsxs(K,{align:"center",gap:x.marginSM,children:[t.jsx(Tt,{strong:!0,children:c("settings.promptsTab.mermaidEnhancement")}),t.jsx(pe,{checked:n,onChange:l})]}),t.jsxs(K,{align:"center",gap:x.marginSM,children:[t.jsx(Tt,{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(K,{align:"center",gap:x.marginSM,children:[t.jsx(Tt,{strong:!0,children:c("settings.promptsTab.copilotConclusionWithOptionsBeforeFinish")}),t.jsx(pe,{checked:i,onChange:u})]}),t.jsx(Tt,{type:"secondary",style:{fontSize:x.fontSizeSM},children:c("settings.promptsTab.copilotConclusionWithOptionsBeforeFinishDescription",{defaultValue:Ta()})})]}),t.jsx(q.TextArea,{rows:6,placeholder:c("settings.promptsTab.enhancementPlaceholder"),value:e,onChange:S=>s(S.target.value)}),t.jsx(K,{justify:"flex-end",children:t.jsx(z,{type:"primary",onClick:g,children:c("settings.promptsTab.saveEnhancement")})}),t.jsx(Tt,{type:"secondary",style:{fontSize:x.fontSizeSM},children:c("settings.promptsTab.description")})]})}),n&&t.jsx(Ss,{size:"small",items:[{key:"mermaid",label:t.jsx(Tt,{strong:!0,children:c("settings.mermaidTab.title")}),children:t.jsx(xr,{})}]})]})},{Text:gt}=ue,{useToken:jr}=ye,Sr=({themeMode:e,onThemeModeChange:s,vdiSafeMode:n,onVdiSafeModeToggle:a,onClearLocalStorage:r,onResetApp:i,isResetting:l,darkModeKey:d})=>{const{t:u}=se(),{token:g}=jr();return t.jsx(O,{size:"small",className:"lotus-settings-card",children:t.jsxs(R,{direction:"vertical",size:g.marginSM,style:{width:"100%"},children:[t.jsxs(K,{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",Jn]})]}),t.jsx(gt,{type:"secondary",style:{fontSize:g.fontSizeSM},children:u("settings.appTab.runningVersionDesc","This is the currently running Lotus frontend version.")}),t.jsxs(K,{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(K,{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(z,{block:!0,icon:t.jsx(Oa,{}),onClick:()=>{Qa(),window.location.reload()},children:u("settings.appTab.resetStepReplayGuide")}),t.jsx(ss,{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(z,{danger:!0,block:!0,icon:t.jsx(At,{}),children:u("settings.appTab.clearLocalStorageButton")})}),t.jsx(Re,{style:{margin:`${g.marginSM}px 0`}}),t.jsxs(K,{align:"center",gap:g.marginSM,children:[t.jsx(La,{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(ss,{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(z,{"data-testid":"reset-to-defaults",danger:!0,block:!0,type:"primary",icon:t.jsx(Na,{}),loading:l,children:u("settings.appTab.resetButton")})})]})})},{Text:jt}=ue,{useToken:_r}=ye,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,}"}],kr=(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")}}},wr=()=>{const{t:e}=se(),{message:s}=xt.useApp(),{token:n}=_r(),[a,r]=o.useState([]),[i,l]=o.useState(!1),[d,u]=o.useState(null),[g,c]=o.useState(""),[x,h]=o.useState("exact"),[S,y]=o.useState(!0),[b,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(j){s.error(e("settings.keywordMaskingTab.loadFailed")),console.error(j)}finally{l(!1)}},[s,e]);o.useEffect(()=>{D()},[D]);const m=async j=>{try{const E=at.getInstance(),I=await E.validateKeywordEntries(j);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(j);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}},T=async()=>{const j={pattern:"",match_type:"exact",enabled:!0},E=[...a,j];r(E),u(E.length-1),c(""),h("exact"),y(!0),F(void 0)},L=j=>{const E=a[j];u(j),c(E.pattern),h(E.match_type),y(E.enabled),F(void 0)},P=async()=>{if(d===null)return;if(!g.trim()){s.error(e("settings.keywordMaskingTab.patternRequired"));return}const j=[...a];j[d]={pattern:g.trim(),match_type:x,enabled:S},await m(j)&&u(null)},U=()=>{var j;d!==null&&!((j=a[d])!=null&&j.pattern)&&r(a.filter((E,I)=>I!==d)),u(null)},Q=async j=>{const E=a.filter((I,Y)=>Y!==j);await m(E)},N=async(j,E)=>{const I=[...a];I[j]={...I[j],enabled:E},await m(I)},f=kr(M,g,x);return t.jsx(O,{className:"lotus-settings-card",title:e("settings.keywordMaskingTab.title"),extra:t.jsx(z,{"data-testid":"add-keyword",type:"primary",icon:t.jsx(yt,{}),onClick:T,loading:i,children:e("settings.keywordMaskingTab.addKeyword")}),children:t.jsxs(R,{direction:"vertical",style:{width:"100%"},size:"large",children:[t.jsx(jt,{type:"secondary",children:e("settings.keywordMaskingTab.description")}),t.jsx(Je,{loading:i,dataSource:a,locale:{emptyText:e("settings.keywordMaskingTab.empty")},renderItem:(j,E)=>t.jsx(Je.Item,{style:{backgroundColor:n.colorFillAlter,marginBottom:8,borderRadius:n.borderRadius,padding:12},actions:d===E?[t.jsx(z,{"data-testid":"save-keyword",type:"primary",icon:t.jsx(_s,{}),onClick:P,"aria-label":e("settings.keywordMaskingTab.save")},"save"),t.jsx(z,{onClick:U,children:e("settings.keywordMaskingTab.cancel")},"cancel")]:[t.jsx(z,{icon:t.jsx(ks,{}),onClick:()=>L(E),"aria-label":e("settings.keywordMaskingTab.edit")},"edit"),t.jsx(z,{"data-testid":`delete-keyword-${E}`,danger:!0,icon:t.jsx(At,{}),onClick:()=>Q(E),"aria-label":e("settings.keywordMaskingTab.delete")},"delete")],children:t.jsx(K,{vertical:!0,style:{width:"100%"},gap:8,children:d===E?t.jsxs(t.Fragment,{children:[t.jsx(q,{"data-testid":"keyword-pattern-input",placeholder:e("settings.keywordMaskingTab.patternPlaceholder"),value:g,onChange:I=>c(I.target.value),autoFocus:!0}),t.jsxs(K,{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:b,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:y})]}),t.jsxs(K,{vertical:!0,gap:6,children:[t.jsx(jt,{type:"secondary",children:e("settings.keywordMaskingTab.sampleText")}),t.jsx(q,{placeholder:e("settings.keywordMaskingTab.sampleTextPlaceholder"),value:M,onChange:I=>w(I.target.value)}),t.jsx(jt,{type:"secondary",children:e("settings.keywordMaskingTab.maskedPreview")}),t.jsx(q,{readOnly:!0,value:f.masked,status:f.error?"error":void 0}),f.error&&t.jsx(jt,{type:"danger",children:f.error})]})]}):t.jsxs(K,{justify:"space-between",align:"center",children:[t.jsxs(K,{vertical:!0,gap:4,children:[t.jsx(jt,{strong:!0,children:j.pattern||e("settings.keywordMaskingTab.emptyPattern")}),t.jsxs(K,{gap:8,children:[t.jsx(jt,{type:"secondary",style:{fontSize:12},children:j.match_type==="regex"?e("settings.keywordMaskingTab.regexPattern"):e("settings.keywordMaskingTab.exactMatch")}),!j.enabled&&t.jsx(jt,{type:"warning",style:{fontSize:12},children:e("settings.keywordMaskingTab.disabled")})]})]}),t.jsx(pe,{checked:j.enabled,onChange:I=>N(E,I),size:"small"})]})})})})]})})},{Text:Tn,Paragraph:Cr}=ue,Mr=["Bash(rm -rf *)","Bash(git push *)","Bash(sudo *)","Write(/etc/**)"],Er=()=>{const{t:e}=se(),{message:s}=xt.useApp(),[n,a]=o.useState([]),[r,i]=o.useState(""),[l,d]=o.useState(!1),[u,g]=o.useState(!1),c=o.useCallback(async()=>{try{d(!0),a(await fe.getPermissionAskRules())}catch(y){s.error(e("settings.permissionsTab.loadFailed")),console.error(y)}finally{d(!1)}},[s,e]);o.useEffect(()=>{c()},[c]);const x=o.useCallback(async y=>{try{g(!0);const b=await fe.updatePermissionAskRules(y);return a(b),s.success(e("settings.permissionsTab.saveSuccess")),!0}catch(b){return s.error(b instanceof Error?b.message:e("settings.permissionsTab.saveFailed")),!1}finally{g(!1)}},[s,e]),h=o.useCallback(async y=>{const b=y.trim();if(!b)return;if(n.includes(b)){s.info(e("settings.permissionsTab.duplicate"));return}await x([...n,b])&&i("")},[n,x,s,e]),S=o.useCallback(y=>x(n.filter(b=>b!==y)),[n,x]);return t.jsx(O,{className:"lotus-settings-card",title:e("settings.permissionsTab.title"),extra:t.jsx(z,{type:"primary",icon:t.jsx(yt,{}),loading:u,disabled:!r.trim(),onClick:()=>void h(r),children:e("settings.permissionsTab.add")}),children:t.jsxs(R,{direction:"vertical",style:{width:"100%"},size:"large",children:[t.jsx(Cr,{type:"secondary",style:{marginBottom:0},children:e("settings.permissionsTab.description")}),t.jsx(q,{value:r,onChange:y=>i(y.target.value),onPressEnter:()=>void h(r),placeholder:e("settings.permissionsTab.placeholder"),allowClear:!0}),t.jsxs(K,{gap:8,wrap:"wrap",align:"center",children:[t.jsx(Tn,{type:"secondary",style:{fontSize:12},children:e("settings.permissionsTab.examples")}),Mr.map(y=>t.jsx(re.CheckableTag,{checked:n.includes(y),onChange:()=>{n.includes(y)||h(y)},children:y},y))]}),t.jsx(Je,{loading:l,dataSource:n,locale:{emptyText:e("settings.permissionsTab.empty")},renderItem:y=>t.jsx(Je.Item,{actions:[t.jsx(z,{danger:!0,size:"small",icon:t.jsx(At,{}),loading:u,onClick:()=>void S(y),"aria-label":e("settings.permissionsTab.remove")},"delete")],children:t.jsx(Tn,{code:!0,children:y})})})]})})},{Text:Et,Paragraph:Dr}=ue,Pr=/^[A-Za-z_][A-Za-z0-9_]*$/,Ir=()=>{const{t:e}=se(),{message:s}=xt.useApp(),[n,a]=o.useState([]),[r,i]=o.useState(!1),[l,d]=o.useState(!1),[u,g]=o.useState(null),[c]=_.useForm(),x=o.useCallback(async()=>{i(!0);try{const w=await fe.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 T=await fe.upsertEnvVar(D);a(T.entries),s.success(u?e("settings.envVars.updated","Variable updated"):e("settings.envVars.created","Variable created")),F()}catch(T){s.error((T instanceof Error?T.message:void 0)||e("settings.envVars.saveError","Failed to save variable"))}},S=async w=>{try{const D=await fe.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"))}},y=()=>{g(null),c.resetFields(),c.setFieldsValue({secret:!1}),d(!0)},b=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(re,{color:"warning",icon:t.jsx(hn,{}),children:e("settings.envVars.secret","Secret")}):t.jsx(re,{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(z,{type:"text",size:"small",icon:t.jsx(ks,{}),onClick:()=>b(D),"aria-label":e("settings.envVars.edit","Edit")}),t.jsx(ss,{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(z,{type:"text",size:"small",danger:!0,icon:t.jsx(At,{}),"aria-label":e("settings.envVars.delete","Delete")})})]})}];return t.jsxs("div",{style:{maxWidth:900},children:[t.jsxs(O,{className:"lotus-settings-card",title:e("settings.envVars.title","Environment Variables"),extra:t.jsx(z,{type:"primary",icon:t.jsx(yt,{}),onClick:y,children:e("settings.envVars.addButton","Add Variable")}),children:[t.jsx(Dr,{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(_,{form:c,layout:"vertical",onFinish:h,initialValues:{secret:!1},children:[t.jsx(_.Item,{name:"name",label:e("settings.envVars.name","Name"),rules:[{required:!0,message:e("settings.envVars.nameRequired","Variable name is required")},{pattern:Pr,message:e("settings.envVars.nameInvalid","Must start with a letter or underscore, followed by letters, digits, or underscores")}],children:t.jsx(q,{placeholder:"GITHUB_TOKEN",disabled:u!==null,autoFocus:u===null})}),t.jsx(_.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(q.Password,{placeholder:u?e("settings.envVars.valuePlaceholderEdit","Enter new value or leave empty"):e("settings.envVars.valuePlaceholder","Enter value"),visibilityToggle:!0})}),t.jsx(_.Item,{name:"secret",label:e("settings.envVars.secret","Secret"),valuePropName:"checked",extra:e("settings.envVars.secretHint","Secret variables are encrypted on disk and masked in the UI"),children:t.jsx(pe,{})}),t.jsx(_.Item,{name:"description",label:e("settings.envVars.descriptionField","Description"),children:t.jsx(q,{placeholder:e("settings.envVars.descriptionPlaceholder","Optional description")})})]})})]})},Ct=class Ct{constructor(){}static getInstance(){return Ct.instance||(Ct.instance=new Ct),Ct.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),nr(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(Ct,"instance");let Zs=Ct;const{Text:Os}=ue,{TextArea:Fr}=q,{useToken:Ar}=ye,Rr=e=>!(!e||e.includes("/")||e.includes("\\")||e.includes("..")),zr=()=>{const{t:e}=se(),{token:s}=Ar(),[n,a]=Rt.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),[y,b]=o.useState(""),[F,M]=o.useState(""),[w,D]=o.useState(!1),m=o.useMemo(()=>Zs.getInstance(),[]),T=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(()=>{T()},[T]);const L=o.useCallback(async N=>{S(N),b(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),b(""),M(""),D(!1)},U=o.useCallback(async()=>{if(!Rr(y)){n.error(e("settings.workflowsTab.invalidName"));return}const N=r.some(f=>f.name===y);if(!h&&N){n.error(e("settings.workflowsTab.nameAlreadyExists"));return}x(!0);try{await at.getInstance().saveWorkflow(y,F),n.success(e("settings.workflowsTab.saved")),D(!1);const E=(await T()).find(I=>I.name===y);E&&S(E)}catch(f){n.error(f instanceof Error?f.message:e("settings.workflowsTab.saveFailed"))}finally{x(!1)}},[F,y,T,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 T()}catch(f){n.error(f instanceof Error?f.message:e("settings.workflowsTab.deleteFailed"))}},[T,n,h,e]);return t.jsxs("div",{style:{padding:"24px"},children:[a,t.jsxs(O,{title:e("settings.workflowsTab.title"),extra:t.jsxs(R,{children:[t.jsx(z,{icon:t.jsx(zt,{}),onClick:T,loading:l,children:e("settings.workflowsTab.refresh")}),t.jsx(z,{"data-testid":"create-workflow",icon:t.jsx(yt,{}),onClick:P,children:e("settings.workflowsTab.newWorkflow")}),t.jsx(z,{"data-testid":"save-workflow",type:"primary",icon:t.jsx(_s,{}),onClick:U,loading:c,disabled:!w,children:e("settings.workflowsTab.save")})]}),children:[t.jsx(Os,{type:"secondary",children:e("settings.workflowsTab.description")}),t.jsxs(K,{gap:s.marginLG,style:{marginTop:s.marginLG},children:[t.jsx("div",{style:{width:320,flexShrink:0},children:t.jsx(Je,{loading:l,dataSource:r,locale:{emptyText:e("settings.workflowsTab.empty")},renderItem:N=>t.jsx(Je.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(z,{"data-testid":`delete-workflow-${N.name}`,type:"text",danger:!0,size:"small",icon:t.jsx(At,{}),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(q,{"data-testid":"workflow-name",placeholder:e("settings.workflowsTab.namePlaceholder"),value:y,onChange:N=>{b(N.target.value),D(!0)},disabled:!!h,prefix:t.jsx(ks,{})}),t.jsx(Fr,{"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,ns=2e4,js=1e4,ws=e=>({id:e,enabled:!0,transport:{type:"stdio",command:"",args:[],env:{},startup_timeout_ms:ns},request_timeout_ms:ls,healthcheck_interval_ms:cs,allowed_tools:[],denied_tools:[]}),Or=()=>({status:"stopped",tool_count:0,restart_count:0}),Lr=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},Nr=(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,ns)}},Vr=(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:Nr(a.transport,n.transport)}},$r=e=>{const s=Or(),a=e.runtime??{},r=a.status??e.status;return{status:Lr(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}},Br=e=>{const s=Vr(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:$r(e)}},qr=(e,s)=>`mcp__${e}__${s}`,Ur=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}},Hr=(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"?Ur(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?qr(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 Kr{async getServers(){const s=await Xe.get("mcp/servers");return Array.isArray(s.servers)?s.servers.map(Br):[]}async addServer(s){return Xe.post("mcp/servers",s)}async updateServer(s,n){const a={...n,id:s};return Xe.put(`mcp/servers/${s}`,a)}async deleteServer(s){return Xe.delete(`mcp/servers/${s}`)}async connectServer(s){return Xe.post(`mcp/servers/${s}/connect`)}async disconnectServer(s){return Xe.post(`mcp/servers/${s}/disconnect`)}async refreshTools(s){return Xe.post(`mcp/servers/${s}/refresh`)}async getTools(s){const n=s?`mcp/servers/${s}/tools`:"mcp/tools",a=await Xe.get(n);return(Array.isArray(a.tools)?a.tools:[]).map((i,l)=>Hr(i,s,l)).filter(i=>!!i)}async importServers(s){return Xe.post("mcp/servers/import",s)}}const ta=new Kr,Wr=5e3,tt=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,jn=(e,s)=>`${e}:${s}`,Gr=(e={})=>{const{service:s=ta,autoRefreshMs:n=Wr,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({}),[y,b]=o.useState(!1),[F,M]=o.useState(!1),[w,D]=o.useState(!1),[m,T]=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},[]),U=o.useCallback(async({silent:C=!1}={})=>{C||b(!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}),T(null)}catch(G){throw T(tt(G,"Failed to load MCP servers")),G}finally{C||b(!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})),T(null),X}catch(X){throw T(tt(X,"Failed to load MCP tools")),X}finally{x(X=>({...X,[C]:!1}))}},[s,u]),N=o.useCallback((C,G,X)=>{const te=jn(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 U()}catch(G){throw T(tt(G,"Failed to add MCP server")),G}finally{M(!1)}},[U,s]),j=o.useCallback(async(C,G)=>{M(!0);try{const X={...G,id:C};await s.updateServer(C,X),L.current[C]=X,await U()}catch(X){throw T(tt(X,"Failed to update MCP server")),X}finally{M(!1)}},[U,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 U()}catch(G){throw T(tt(G,"Failed to delete MCP server")),G}finally{N(C,"delete",!1)}},[U,s,N]),I=o.useCallback(async C=>{N(C,"connect",!0);try{await s.connectServer(C),await U({silent:!0})}catch(G){throw T(tt(G,"Failed to connect MCP server")),G}finally{N(C,"connect",!1)}},[U,s,N]),Y=o.useCallback(async C=>{N(C,"disconnect",!0);try{await s.disconnectServer(C),await U({silent:!0})}catch(G){throw T(tt(G,"Failed to disconnect MCP server")),G}finally{N(C,"disconnect",!1)}},[U,s,N]),A=o.useCallback(async C=>{N(C,"refresh",!0);try{await s.refreshTools(C),await Q(C,!0),await U({silent:!0})}catch(G){throw T(tt(G,"Failed to refresh MCP tools")),G}finally{N(C,"refresh",!1)}},[Q,U,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 U(),l&&await Q(l,!0)}catch(C){throw T(tt(C,"Failed to refresh MCP status")),C}finally{D(!1)}},[Q,U,l,r,s]),W=o.useCallback(C=>{d(C)},[]),ne=o.useCallback((C,G)=>!!h[jn(C,G)],[h]),ie=o.useMemo(()=>l?u[l]??[]:[],[l,u]),Ce=o.useMemo(()=>l?!!c[l]:!1,[l,c]);return o.useEffect(()=>{U().catch(()=>{})},[U]),o.useEffect(()=>{if(!a||n<=0)return;const C=window.setInterval(()=>{U({silent:!0}).catch(()=>{})},n);return()=>{window.clearInterval(C)}},[a,n,U]),o.useEffect(()=>{l&&Q(l).catch(()=>{})},[Q,l]),{servers:r,selectedServerId:l,selectedServerTools:ie,isLoadingServers:y,isMutatingConfig:F,isRefreshingAll:w,isSelectedServerToolsLoading:Ce,error:m,setSelectedServerId:W,refreshServers:U,addServer:f,updateServer:j,deleteServer:E,connectServer:I,disconnectServer:Y,refreshServerTools:A,refreshAll:Z,isServerActionLoading:ne}},Jr={[B.Connecting]:"blue",[B.Ready]:"green",[B.Degraded]:"orange",[B.Stopped]:"default",[B.Error]:"red"},Xr=e=>e===B.Connecting||e===B.Ready||e===B.Degraded,Yr=e=>{if(!e)return;const s=e.replace(/\s+/g," ").trim();if(s)return s.length>180?`${s.slice(0,180)}...`:s},Zr=({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}=ye.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:(y,b)=>b.name||b.id},{key:"transport",title:c("settings.mcpServerTable.columns.transportType"),render:(y,b)=>b.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:(y,b)=>{var m,T;const F=((m=b.runtime)==null?void 0:m.status)??B.Stopped,M=Yr((T=b.runtime)==null?void 0:T.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(Te,{title:M?`${w} ${c("settings.mcpTab.statusLastError",{error:M})}`:w,children:t.jsx(re,{color:F===B.Stopped?void 0:Jr[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:(y,b)=>{var F;return((F=b.runtime)==null?void 0:F.tool_count)??0},width:100},{key:"actions",title:c("settings.mcpServerTable.columns.actions"),width:360,render:(y,b)=>{var w;const F=((w=b.runtime)==null?void 0:w.status)??B.Stopped,M=Xr(F);return t.jsxs(R,{size:x.marginXS,children:[t.jsx(z,{size:"small",onClick:D=>{D.stopPropagation(),r==null||r(b)},children:c("settings.mcpServerTable.actions.edit")}),t.jsx(ss,{title:c("settings.mcpServerTable.deleteTitle"),description:c("settings.mcpServerTable.deleteDescription",{name:b.name||b.id}),onConfirm:()=>i==null?void 0:i(b),okText:c("settings.mcpServerTable.actions.delete"),okButtonProps:{danger:!0,loading:g==null?void 0:g(b.id,"delete")},children:t.jsx(z,{size:"small",danger:!0,loading:g==null?void 0:g(b.id,"delete"),onClick:D=>D.stopPropagation(),children:c("settings.mcpServerTable.actions.delete")})}),M?t.jsx(z,{size:"small",onClick:D=>{D.stopPropagation(),d==null||d(b)},loading:g==null?void 0:g(b.id,"disconnect"),children:c("settings.mcpServerTable.actions.disconnect")}):t.jsx(z,{size:"small",type:"primary",ghost:!0,onClick:D=>{D.stopPropagation(),l==null||l(b)},loading:g==null?void 0:g(b.id,"connect"),children:c("settings.mcpServerTable.actions.connect")}),t.jsx(z,{size:"small",onClick:D=>{D.stopPropagation(),u==null||u(b)},loading:g==null?void 0:g(b.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:y=>({onClick:()=>a==null?void 0:a(y.id),style:{cursor:a?"pointer":"default",backgroundColor:n===y.id?x.colorFillSecondary:void 0}})})},{Text:Sn}=ue,{TextArea:Qr}=q,_n=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||[]}},ei=e=>e.reduce((s,n)=>{var r;const a=(r=n.key)==null?void 0:r.trim();return a&&(s[a]=n.value??""),s},{}),ti=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??""}}),kn=(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:ti(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:ei(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??ns:ns};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}},wn=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(y=>{if(!y||typeof y!="object")return null;const b=y,F=typeof b.name=="string"?b.name:"",M=typeof b.value=="string"?b.value:"";return F.trim()?{name:F,value:M}:null}).filter(y=>!!y):x&&typeof x=="object"?Object.entries(x).filter(([y])=>y.trim()).map(([y,b])=>({name:y,value:typeof b=="string"?b:""})):[],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(b=>typeof b=="string"):[],h=a.env,S=h&&typeof h=="object"?Object.entries(h).reduce((b,[F,M])=>(typeof M=="string"&&(b[F]=M),b),{}):{},y=typeof a.startup_timeout_ms=="number"?a.startup_timeout_ms:ns;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:y},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")})}}},si=({open:e,mode:s,initialConfig:n,confirmLoading:a=!1,onCancel:r,onSubmit:i})=>{const{t:l}=se(),[d]=_.useForm(),[u,g]=o.useState("form"),[c,x]=o.useState(""),[h,S]=o.useState(null),y=o.useMemo(()=>_n(n),[n]),b=_.useWatch("transportType",d)??"stdio";o.useEffect(()=>{e&&(d.setFieldsValue(y),x(wn(n)),S(null),g("form"))},[d,y,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(T){console.error("MCP server JSON submission error:",T)}return}try{const m=await d.validateFields(),T=kn(m,s,n);await i(T),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 T=d.getFieldsValue(),L=kn(T,s,n);x(JSON.stringify(L,null,2))}catch{x(wn(n))}else{const T=Ls(c,l);T.valid&&d.setFieldsValue(_n(T.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(Va,{})," ",l("settings.mcpServerForm.modeForm")]}),t.jsxs(It.Button,{value:"json",children:[t.jsx($a,{})," ",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(Qr,{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(_,{layout:"vertical",form:d,preserve:!0,initialValues:y,children:[t.jsx(_.Item,{name:"id",label:l("settings.mcpServerForm.serverId"),rules:[{required:!0,message:l("settings.mcpServerForm.serverIdRequired")},{pattern:/^[a-zA-Z0-9_-]+$/,message:l("settings.mcpServerForm.serverIdPatternError")}],children:t.jsx(q,{placeholder:"filesystem",disabled:s==="edit",autoComplete:"off"})}),t.jsx(_.Item,{name:"name",label:l("settings.mcpServerForm.displayName"),children:t.jsx(q,{placeholder:"Filesystem MCP",autoComplete:"off"})}),t.jsx(_.Item,{name:"enabled",label:l("settings.mcpServerForm.enabled"),valuePropName:"checked",extra:l("settings.mcpServerForm.enabledHelp"),children:t.jsx(pe,{})}),t.jsx(_.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"}]})}),b==="stdio"?t.jsxs(t.Fragment,{children:[t.jsx(_.Item,{name:"command",label:l("settings.mcpServerForm.command"),rules:[{required:!0,message:l("settings.mcpServerForm.commandRequired")}],children:t.jsx(q,{placeholder:"npx",autoComplete:"off"})}),t.jsx(_.Item,{name:"args",label:l("settings.mcpServerForm.arguments"),children:t.jsx(ee,{mode:"tags",tokenSeparators:[","],placeholder:l("settings.mcpServerForm.argumentsPlaceholder"),open:!1})}),t.jsx(_.List,{name:"envEntries",children:(m,{add:T,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(Sn,{strong:!0,children:l("settings.mcpServerForm.envVars")}),t.jsx(z,{icon:t.jsx(yt,{}),onClick:()=>T({key:"",value:""}),type:"dashed",children:l("settings.mcpServerForm.addEnv")})]}),m.map(P=>t.jsxs(R,{align:"baseline",style:{display:"flex"},children:[t.jsx(_.Item,{...P,name:[P.name,"key"],rules:[{required:!0,message:l("settings.mcpServerForm.keyRequired")}],children:t.jsx(q,{placeholder:"MCP_ROOT",autoComplete:"off"})}),t.jsx(_.Item,{...P,name:[P.name,"value"],children:t.jsx(q,{placeholder:"/Users/me/workspace",autoComplete:"off"})}),t.jsx(z,{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(_.Item,{name:"url",label:l("settings.mcpServerForm.sseUrl"),rules:[{required:!0,message:l("settings.mcpServerForm.sseUrlRequired")},{validator:async(m,T)=>{if(T)try{new URL(T)}catch{throw new Error(l("settings.mcpServerForm.validUrlRequired"))}}}],children:t.jsx(q,{placeholder:"http://localhost:4000/sse",autoComplete:"off"})}),t.jsx(_.List,{name:"headerEntries",children:(m,{add:T,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(Sn,{strong:!0,children:l("settings.mcpServerForm.headers")}),t.jsx(z,{icon:t.jsx(yt,{}),onClick:()=>T({name:"",value:""}),type:"dashed",children:l("settings.mcpServerForm.addHeader")})]}),m.map(P=>t.jsxs(R,{align:"baseline",style:{display:"flex"},children:[t.jsx(_.Item,{...P,name:[P.name,"name"],rules:[{required:!0,message:l("settings.mcpServerForm.headerNameRequired")}],children:t.jsx(q,{placeholder:"Authorization",autoComplete:"off"})}),t.jsx(_.Item,{...P,name:[P.name,"value"],children:t.jsx(q,{placeholder:"Bearer token",autoComplete:"off"})}),t.jsx(z,{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),St=(e,s)=>{const n=e[s];return typeof n=="string"?n:void 0},Cn=(e,s)=>{const n=e[s];return typeof n=="boolean"?n:void 0},ni=(e,s)=>{const n=e[s];return Array.isArray(n)?n:void 0},Zt=e=>{if(!bs(e))return"any";const s=e.type;if(typeof s=="string"){if(s==="array"){const i=e.items;return`array<${Zt(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(Zt).join(" | ")||"any";const a=Array.isArray(e.anyOf)?e.anyOf:null;if(a)return a.map(Zt).join(" | ")||"any";const r=Array.isArray(e.allOf)?e.allOf:null;return r&&r.map(Zt).join(" & ")||"any"},ai=e=>{if(!bs(e))return null;const s=e.properties;if(!bs(s))return{schemaUri:St(e,"$schema"),title:St(e,"title"),description:St(e,"description"),additionalProperties:Cn(e,"additionalProperties"),fields:[]};const n=new Set((ni(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:Zt(i),required:n.has(r),description:l?St(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:St(e,"$schema"),title:St(e,"title"),description:St(e,"description"),additionalProperties:Cn(e,"additionalProperties"),fields:a}},{Text:Qe}=ue,ri=e=>e===void 0?"":e===null?"null":typeof e=="string"?e:Xn(e,0),ii=({schema:e})=>{const{token:s}=ye.useToken(),{t:n}=se(),a=o.useMemo(()=>ai(e),[e]);if(!a)return t.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:Xn(e,2)});const r=[{title:n("components.jsonSchema.field"),dataIndex:"name",key:"name",width:180,render:l=>t.jsx(Qe,{code:!0,children:l})},{title:n("components.jsonSchema.type"),dataIndex:"type",key:"type",width:140,render:l=>t.jsx(Qe,{children:l})},{title:n("components.jsonSchema.required"),dataIndex:"required",key:"required",width:110,render:l=>l?t.jsx(Qe,{strong:!0,style:{color:s.colorError},children:n("components.jsonSchema.yes")}):t.jsx(Qe,{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(Qe,{type:"secondary",children:"-"}):t.jsx(Qe,{children:ri(l)})},{title:n("components.jsonSchema.description"),dataIndex:"description",key:"description",render:l=>l?t.jsx(Qe,{style:{whiteSpace:"pre-wrap"},children:l}):t.jsx(Qe,{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(Qe,{code:!0,children:a.schemaUri})}:null,typeof a.additionalProperties=="boolean"?{key:"additionalProperties",label:"additionalProperties",children:t.jsx(Qe,{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:Ut}=ue,oi=(e,s)=>`mcp__${e}__${s}`,li=({server:e,tools:s,loading:n=!1})=>{const{t:a}=se();return t.jsx(O,{title:a("settings.mcpToolList.title"),size:"small",children:e?t.jsx(Je,{loading:n,dataSource:s,locale:{emptyText:a("settings.mcpToolList.empty")},renderItem:r=>{const i=oi(r.server_id,r.original_name);return t.jsx(Je.Item,{children:t.jsxs(R,{direction:"vertical",size:2,style:{width:"100%"},children:[t.jsx(Ut,{strong:!0,children:r.original_name}),t.jsx(Ut,{type:"secondary",children:r.description||a("settings.mcpToolList.noDescription")}),t.jsx(Ut,{code:!0,children:r.alias}),t.jsxs(Ut,{type:"secondary",children:[a("settings.mcpToolList.aliasMapping"),": ",t.jsx(Ut,{code:!0,children:i})]}),r.parameters!==void 0&&t.jsx(Ss,{size:"small",items:[{key:"schema",label:a("settings.mcpToolList.parametersSchema"),children:t.jsx(ii,{schema:r.parameters})}]})]})})}}):t.jsx(Be,{image:Be.PRESENTED_IMAGE_SIMPLE,description:a("settings.mcpToolList.selectServerHint")})})},{Text:Ht}=ue,{useToken:ci}=ye,{TextArea:di}=q,Mn={[B.Connecting]:"processing",[B.Ready]:"success",[B.Degraded]:"warning",[B.Stopped]:"default",[B.Error]:"error"},ui=()=>({[B.Connecting]:0,[B.Ready]:0,[B.Degraded]:0,[B.Stopped]:0,[B.Error]:0}),_t=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,gi=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 y=(a=S.name)==null?void 0:a.trim();y&&(x[y]=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}},mi=()=>{const{t:e}=se(),{token:s}=ci(),[n,a]=Rt.useMessage(),{servers:r,selectedServerId:i,selectedServerTools:l,isLoadingServers:d,isMutatingConfig:u,isRefreshingAll:g,isSelectedServerToolsLoading:c,error:x,setSelectedServerId:h,addServer:S,updateServer:y,deleteServer:b,connectServer:F,disconnectServer:M,refreshServerTools:w,refreshAll:D,isServerActionLoading:m}=Gr(),T=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,U]=o.useState(!1),[Q,N]=o.useState("create"),[f,j]=o.useState(null),[E,I]=o.useState(!1),[Y,A]=o.useState("merge"),[Z,W]=o.useState(""),[ne,ie]=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=ui();let le=0;return r.forEach(he=>{var xe,Le;const Oe=((xe=he.runtime)==null?void 0:xe.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 b(p.id),n.success(e("settings.mcpTab.serverDeleted"))}catch(le){n.error(_t(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(_t(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(_t(le,e("settings.mcpTab.disconnectServerFailed")))}},Ze=async p=>{try{await w(p.id),n.success(e("settings.mcpTab.toolsRefreshedFor",{name:p.name||p.id}))}catch(le){n.error(_t(le,e("settings.mcpTab.refreshToolsFailed")))}},$=async()=>{try{await D(),n.success(e("settings.mcpTab.statusRefreshed"))}catch(p){n.error(_t(p,e("settings.mcpTab.refreshStatusFailed")))}},ve=()=>{j(null),N("create"),U(!0)},Ke=p=>{j(p),N("edit"),U(!0)},Me=async p=>{try{if(Q==="edit"){if(!f){n.error(e("settings.mcpTab.noServerForEditing"));return}await y(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}));U(!1),j(null)}catch(le){n.error(_t(le,e("settings.mcpTab.saveServerFailed")))}},ze=()=>{I(!0),ie(null),A("merge"),W("")},_e=async()=>{const p=gi(r),le=JSON.stringify(p,null,2);try{await tn(le),n.success(e("settings.mcpTab.copiedConfig"))}catch{I(!0),ie(null),A("merge"),W(le),n.warning(e("settings.mcpTab.clipboardUnavailable"))}},We=async()=>{var Oe;ie(null);let p;try{p=JSON.parse(Z)}catch(xe){ie(`${e("settings.mcpTab.invalidJsonPrefix")}: ${xe instanceof Error?xe.message:e("settings.mcpTab.unknownError")}`);return}if(!p||typeof p!="object"){ie(e("settings.mcpTab.jsonMustBeObject"));return}const he=p.mcpServers;if(!he||typeof he!="object"){ie(e("settings.mcpTab.missingMcpServers"));return}C(!0);try{const xe=await ta.importServers({mcpServers:he,mode:Y}),Le=((Oe=xe.start_errors)==null?void 0:Oe.length)??0;n.success(e("settings.mcpTab.importSummary",{count:xe.server_ids.length,added:xe.added,updated:xe.updated,removed:xe.removed,failed:Le})),Le&&n.warning(e("settings.mcpTab.importStartFailures")),I(!1),W(""),await $()}catch(xe){ie(_t(xe,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(O,{size:"small",title:e("settings.mcpTab.overviewTitle"),children:t.jsxs(R,{direction:"vertical",size:s.marginXS,style:{width:"100%"},children:[t.jsx(Ht,{type:"secondary",children:e("settings.mcpTab.overviewDescription")}),t.jsxs(R,{wrap:!0,children:[t.jsx(re,{style:te,children:e("settings.mcpTab.totalServers",{count:X.totalServers})}),t.jsx(re,{style:te,children:e("settings.mcpTab.totalTools",{count:X.totalTools})}),Object.values(B).map(p=>t.jsx(Te,{title:L[p],children:t.jsxs(re,{color:p===B.Stopped?void 0:Mn[p],style:{cursor:"help",...p===B.Stopped?te:void 0},children:[T[p],": ",X.byStatus[p]]})},p))]}),t.jsx(Ht,{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(Ht,{type:"secondary",children:[t.jsx(re,{color:p===B.Stopped?void 0:Mn[p],style:{marginInlineEnd:8,...p===B.Stopped?te:void 0},children:T[p]}),L[p]]},`guide-${p}`))})]})}),t.jsx(O,{size:"small",title:e("settings.mcpTab.serversTitle"),extra:t.jsxs(R,{children:[t.jsx(z,{type:"primary",onClick:ve,children:e("settings.mcpTab.addServer")}),t.jsx(z,{icon:t.jsx(zt,{}),loading:g,onClick:()=>{$()},children:e("settings.mcpTab.refreshAll")}),t.jsx(z,{icon:t.jsx(Yn,{}),onClick:()=>void _e(),children:e("settings.mcpTab.export")}),t.jsx(z,{icon:t.jsx(Ba,{}),onClick:ze,children:e("settings.mcpTab.import")})]}),children:t.jsx(Zr,{servers:r,loading:d,selectedServerId:i,onSelectServer:h,onEditServer:Ke,onDeleteServer:De,onConnectServer:Pe,onDisconnectServer:qe,onRefreshTools:Ze,isServerActionLoading:m})}),t.jsx(li,{server:G,tools:l,loading:c}),t.jsx(si,{open:P,mode:Q,initialConfig:(f==null?void 0:f.config)??null,confirmLoading:u,onCancel:()=>{u||(U(!1),j(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),ie(null))},width:800,destroyOnClose:!1,children:t.jsxs(R,{direction:"vertical",style:{width:"100%"},size:"middle",children:[t.jsxs(Ht,{type:"secondary",children:[e("settings.mcpTab.importHint"),t.jsx("br",{}),t.jsx(Ht,{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(di,{value:Z,onChange:p=>W(p.target.value),rows:14,placeholder:'{"mcpServers": { "filesystem": { "command": "...", "args": [], "env": {} } }}',spellCheck:!1})]})})]})},sa=1,pi=365,na=e=>Number.isFinite(e)?Math.min(pi,Math.max(sa,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},Kt=e=>e.toISOString().slice(0,10),hi=(e,s)=>{const n=new Date(e.getTime());return n.setUTCDate(n.getUTCDate()+s),n},fi=(e,s)=>{const n=s.getTime()-e.getTime(),a=Math.floor(n/864e5)+1;return na(a)},an=(e,s=new Date)=>{const n=na(e.days),a=Kt(s),r=Ns(e.endDate)??Ns(a);if(!r)return{startDate:a,endDate:a,days:sa};const i=Ns(e.startDate);if(i){const d=r<i?i:r;return{startDate:Kt(i),endDate:Kt(d),days:fi(i,d)}}const l=hi(r,-(n-1));return{startDate:Kt(l),endDate:Kt(r),days:n}},yi=15e3,xi=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,bi=(e={})=>{const{filters:s,autoRefreshMs:n=yi}=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,y]=o.useState(!1),[b,F]=o.useState(null),M=o.useCallback(async D=>{D?h(!0):y(!0);try{const m={startDate:r.startDate,endDate:r.endDate,endpoint:a.endpoint,model:a.model,limit:a.limit},[T,L,P]=await Promise.all([Qt.getForwardSummary(m),Qt.getForwardByEndpoint(m),Qt.getForwardRequests(m)]);l(T),u(L),c(P),F(null)}catch(m){F(xi(m,"Failed to load forward metrics"))}finally{D?h(!1):y(!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:b,refresh:w}},vi=15e3,En=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,Ti=(e={})=>{const{filters:s,autoRefreshMs:n=vi,service:a=Qt}=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([]),[y,b]=o.useState(null),[F,M]=o.useState([]),[w,D]=o.useState(null),[m,T]=o.useState(!1),[L,P]=o.useState(!1),[U,Q]=o.useState(!1),[N,f]=o.useState(null),j=o.useCallback(async A=>{A?P(!0):Q(!0);try{const Z=a.getMemorySummary?a.getMemorySummary().catch(()=>null):Promise.resolve(null),W=a.getMemoryTimeline?a.getMemoryTimeline({days:i.days,endDate:i.endDate,granularity:r.granularity}).catch(()=>[]):Promise.resolve([]),[ne,ie,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,W]);d(ne),g(ie),x(Ce),S(C),b(G),M(X),f(null)}catch(Z){f(En(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 j(!1)},[j]),I=o.useCallback(async A=>{T(!0);try{const Z=await a.getSessionDetail(A);D(Z)}catch(Z){f(En(Z,"Failed to load session detail"))}finally{T(!1)}},[a]),Y=o.useCallback(()=>{D(null)},[]);return o.useEffect(()=>{j(!0)},[j]),o.useEffect(()=>{if(n<=0)return;const A=window.setInterval(()=>{j(!1)},n);return()=>{window.clearInterval(A)}},[n,j]),{summary:l,modelMetrics:u,sessions:c,timeline:h,memorySummary:y,memoryTimeline:F,sessionDetail:w,isLoading:L,isRefreshing:U,isSessionDetailLoading:m,error:N,refresh:E,loadSessionDetail:I,clearSessionDetail:Y}},ji=15e3,Si=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,_i=(e={})=>{const{filters:s,autoRefreshMs:n=ji}=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 b=>{b?u(!0):c(!0);try{const F=await Qt.getUsageBreakdown({startDate:r.startDate,endDate:r.endDate,model:a.model});l(F),h(null)}catch(F){h(Si(F,"Failed to load usage breakdown"))}finally{b?u(!1):c(!1)}},[a.model,r.endDate,r.startDate]),y=o.useCallback(async()=>{await S(!1)},[S]);return o.useEffect(()=>{S(!0)},[S]),o.useEffect(()=>{if(n<=0)return;const b=window.setInterval(()=>{S(!1)},n);return()=>{window.clearInterval(b)}},[n,S]),{data:i,isLoading:d,isRefreshing:g,error:x,refresh:y}},{useToken:ki}=ye,wi=({data:e,loading:s})=>{const{t:n}=se(),{token:a}=ki();if(s)return t.jsx(O,{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(O,{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(O,{size:"small",className:"lotus-metric-card",title:n("settings.charts.endpointDistribution"),children:t.jsx("div",{style:{width:"100%",height:240},children:t.jsx(Ot,{children:t.jsxs(sn,{data:r,children:[t.jsx(rs,{strokeDasharray:"3 3"}),t.jsx(is,{dataKey:"endpoint"}),t.jsx(os,{}),t.jsx(Lt,{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$/,""),aa=e=>e.toLocaleString(),ra=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 aa(e)},Ci=e=>Number.isFinite(e)&&Math.abs(e)>=1e3,ia=e=>ra(e),as=e=>{if(!Number.isFinite(e))return String(e);const s=rn(e);return Ci(e)?t.jsx(Te,{title:t.jsx("div",{children:ra(e)}),children:t.jsx("span",{children:s})}):s},it=e=>{const s=Number(e??0);return Number.isFinite(s)?as(s):e==null?"-":String(e)},{useToken:Mi}=ye,Ei=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`},Dn=({summary:e,loading:s})=>{const{t:n}=se(),{token:a}=Mi();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(O,{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(O,{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(O,{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(O,{size:"small",className:"lotus-metric-card",children:t.jsx(Se,{title:n("settings.forwardMetricsCards.avgResponseTime"),value:Ei(e==null?void 0:e.avg_duration_ms),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:kt}=ue,Di=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`},Pi=e=>new Date(e).toLocaleString(),Ii=({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(kt,{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(re,{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(re,{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(qa,{status:l,text:i.status_code?t.jsxs("span",{children:[i.status,t.jsxs(kt,{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(kt,{children:as(i.token_usage.total_tokens)}):t.jsx(kt,{type:"secondary",children:"-"})},{title:n("settings.metricsTable.forward.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",width:100,render:r=>Di(r)},{title:n("settings.metricsTable.forward.columns.started"),dataIndex:"started_at",key:"started_at",width:160,render:r=>t.jsx(kt,{type:"secondary",style:{fontSize:12},children:Pi(r)})},{title:n("settings.metricsTable.forward.columns.error"),dataIndex:"error",key:"error",width:200,render:r=>r?t.jsx(kt,{type:"danger",ellipsis:!0,style:{maxWidth:180},children:r}):t.jsx(kt,{type:"secondary",children:"-"})}];return t.jsx(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:Fi}=ye,Ai=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString()},Pn=({summary:e,loading:s})=>{const{t:n}=se(),{token:a}=Fi();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(O,{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(O,{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(O,{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(O,{size:"small",className:"lotus-metric-card",children:t.jsx(Se,{title:n("settings.unifiedMetricsCards.lastReindex"),value:Ai(e==null?void 0:e.last_reindex_at),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:Ri}=ue,zi=({data:e,loading:s})=>{const{t:n}=se();return s?t.jsx(O,{size:"small",className:"lotus-metric-card",title:n("settings.charts.memoryTrendTitle"),children:t.jsx(dt,{active:!0,paragraph:{rows:5}})}):t.jsx(O,{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(Ri,{type:"secondary",children:n("settings.charts.memoryTrendDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(Ot,{children:t.jsxs(Qn,{data:e,children:[t.jsx(rs,{strokeDasharray:"3 3"}),t.jsx(is,{dataKey:"label",minTickGap:24}),t.jsx(os,{allowDecimals:!1}),t.jsx(Lt,{}),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:Oi}=ye,Li=e=>{const s=Math.floor(e/1e3),n=Math.floor(s/60),a=s%60;return n>0?`${n}m ${a}s`:`${a}s`},Ni=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)},In=({summary:e,sessions:s,loading:n})=>{const{t:a}=se(),{token:r}=Oi();if(n)return t.jsx(dt,{active:!0,paragraph:{rows:1}});const i=Ni(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(O,{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(O,{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(O,{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(O,{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(O,{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(O,{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(O,{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(O,{size:"small",className:"lotus-metric-card",children:t.jsx(Se,{title:a("settings.metricsCards.avgSessionDuration"),value:i>0?Li(i):"-",valueStyle:{color:"var(--lotus-chart-accent)"}})})})]})},{Text:Vi}=ue,Fn=["var(--lotus-chart-primary)","var(--lotus-chart-secondary)","var(--lotus-chart-accent)","var(--lotus-chart-purple)","var(--lotus-chart-cyan)"],$i=({data:e,loading:s})=>{const{t:n}=se();if(s)return t.jsx(O,{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(O,{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(Vi,{type:"secondary",children:n("settings.charts.modelDistributionDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(Ot,{children:t.jsxs(er,{children:[t.jsx(tr,{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(sr,{fill:Fn[i%Fn.length]},`${r.name}-${i}`))}),t.jsx(Lt,{formatter:r=>ia(r)})]})})})]})})},Bi=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?"-":s.toLocaleString()},qi=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`},Ui=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"}},Hi=(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}},Ki=({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(Te,{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(re,{color:Ui(i),children:Hi(i,a)})},{title:a("settings.metricsTable.session.columns.started"),dataIndex:"started_at",key:"started_at",render:i=>Bi(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=>qi(i),width:120},{title:a("settings.metricsTable.session.columns.tokens"),key:"tokens",render:(i,l)=>as(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(z,{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:Wi}=ue,An={message_count:"Message Count",last_message_id:"Last Message",pending_question:"Pending Question"},Gi=e=>An[e]?An[e]:e.split("_").map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "),Ji=({breakdown:e,loading:s})=>{const{t:n}=se();if(s)return t.jsx(O,{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:Gi(r)}),count:i})).sort((r,i)=>i.count-r.count);return t.jsx(O,{size:"small",className:"lotus-metric-card",title:n("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),extra:t.jsx(Wi,{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(Ot,{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(Lt,{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:Xi}=ue,Yi=({data:e,loading:s})=>{const{t:n}=se();return s?t.jsx(O,{size:"small",className:"lotus-metric-card",title:n("settings.charts.tokenUsageOverTime"),children:t.jsx(dt,{active:!0,paragraph:{rows:5}})}):t.jsx(O,{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(Xi,{type:"secondary",children:n("settings.charts.tokenUsageDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(Ot,{children:t.jsxs(Qn,{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(Lt,{formatter:a=>ia(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:Zi}=ue,Wt=({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(O,{size:"small",className:"lotus-metric-card",title:e,children:t.jsx(dt,{active:!0,paragraph:{rows:5}})}):t.jsx(O,{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(Zi,{type:"secondary",children:s}):null,t.jsx("div",{style:{width:"100%",minWidth:0,height:280,marginTop:s?12:0},children:t.jsx(Ot,{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(Lt,{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:Qi}=ye,Rn=({summary:e,loading:s})=>{const{t:n}=se(),{token:a}=Qi();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(O,{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:wt}=ue,{useToken:eo}=ye,zn=e=>"date"in e?e.date:e.label,to=(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`},On=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}: ${aa(a)}`).join(" • ")},Bs=(e,s=320)=>({width:"100%",display:"grid",gridTemplateColumns:`repeat(auto-fit, minmax(${s}px, 1fr))`,gap:e}),so=()=>{const{t:e}=se(),{token:s}=eo(),n=ja(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:y,sessions:b,timeline:F,memorySummary:M,memoryTimeline:w,sessionDetail:D,isLoading:m,isRefreshing:T,isSessionDetailLoading:L,error:P,refresh:U,loadSessionDetail:Q,clearSessionDetail:N}=Ti({filters:{startDate:a,endDate:i,model:d,days:g,granularity:x}}),{summary:f,endpointMetrics:j,requests:E,isLoading:I,isRefreshing:Y,error:A,refresh:Z}=bi({filters:{startDate:a,endDate:i,days:g,model:d}}),{data:W,isLoading:ne,isRefreshing:ie,error:Ce,refresh:C}=_i({filters:{startDate:a,endDate:i,days:g,model:d}}),G=o.useMemo(()=>F.map(p=>({label:zn(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(()=>y.map(p=>({label:p.model,value:p.model})),[y]),te=o.useMemo(()=>{const p=F.map(he=>({label:zn(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)=>as(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,xe=b.reduce((Vt,v)=>Vt+v.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,Nt=(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(Vt=>Vt.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,bt=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:bt,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:Nt},{title:e("settings.metricsDashboard.compactStats.avgRoundsPerSession"),value:p>0?Number((xe/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:y.length},{title:e("settings.metricsDashboard.compactStats.endpointCoverage"),value:j.length}]},[j.length,E,f,y.length,De,b,S,e]),Ze=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,xe=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(xe.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:j.length}]},[j.length,E,f,De,e]),$=o.useMemo(()=>W?[{label:e("settings.metricsDashboard.skillsAndMcp.mix.coreTools",{defaultValue:"Core Tools"}),count:W.core_tool_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.skillLoads",{defaultValue:"Skill Loads"}),count:W.skill_load_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.mcpCalls",{defaultValue:"MCP Calls"}),count:W.mcp_calls}].filter(p=>p.count>0):[],[e,W]),ve=o.useMemo(()=>((W==null?void 0:W.top_skills)??[]).map(p=>({label:p.skill_id,count:p.count})),[W]),Ke=o.useMemo(()=>((W==null?void 0:W.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,W]),Me=o.useMemo(()=>((W==null?void 0:W.top_mcp_tools)??[]).map(p=>({label:p.tool_name,count:p.count,meta:p.server_id})),[W]),ze=o.useMemo(()=>((W==null?void 0:W.top_core_tools)??[]).map(p=>({label:p.name,count:p.count})),[W]),_e=D==null?void 0:D.session,We=T||Y||ie;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(O,{size:"small",title:e("settings.metricsDashboard.filtersTitle"),extra:t.jsx(z,{icon:t.jsx(zt,{}),loading:We,onClick:()=>{U(),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(O,{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(O,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.overviewSections.scaleTitle",{defaultValue:"Scale & Activity"}),extra:t.jsx(wt,{type:"secondary",children:e("settings.metricsDashboard.overviewSections.scaleSubtitle",{defaultValue:"Current usage volume across chat, forward, skills, and memory."})}),children:t.jsxs(R,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(In,{summary:S,sessions:b,loading:m}),t.jsx(Dn,{summary:f,loading:I}),t.jsx(Rn,{summary:W,loading:ne}),t.jsx(Pn,{summary:M,loading:m})]})}),t.jsxs(O,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.overviewSections.efficiencyTitle",{defaultValue:"Compression & Efficiency Advantage"}),extra:t.jsx(wt,{type:"secondary",children:e("settings.metricsDashboard.overviewSections.efficiencySubtitle",{defaultValue:"Real savings from context compression, especially around tool-heavy workflows."})}),children:[t.jsx(Ge,{gutter:[s.marginSM,s.marginSM],children: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(wt,{type:"secondary",style:{display:"block",marginTop:s.marginXS},children:e("settings.metricsDashboard.efficiencyHint",{defaultValue:"这些指标优先使用真实运行统计:总节约 Tokens、工具上下文压缩节约、非工具压缩节约、压缩事件数,以及会话 / Forward 的平均负载与质量指标。"})})]})]})},{key:"chat",label:e("settings.metricsDashboard.tabs.chat",{defaultValue:"Chat"}),children:t.jsxs(R,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(In,{summary:S,sessions:b,loading:m}),t.jsxs("div",{style:Bs(s.marginSM,360),children:[t.jsx(Yi,{data:G,loading:m}),t.jsx($i,{data:y,loading:m})]}),t.jsxs("div",{style:Bs(s.marginSM,360),children:[t.jsx(Ji,{breakdown:S==null?void 0:S.sync_mismatch_breakdown,loading:m}),t.jsx(O,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.activityHeatmapTitle"),children:te.points.length===0?t.jsx(wt,{type:"secondary",children:e("settings.metricsDashboard.noActivity")}):t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(72px, 1fr))",gap:s.marginXS},children:te.points.map(p=>t.jsxs("div",{style:{borderRadius:s.borderRadiusSM,padding:s.paddingXS,background:to(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(Rn,{summary:W,loading:ne}),t.jsxs("div",{style:Bs(s.marginSM,360),children:[t.jsx(Wt,{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(Wt,{title:e("settings.metricsDashboard.skillsAndMcp.topSkillsTitle",{defaultValue:"Top Skills"}),subtitle:e("settings.metricsDashboard.skillsAndMcp.topSkillsSubtitle",{defaultValue:"Counted from load_skill calls during matching sessions."}),emptyText:e("settings.metricsDashboard.skillsAndMcp.noSkills",{defaultValue:"No skills were loaded in this range."}),data:ve,loading:ne,color:"var(--lotus-chart-purple)"}),t.jsx(Wt,{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(Wt,{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(Wt,{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(Dn,{summary:f,loading:I}),t.jsx(O,{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:Ze.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(wi,{data:j,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(Pn,{summary:M,loading:m}),t.jsx(zi,{data:w,loading:m}),t.jsx(O,{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:On(M==null?void 0:M.last_dream_at)}),t.jsx(Ae.Item,{label:e("settings.metricsDashboard.memory.lastReindex",{defaultValue:"Last Reindex"}),children:On(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:b.length}),children:t.jsx(O,{size:"small",extra:t.jsx(wt,{type:"secondary",children:e("settings.metricsDashboard.sessionsHint")}),children:t.jsx(Ki,{sessions:b,loading:m,onSelectSession:p=>{Q(p)}})})},{key:"forward-requests",label:e("settings.metricsDashboard.forwardTabLabel",{count:E.length}),children:t.jsx(O,{size:"small",children:t.jsx(Ii,{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(wt,{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:as(_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(wt,{type:"secondary",children:e("settings.metricsDashboard.noDetail")})})]})},{Text:ps}=ue,{useToken:no}=ye,ao=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"},ro=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},io=()=>{const{t:e}=se(),{token:s}=no(),[n,a]=Rt.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 b=await Fe.getBambooConfig();d(ro(b)),g(ao(b))}catch(b){n.error(b instanceof Error?b.message:e("settings.hooksTab.loadFailed"))}finally{i(!1)}},[n,e]),h=o.useCallback(async(b,F)=>{await Fe.setBambooConfig({hooks:{image_fallback:{enabled:b,mode:F}}})},[]),S=o.useCallback(async b=>{i(!0);try{await h(b,u),n.success(e(b?"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]),y=o.useCallback(async b=>{var F;i(!0);try{await h(l,b),n.success(e("settings.hooksTab.modeUpdated",{mode:((F=c.find(M=>M.value===b))==null?void 0:F.label)??b})),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(K,{vertical:!0,gap:s.marginLG,children:[a,t.jsx(O,{size:"small",loading:r,children:t.jsxs(K,{vertical:!0,gap:s.marginXS,children:[t.jsx(ps,{strong:!0,children:e("settings.hooksTab.title")}),t.jsxs(K,{align:"center",justify:"space-between",children:[t.jsx(ps,{children:e("settings.hooksTab.enableImagePreflight")}),t.jsx(pe,{checked:l,onChange:S})]}),t.jsxs(K,{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:y,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 oa(e){return{type:"interval",every_seconds:e}}function oo(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 Ln(e){switch(e.trigger_type){case"interval":{const s=Number(e.interval_seconds||0);return s<=0?{errorKey:"settings.schedulesTab.validation.intervalRequired"}:{trigger:oa(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}=oo(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 Nn(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 lo(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 co=[{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 uo(e){return(e==null?void 0:e.type)==="interval"?e.every_seconds:null}function go(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 mo(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 po(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 ho(e){var s;return(s=e.state)!=null&&s.next_fire_at?String(e.state.next_fire_at):"-"}function fo(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 yo(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 xo(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(K,{gap:12,wrap:"wrap",children:[t.jsx(_.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(_.Item,{label:n("settings.schedulesTab.form.dailyMinute"),name:s,style:{width:180},children:t.jsx(we,{min:0,max:59,style:{width:"100%"}})})]})}function bo(){const{t:e}=se(),[s,n]=Rt.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),[y]=_.useForm(),[b]=_.useForm(),F=_.useWatch("trigger_type",y),M=_.useWatch("misfire_policy",y),w=_.useWatch("trigger_type",b),D=_.useWatch("misfire_policy",b),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]),T=o.useCallback(async(f,j,E)=>{try{await E()}catch(I){console.error(`[Schedules] ${f}:`,I),s.error(e(j))}},[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")}],U=[{value:"queue_one",label:e("settings.schedulesTab.overlapPolicyOptions.queueOne")},{value:"skip",label:e("settings.schedulesTab.overlapPolicyOptions.skip")},{value:"allow",label:e("settings.schedulesTab.overlapPolicyOptions.allow")}],Q=(f,j)=>t.jsxs(t.Fragment,{children:[t.jsxs(K,{gap:12,wrap:"wrap",children:[t.jsx(_.Item,{label:e("settings.schedulesTab.form.name"),name:"name",rules:[{required:!0,message:e("settings.schedulesTab.validation.nameRequired")}],style:{flex:"1 1 260px"},children:t.jsx(q,{})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.triggerType"),name:"trigger_type",rules:[{required:!0,message:e("settings.schedulesTab.validation.triggerRequired")}],style:{width:220},children:t.jsx(ee,{options:L})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.enabled"),name:"enabled",valuePropName:"checked",style:{width:120},children:t.jsx(pe,{})})]}),f==="interval"?t.jsx(_.Item,{label:e("settings.schedulesTab.form.intervalSeconds"),name:"interval_seconds",rules:[{required:!0,message:e("settings.schedulesTab.validation.intervalRequired")}],style:{width:220},children:t.jsx(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(_.Item,{label:e("settings.schedulesTab.form.weeklyWeekdays"),name:"weekly_weekdays",style:{minWidth:320},children:t.jsx(ee,{mode:"multiple",options:co})}),t.jsx(qs,{hourName:"weekly_hour",minuteName:"weekly_minute"})]}):null,f==="monthly"?t.jsxs(t.Fragment,{children:[t.jsx(_.Item,{label:e("settings.schedulesTab.form.monthlyDays"),name:"monthly_days",style:{minWidth:320},children:t.jsx(q,{placeholder:e("settings.schedulesTab.form.monthlyDaysPlaceholder")})}),t.jsx(qs,{hourName:"monthly_hour",minuteName:"monthly_minute"})]}):null,f==="cron"?t.jsx(_.Item,{label:e("settings.schedulesTab.form.cronExpr"),name:"cron_expr",children:t.jsx(q,{placeholder:e("settings.schedulesTab.form.cronExprPlaceholder")})}):null,t.jsxs(K,{gap:12,wrap:"wrap",children:[t.jsx(_.Item,{label:e("settings.schedulesTab.form.timezone"),name:"timezone",style:{flex:"1 1 240px"},children:t.jsx(q,{placeholder:e("settings.schedulesTab.form.timezonePlaceholder")})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.startAt"),name:"start_at",style:{flex:"1 1 240px"},children:t.jsx(q,{placeholder:e("settings.schedulesTab.form.datetimePlaceholder")})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.endAt"),name:"end_at",style:{flex:"1 1 240px"},children:t.jsx(q,{placeholder:e("settings.schedulesTab.form.datetimePlaceholder")})})]}),t.jsxs(K,{gap:12,wrap:"wrap",children:[t.jsx(_.Item,{label:e("settings.schedulesTab.form.misfirePolicy"),name:"misfire_policy",style:{flex:"1 1 240px"},children:t.jsx(ee,{options:P})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.overlapPolicy"),name:"overlap_policy",style:{flex:"1 1 240px"},children:t.jsx(ee,{options:U})})]}),j==="catch_up_window"?t.jsxs(K,{gap:12,wrap:"wrap",children:[t.jsx(_.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxRuns"),name:"catch_up_window_max_runs",style:{width:220},children:t.jsx(we,{min:1,style:{width:"100%"}})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxLatenessSeconds"),name:"catch_up_window_max_lateness_seconds",style:{width:260},children:t.jsx(we,{min:1,style:{width:"100%"}})})]}):null,t.jsx(_.Item,{label:e("settings.schedulesTab.form.taskMessage"),name:"task_message",children:t.jsx(q.TextArea,{rows:3,placeholder:e("settings.schedulesTab.form.taskMessagePlaceholder")})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.systemPrompt"),name:"system_prompt",children:t.jsx(q.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})}),t.jsxs(K,{gap:12,wrap:"wrap",children:[t.jsx(_.Item,{label:e("settings.schedulesTab.form.model"),name:"model",style:{flex:"1 1 240px"},children:t.jsx(q,{placeholder:e("settings.schedulesTab.form.modelPlaceholder")})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.workspacePath"),name:"workspace_path",style:{flex:"1 1 320px"},children:t.jsx(q,{placeholder:e("settings.schedulesTab.optional")})}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.autoExecute"),name:"auto_execute",valuePropName:"checked",style:{width:160},children:t.jsx(pe,{})})]}),t.jsx(_.Item,{label:e("settings.schedulesTab.form.enhancePrompt"),name:"enhance_prompt",children:t.jsx(q.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})})]}),N=o.useMemo(()=>[{title:e("settings.schedulesTab.columns.name"),key:"name",render:(f,j)=>t.jsxs(K,{vertical:!0,gap:6,children:[t.jsx(Ee,{strong:!0,children:j.name}),t.jsxs(K,{gap:6,wrap:"wrap",children:[t.jsx(re,{children:go(j.trigger)}),j.timezone?t.jsx(re,{color:"blue",children:j.timezone}):null,t.jsx(re,{children:mo(j.misfire_policy)}),t.jsx(re,{children:po(j.overlap_policy)})]})]})},{title:e("settings.schedulesTab.columns.status"),key:"status",render:(f,j)=>{const E=yo(j);return t.jsxs(K,{vertical:!0,gap:4,children:[t.jsx(re,{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,j)=>{var E,I,Y,A;return t.jsxs(K,{vertical:!0,gap:2,children:[t.jsx(Ee,{type:"secondary",children:e("settings.schedulesTab.activityLabels.queued",{count:((E=j.state)==null?void 0:E.queued_run_count)??0})}),t.jsx(Ee,{type:"secondary",children:e("settings.schedulesTab.activityLabels.running",{count:((I=j.state)==null?void 0:I.running_run_count)??0})}),t.jsx(Ee,{type:"secondary",children:e("settings.schedulesTab.activityLabels.ok",{count:((Y=j.state)==null?void 0:Y.total_success_count)??0})}),t.jsx(Ee,{type:"secondary",children:e("settings.schedulesTab.activityLabels.fail",{count:((A=j.state)==null?void 0:A.total_failure_count)??0})})]})}},{title:e("settings.schedulesTab.columns.nextRun"),key:"next_run_at",render:(f,j)=>t.jsx(Ee,{type:"secondary",children:ho(j)})},{title:e("settings.schedulesTab.columns.lastRun"),key:"last_run_at",render:(f,j)=>t.jsx(Ee,{type:"secondary",children:fo(j)})},{title:e("settings.schedulesTab.columns.autoExecute"),key:"auto_execute",render:(f,j)=>{var E,I;return t.jsx(Ee,{type:(E=j.run_config)!=null&&E.auto_execute?void 0:"secondary",children:(I=j.run_config)!=null&&I.auto_execute?e("settings.schedulesTab.yes"):e("settings.schedulesTab.no")})}},{title:e("settings.schedulesTab.columns.model"),key:"model",render:(f,j)=>{var E;return t.jsx(Ee,{type:"secondary",children:(E=j.run_config)!=null&&E.model?String(j.run_config.model):"-"})}},{title:e("settings.schedulesTab.columns.enabled"),key:"enabled",render:(f,j)=>t.jsx(pe,{checked:j.enabled,onChange:async E=>{await T("Failed to toggle","settings.schedulesTab.updateFailed",async()=>{await st.patchSchedule(j.id,{enabled:E}),await m()})}})},{title:e("settings.schedulesTab.columns.actions"),key:"actions",render:(f,j)=>{const E=t.jsx(we,{min:1,value:uo(j.trigger)??void 0,disabled:j.trigger.type!=="interval",onChange:async I=>{const Y=typeof I=="number"?I:null;!Y||Y<=0||await T("Failed to patch interval","settings.schedulesTab.updateFailed",async()=>{await st.patchSchedule(j.id,{trigger:oa(Y)}),await m()})}});return t.jsxs(K,{vertical:!0,gap:8,children:[t.jsxs(K,{gap:8,wrap:"wrap",children:[t.jsx(z,{size:"small",onClick:()=>{h({open:!0,schedule:j,saving:!1}),b.setFieldsValue(xo(j))},children:e("settings.schedulesTab.actions.edit")}),t.jsx(z,{size:"small",onClick:async()=>{await T("Failed to run now","settings.schedulesTab.runNowFailed",async()=>{await st.runScheduleNow(j.id),s.success(e("settings.schedulesTab.enqueuedRun")),await m()})},children:e("settings.schedulesTab.actions.runNow")}),t.jsx(z,{size:"small",onClick:async()=>{u(I=>({...I,open:!0,scheduleId:j.id,loading:!0,sessions:[]}));try{const I=await st.listScheduleSessions(j.id);u(Y=>({...Y,open:!0,scheduleId:j.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(z,{size:"small",onClick:async()=>{c(I=>({...I,open:!0,scheduleId:j.id,loading:!0,runs:[]}));try{const I=await st.listScheduleRuns(j.id);c(Y=>({...Y,open:!0,scheduleId:j.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(z,{danger:!0,size:"small",onClick:async()=>{await T("Failed to delete","settings.schedulesTab.deleteFailed",async()=>{await st.deleteSchedule(j.id),s.success(e("settings.schedulesTab.deleted")),await m()})},children:e("settings.schedulesTab.actions.delete")})]}),t.jsxs(K,{gap:8,align:"center",wrap:"wrap",children:[t.jsx(Ee,{type:"secondary",children:e("settings.schedulesTab.columns.intervalSeconds")}),j.trigger.type==="interval"?E:t.jsx(Te,{title:e("settings.schedulesTab.nonIntervalReadOnly"),children:t.jsx("span",{children:E})})]})]})}}],[b,s,m,T,e]);return t.jsxs(K,{vertical:!0,gap:16,children:[n,t.jsx(O,{title:e("settings.schedulesTab.createTitle"),className:"lotus-settings-card",children:t.jsxs(_,{form:y,layout:"vertical",initialValues:{name:e("settings.schedulesTab.defaultName"),trigger_type:"interval",interval_seconds:3600,daily_hour:9,daily_minute:0,weekly_weekdays:["mon"],weekly_hour:9,weekly_minute:0,monthly_days:"1",monthly_hour:9,monthly_minute:0,cron_expr:"",timezone:"",start_at:"",end_at:"",enabled:!1,task_message:"",model:"",auto_execute:!0,misfire_policy:"run_once",overlap_policy:"queue_one",catch_up_window_max_runs:1,catch_up_window_max_lateness_seconds:60},onFinish:async f=>{try{const j=!!f.auto_execute,E=ke(f.task_message),I=ke(f.model);if(j&&!E){s.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:Y,errorKey:A}=Ln(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:Nn(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:j}}),s.success(e("settings.schedulesTab.created")),y.resetFields(),await m()}catch(j){console.error("[Schedules] Failed to create schedule:",j),s.error(e("settings.schedulesTab.createFailed"))}},children:[Q(F,M),t.jsx(z,{type:"primary",htmlType:"submit",children:e("settings.schedulesTab.actions.create")})]})}),t.jsx(O,{title:e("settings.schedulesTab.listTitle"),className:"lotus-settings-card",extra:t.jsx(z,{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(K,{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(K,{justify:"space-between",align:"center",children:[t.jsxs(K,{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(z,{size:"small",onClick:()=>{Sa(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,j)=>t.jsx(re,{color:lo(j.status),children:j.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,j)=>j.started_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.completedAt"),key:"completed_at",render:(f,j)=>j.completed_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.session"),key:"session_id",render:(f,j)=>j.session_id||"-"},{title:e("settings.schedulesTab.runHistory.columns.duration"),key:"execution_duration_ms",render:(f,j)=>j.execution_duration_ms!=null?`${j.execution_duration_ms}ms`:"-"},{title:e("settings.schedulesTab.runHistory.columns.outcome"),key:"outcome_reason",render:(f,j)=>j.outcome_reason||(j.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:()=>b.submit(),forceRender:!0,children:t.jsx(_,{form:b,layout:"vertical",onFinish:async f=>{const j=x.schedule;if(!j)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}=Ln(f);if(!A){s.error(e(Z||"settings.schedulesTab.validation.triggerRequired"));return}h(W=>({...W,saving:!0}));try{await st.patchSchedule(j.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:Nn(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(W){console.error("[Schedules] Failed to patch schedule:",W),s.error(e("settings.schedulesTab.updateFailed")),h(ne=>({...ne,saving:!1}))}},children:Q(w,D)})})]})}const{Text:Gt}=ue,Jt=en.getInstance();function vo(){const{t:e}=se(),{modal:s,message:n}=xt.useApp(),a=He(y=>y.chats),r=He(y=>y.currentSessionId),i=He(y=>y.refreshChats),l=He(y=>y.loadChats),d=He(y=>y.loadChatHistory),[u,g]=o.useState(!0),[c,x]=o.useState(!1),h=o.useMemo(()=>r?a.find(y=>y.id===r)??null:null,[a,r]),S=async y=>{if(!c){x(!0);try{await y()}finally{x(!1)}}};return t.jsxs(K,{vertical:!0,gap:16,children:[t.jsx(O,{size:"small",title:e("settings.sessionsTab.currentSessionTitle"),children:h?t.jsxs(K,{vertical:!0,gap:4,children:[t.jsx(Gt,{strong:!0,ellipsis:!0,children:h.title}),t.jsxs(Gt,{type:"secondary",ellipsis:!0,children:[e("settings.sessionsTab.id"),": ",h.id," ","•"," ",e("settings.sessionsTab.kind"),": ",h.kind]}),t.jsx(K,{gap:8,wrap:"wrap",style:{marginTop:8},children:t.jsx(z,{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 Jt.clearSession(h.id),await d(h.id),await i(),n.success(e("settings.sessionsTab.sessionCleared"))})}})},children:e("settings.sessionsTab.clearMessages")})})]}):t.jsx(Gt,{type:"secondary",children:e("settings.sessionsTab.noActiveSession")})}),t.jsxs(O,{size:"small",title:e("settings.sessionsTab.bulkCleanupTitle"),children:[t.jsxs(K,{align:"center",gap:8,style:{marginBottom:12},children:[t.jsx(Gt,{children:e("settings.sessionsTab.keepPinned")}),t.jsx(pe,{checked:u,onChange:g})]}),t.jsxs(K,{gap:8,wrap:"wrap",children:[t.jsx(z,{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 Jt.cleanupSessions("all",u),await l(),n.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteAll")}),t.jsx(z,{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 Jt.cleanupSessions("empty",u),await l(),n.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteEmpty")}),t.jsx(z,{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 Jt.cleanupSessions("children",u),await l(),n.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteChildren")})]})]}),t.jsxs(O,{size:"small",title:e("settings.sessionsTab.devResetTitle"),children:[t.jsx(Gt,{type:"secondary",children:e("settings.sessionsTab.devResetDescription")}),t.jsx(K,{style:{marginTop:12},children:t.jsx(z,{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 Jt.devResetSessions(),await l(),n.success(e("settings.sessionsTab.devResetDone"))})}})},children:e("settings.sessionsTab.devResetAction")})})]})]})}const la="notifications/preferences";function ca(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 To(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 jo(){const e=await Xe.get(la);return ca(e)}async function So(e){const s=await Xe.put(la,To(e));return ca(s)}const{Text:nt}=ue,{useToken:_o}=ye,ko={enabled:!0,onClarification:!0,onToolApproval:!0,onContextPressure:!0,onSubAgentComplete:!0},wo=()=>{const{t:e}=se(),{token:s}=_o(),{message:n}=xt.useApp(),[a,r]=o.useState(ko),[i,l]=o.useState(!0),d=_a();o.useEffect(()=>{let c=!1;return(async()=>{try{const x=await jo();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),So(S).then(y=>{r(y)}).catch(()=>{r(h),n.error(e("settings.notificationsTab.saveError","Failed to save notification preferences"))})},g=!d||i;return t.jsx(O,{size:"small",className:"lotus-settings-card",children:t.jsxs(K,{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(K,{align:"center",gap:s.marginSM,children:[t.jsx(Ua,{}),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(K,{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(K,{vertical:!0,gap:s.marginSM,style:{opacity:a.enabled?1:.5,pointerEvents:a.enabled?"auto":"none"},children:[t.jsxs(K,{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(K,{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(K,{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(K,{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(K,{align:"center",gap:s.marginSM,children:[t.jsx(Ha,{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:Co}=ue,da=({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(z,{onClick:s,children:g("settings.providerTab.cancel")},"cancel"),t.jsx(z,{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(O,{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(O,{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(z,{icon:i?t.jsx(Xs,{}):t.jsx(Yn,{}),onClick:a,type:i?"default":"primary",children:g(i?"settings.providerTab.copied":"settings.providerTab.copyCode")})]}),t.jsx("div",{style:{marginTop:8},children:t.jsxs(re,{color:d<60?"error":d<180?"warning":"success",children:[t.jsx(Ka,{style:{marginRight:4}}),"Expires in ",Math.floor(d/60),":",(d%60).toString().padStart(2,"0")]})})]})}),t.jsx(Co,{type:"secondary",children:g("settings.providerTab.afterContinueHint")})]})})},Mo=new Set(["id","type","provider_type","label","enabled","api_key_encrypted"]),Vn=e=>e?Object.fromEntries(Object.entries(e).filter(([s])=>!Mo.has(s))):{},{Password:$n}=q,{Text:mt,Paragraph:Us}=ue,Eo=["low","medium","high","xhigh","max"],Xt=(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:Eo.map(n=>t.jsx(ee.Option,{value:n,children:e(`chat.input.reasoning.${n}`)},n))}),Bn=e=>t.jsx(_.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})}),Do=e=>Array.isArray(e)?e.map(s=>typeof s=="string"?s.trim():"").filter(s=>!!s):[],Po=({type:e})=>{const{t:s}=se();if(!e)return null;switch(e){case"openai":return t.jsxs(t.Fragment,{children:[t.jsx(_.Item,{name:"api_key",label:s("settings.providerTab.openaiApiKey"),rules:[{required:!0,message:s("settings.providerTab.openaiApiKeyRequired")}],children:t.jsx(q.Password,{placeholder:s("settings.providerTab.openaiApiKeyPlaceholder","sk-..."),prefix:t.jsx(ft,{})})}),t.jsx(_.Item,{name:"base_url",label:s("settings.providerTab.baseUrlOptional"),extra:s("settings.providerTab.openaiBaseUrlHelp"),children:t.jsx(q,{placeholder:s("settings.providerTab.openaiBaseUrlPlaceholder","https://api.openai.com/v1")})}),t.jsx(_.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Xt(s)}),Bn(s)]});case"anthropic":return t.jsxs(t.Fragment,{children:[t.jsx(_.Item,{name:"api_key",label:s("settings.providerTab.anthropicApiKey"),rules:[{required:!0,message:s("settings.providerTab.anthropicApiKeyRequired")}],children:t.jsx($n,{placeholder:s("settings.providerTab.anthropicApiKeyPlaceholder","sk-ant-..."),prefix:t.jsx(ft,{})})}),t.jsx(_.Item,{name:"base_url",label:s("settings.providerTab.baseUrlOptional"),extra:s("settings.providerTab.anthropicBaseUrlHelp"),children:t.jsx(q,{placeholder:s("settings.providerTab.anthropicBaseUrlPlaceholder","https://api.anthropic.com/v1")})}),t.jsx(_.Item,{name:"max_tokens",label:s("settings.providerTab.maxTokensOptional"),extra:s("settings.providerTab.maxTokensHelp"),children:t.jsx(q,{type:"number",placeholder:s("settings.providerTab.maxTokensPlaceholder","4096"),min:1,max:1e5})}),t.jsx(_.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Xt(s)})]});case"gemini":return t.jsxs(t.Fragment,{children:[t.jsx(_.Item,{name:"api_key",label:s("settings.providerTab.geminiApiKey"),rules:[{required:!0,message:s("settings.providerTab.geminiApiKeyRequired")}],children:t.jsx($n,{placeholder:s("settings.providerTab.geminiApiKeyPlaceholder","AIza..."),prefix:t.jsx(ft,{})})}),t.jsx(_.Item,{name:"base_url",label:s("settings.providerTab.baseUrlOptional"),extra:s("settings.providerTab.geminiBaseUrlHelp"),children:t.jsx(q,{placeholder:s("settings.providerTab.geminiBaseUrlPlaceholder","https://generativelanguage.googleapis.com/v1beta")})}),t.jsx(_.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Xt(s)})]});case"copilot":return t.jsxs(t.Fragment,{children:[t.jsx(_.Item,{name:"headless_auth",label:s("settings.providerTab.headlessAuth"),valuePropName:"checked",extra:s("settings.providerTab.headlessAuthHelp"),children:t.jsx(pe,{})}),t.jsx(_.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Xt(s)}),Bn(s)]});case"bodhi":return t.jsxs(t.Fragment,{children:[t.jsx(_.Item,{name:"api_key",label:s("settings.providerTab.bodhiApiKey"),rules:[{required:!0,message:s("settings.providerTab.apiKeyRequired")}],children:t.jsx(q.Password,{placeholder:s("settings.providerTab.bodhiApiKeyPlaceholder","bhi_sk_..."),prefix:t.jsx(ft,{})})}),t.jsx(_.Item,{name:"base_url",label:s("settings.providerTab.bodhiBaseUrl"),extra:s("settings.providerTab.bodhiBaseUrlExtra"),children:t.jsx(q,{placeholder:s("settings.providerTab.bodhiBaseUrlPlaceholder","http://localhost:8080")})}),t.jsx(_.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(_.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Xt(s)})]});default:return null}},Io=({instances:e,defaultInstanceId:s,onInstancesChanged:n})=>{const{t:a}=se(),{message:r}=xt.useApp(),{token:i}=ye.useToken(),[l]=_.useForm(),[d,u]=o.useState(!1),[g,c]=o.useState(null),[x,h]=o.useState(!1),[S,y]=o.useState(null),[b,F]=o.useState(void 0),[M,w]=o.useState(null),[D,m]=o.useState(!1),[T,L]=o.useState(!1),[P,U]=o.useState(0),[Q,N]=o.useState(!1),[f,j]=o.useState(!1),[E,I]=o.useState("unknown"),[Y,A]=o.useState(!1),Z=o.useCallback($=>({type:$.type,label:$.label,enabled:$.enabled,...Vn($.config)}),[]),W=o.useCallback(()=>{c(null),F(void 0),u(!0)},[]),ne=async()=>{try{j(!0);const $=await fe.startCopilotAuth();w($),m(!0),U($.expires_in)}catch($){r.error(a("settings.providerTab.startCopilotAuthFailed","Failed to start Copilot authentication")),console.error("Failed to start Copilot authentication:",$)}finally{j(!1)}},ie=async()=>{if(M)try{L(!0),await fe.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 fe.getCopilotAuthStatus();I($.authenticated?"authenticated":"not_authenticated")}catch($){console.error("Failed to check Copilot auth status:",$),I("unknown")}finally{A(!1)}},[]);o.useEffect(()=>{d&&b==="copilot"&&C()},[C,d,b]);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(O,{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(re,{color:"success",children:a("settings.providerTab.authenticated","Authenticated")}):E==="not_authenticated"?t.jsx(re,{color:"warning",children:a("settings.providerTab.notAuthenticated","Not Authenticated")}):t.jsx(re,{children:a("settings.providerTab.unknown","Unknown")}),t.jsx(z,{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(z,{type:"primary",icon:t.jsx(Zn,{}),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:ve,label:Ke,enabled:Me,request_overrides_json:ze,..._e}=$,We=Vn(_e);if("responses_only_models"in We&&(We.responses_only_models=Do(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 fe.updateProviderInstance(g.id,p),r.success(a("settings.providerTab.instanceUpdated","Provider instance updated"))}else{const p={type:ve,label:Ke||ht[ve]||ve,enabled:Me??!0,config:We};await fe.createProviderInstance(p),r.success(a("settings.providerTab.instanceCreated","Provider instance created"))}u(!1),await n(),await et.getState().loadProviderInstances()}catch($){(xs($)||$ instanceof Error&&!ea($))&&r.error($.message)}finally{h(!1)}},[g,l,r,n,a]),Pe=o.useCallback(async $=>{try{y($),await fe.deleteProviderInstance($),r.success(a("settings.providerTab.instanceDeleted","Provider instance deleted")),await n(),await et.getState().loadProviderInstances()}catch(ve){r.error(xs(ve)?ve.message:a("settings.providerTab.instanceDeleteFailed","Failed to delete instance"))}finally{y(null)}},[n,r,a]),qe=o.useCallback(async $=>{try{await fe.setDefaultProviderInstance($),r.success(a("settings.providerTab.defaultInstanceSet","Default provider updated")),await n(),await et.getState().loadProviderInstances()}catch(ve){r.error(xs(ve)?ve.message:a("settings.providerTab.defaultInstanceFailed","Failed to set default"))}},[n,r,a]),Ze=o.useCallback(async()=>{await n()},[n]);return o.useEffect(()=>{Ze()},[]),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(z,{type:"dashed",icon:t.jsx(yt,{}),onClick:W,"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 ve=$.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(re,{color:"processing",style:{fontSize:11},children:Ke}),ve&&t.jsxs(re,{color:"gold",style:{fontSize:11},children:[t.jsx(Ga,{})," ",a("settings.providerTab.default","Default")]}),!$.enabled&&t.jsx(re,{color:"default",style:{fontSize:11},children:a("settings.providerTab.disabled","Disabled")})]}),extra:t.jsxs(R,{size:4,onClick:Me=>Me.stopPropagation(),children:[!ve&&t.jsx(Te,{title:a("settings.providerTab.setDefault","Set as default"),children:t.jsx(z,{type:"text",size:"small",icon:t.jsx(Wa,{}),onClick:()=>void qe($.id)})}),t.jsx(z,{type:"text",size:"small",icon:t.jsx(ks,{}),onClick:()=>te($)}),t.jsx(ss,{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(z,{type:"text",size:"small",danger:!0,icon:t.jsx(At,{}),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(O,{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(_,{form:l,layout:"vertical",preserve:!1,children:[t.jsx(_.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(([$,ve])=>t.jsx(ee.Option,{value:$,children:ve},$))})}),t.jsx(_.Item,{name:"label",label:a("settings.providerTab.instanceLabel","Label"),extra:a("settings.providerTab.labelHelp","A display name for this provider instance"),children:t.jsx(q,{placeholder:a("settings.providerTab.labelPlaceholder","My OpenAI Instance")})}),t.jsx(_.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(_.Item,{noStyle:!0,shouldUpdate:!0,children:()=>t.jsx(Po,{form:l,type:b})}),b==="copilot"&&X("middle")]})}),t.jsx(da,{open:D,onCancel:()=>m(!1),onComplete:()=>void ie(),onCopyCode:()=>void Ce(),completingAuth:T,copiedUserCode:Q,deviceCodeInfo:M,timeRemaining:P,token:i})]})},{Password:qn}=q,{Text:Ye,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()))},Fo=(e,s,n)=>{const a=e;a[s]={...a[s]??{},model:n}},Un=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},Hn=(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},Kn=e=>t.jsxs(R,{direction:"vertical",size:4,children:[t.jsxs(Ye,{type:"secondary",children:[e("settings.providerTab.responsesOnlyHelp1")," ",t.jsx(Ye,{code:!0,children:"/responses"}),"."]}),t.jsx(Ye,{type:"secondary",children:e("settings.providerTab.responsesOnlyHelp2")})]}),Ao=["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:Ao.map(n=>t.jsx(ee.Option,{value:n,children:e(`chat.input.reasoning.${n}`)},n))}),Ro=()=>{const{t:e}=se(),{token:s}=ye.useToken(),{message:n}=xt.useApp(),[a]=_.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),[y,b]=o.useState(!1),[F,M]=o.useState(!1),[w,D]=o.useState(null),[m,T]=o.useState(!1),[L,P]=o.useState(!1),[U,Q]=o.useState(0),[N,f]=o.useState(!1),[j,E]=o.useState([]),[I,Y]=o.useState(!1),[A,Z]=o.useState([]),[W,ne]=o.useState(null),[ie,Ce]=o.useState(!1),[C,G]=o.useState([]),[X,te]=o.useState("idle"),[De,Pe]=o.useState(null),qe=o.useCallback((v,k)=>{const J=v.instances??[],V=J.reduce((ce,oe)=>{const Ne={...oe.config};return Ne.request_overrides&&typeof Ne.request_overrides=="object"&&(Ne.request_overrides_json=JSON.stringify(Ne.request_overrides,null,2)),ce[oe.id]=Ne,ce},{});let H=v.defaults?{...v.defaults}:void 0;const me=v.default_provider_instance_id??null,ge=me?J.find(ce=>ce.id===me):void 0,be=typeof(ge==null?void 0:ge.config.model)=="string"?ge.config.model.trim():void 0;!Ks(H==null?void 0:H.chat)&&me&&be&&(H={...H||{},chat:{provider:me,model:be}});const Ie=k?Un(k):void 0,je=Hn(H,me);return Ie&&!(H!=null&&H.memory_background)&&je&&(H={...H||{},memory_background:{provider:je,model:Ie}}),{defaults:H,features:v.features,providers:V}},[]),Ze=o.useCallback((v,k)=>{Z(v.instances??[]),ne(v.default_provider_instance_id??null),Ce(!0),a.setFieldsValue(qe(v,k)),x(!0)},[qe,a]),$=o.useCallback(v=>{if(!(v!=null&&v.trim()))return;const k=A.find(J=>J.id===v);return k?k.label||ht[k.type]:ht[v]||v},[A]),ve=o.useCallback((v,k)=>{const J=new Set;v!=null&&v.trim()&&J.add(v);for(const V of fs){const H=k==null?void 0:k[V];H&&Object.keys(H).length>0&&J.add(V)}return Array.from(J)},[]);o.useEffect(()=>{if(X!=="success")return;const v=setTimeout(()=>{te("idle"),Pe(null)},2e3);return()=>clearTimeout(v)},[X]),o.useEffect(()=>{if(!m||!w){Q(0);return}Q(w.expires_in);const v=setInterval(()=>{Q(k=>k<=1?(clearInterval(v),0):k-1)},1e3);return()=>clearInterval(v)},[m,w]);const Ke=o.useCallback(async()=>{var v;try{i(!0);const[k,J]=await Promise.all([fe.getProviderConfig(),at.getInstance().getBambooConfig().catch(()=>({}))]);let V=k.defaults?{...k.defaults}:void 0;if(!((v=V==null?void 0:V.chat)!=null&&v.model)&&k.provider&&k.providers){const je=k.provider,ce=k.providers[je],oe=ce==null?void 0:ce.model;oe&&(V={...V||{},chat:{provider:je,model:oe}})}const H=Un(J),me=Hn(V,k.provider||null);H&&!(V!=null&&V.memory_background)&&me&&(V={...V||{},memory_background:{provider:me,model:H}});const ge=Ks(V==null?void 0:V.chat)?V:void 0,be={provider:k.provider,defaults:ge,providers:k.providers||{},features:k.features};ot("[Provider]","Loaded provider config:",be);const Ie={...be.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(be.provider),Ce(!1),G(ve(be.provider,Ie)),a.setFieldsValue({...be,providers:Ie,defaults:be.defaults}),x(!0)}catch(k){n.error(e("settings.providerTab.loadConfigFailed")),console.error("Failed to load provider config:",k)}finally{i(!1)}},[a,ve,n,e]),Me=o.useCallback(async()=>{try{const v=await fe.getEnvVars();E(v.entries||[])}catch(v){console.warn("Failed to load env vars for provider overrides:",v)}},[]),ze=o.useCallback(async()=>{try{const[v,k]=await Promise.all([fe.getProviderInstances(),at.getInstance().getBambooConfig().catch(()=>({}))]);if(!Array.isArray(v.instances))throw new Error("Provider instances API returned an invalid payload");Ze(v,k)}catch{}},[Ze]),_e=o.useCallback(async()=>{try{b(!0);const v=await fe.getCopilotAuthStatus();S(v)}catch(v){console.error("Failed to check Copilot auth status:",v),S({authenticated:!1,message:e("settings.providerTab.checkStatusFailed")})}finally{b(!1)}},[e]);o.useEffect(()=>{Me(),et.getState().loadCatalog(),_e(),(async()=>{try{const[v,k]=await Promise.all([fe.getProviderInstances(),at.getInstance().getBambooConfig().catch(()=>({}))]);if(!Array.isArray(v.instances))throw new Error("Provider instances API returned an invalid payload");Ze(v,k)}catch{await Ke()}})()},[Ke,Me,_e,Ze]);const We=async()=>{try{M(!0);const v=await fe.startCopilotAuth();D(v),T(!0)}catch(v){n.error(e("settings.providerTab.startCopilotAuthFailed")),console.error("Failed to start Copilot authentication:",v)}finally{M(!1)}},p=async()=>{if(w)try{P(!0),await fe.completeCopilotAuth({device_code:w.device_code,interval:w.interval||5,expires_in:w.expires_in}),n.success(e("settings.providerTab.copilotAuthSuccess")),T(!1),D(null),await _e()}catch(v){n.error(e("settings.providerTab.completeAuthFailed")),console.error("Authentication completion failed:",v)}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 fe.logoutCopilot(),n.success(e("settings.providerTab.logoutSuccess")),await _e()}catch(v){n.error(e("settings.providerTab.logoutFailed")),console.error("Failed to logout:",v)}finally{M(!1)}},Oe=o.useCallback(async()=>{Y(!0);try{const v=await fe.fetchCatalogModels();await et.getState().loadCatalog();const k=v.fetched.filter(V=>V.models&&V.models.length>0).length;v.fetched.filter(V=>V.error).length>0?n.warning(e("settings.providerTab.fetchModelsPartialSuccess",{success:k,total:v.fetched.length})):n.success(e("settings.providerTab.fetchModelsSuccess",{count:k}))}catch{n.error(e("settings.providerTab.fetchModelsFailed"))}finally{Y(!1)}},[n,e]),xe=v=>xs(v)||v instanceof Error?v.message:e("settings.providerTab.unknownError"),Le=v=>{a.setFields([{name:["provider"],errors:[]},{name:["providers",v,"api_key"],errors:[]},{name:["defaults","chat"],errors:[]}])},ds=v=>{const k=v.trim();return k?k.includes(".")?k.split(".").filter(Boolean):k==="provider"?["provider"]:k==="provider/providers"?["provider"]:null:null},Cs=(v,k)=>{if(!v.length)return;const J=v.map(V=>{const H=ds(V.path);return H?{name:H,errors:[V.message]}:V.message.toLowerCase().includes("api key")?{name:["providers",k,"api_key"],errors:[V.message]}:{name:["provider"],errors:[V.message]}}).filter((V,H,me)=>me.findIndex(ge=>JSON.stringify(ge.name)===JSON.stringify(V.name))===H);J.length&&a.setFields(J)},Ms=async v=>{var J;const k=v.provider||u;Le(k);try{const H=await at.getInstance().validateBambooConfigPatch({provider:v.provider,providers:v.providers||{},defaults:v.defaults,features:{...v.features||{},provider_model_ref:!0}});if(H.valid)return{valid:!0};const me=((J=H.errors)==null?void 0:J.provider)||[];Cs(me,k);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}}},Nt=async(v,k)=>{var J,V;try{i(!0);const H={provider:v.provider,defaults:v.defaults,providers:{...v.providers||{}},features:{...v.features||{},provider_model_ref:!0}},me=(J=H.defaults)==null?void 0:J.chat;if(!Ks(me)){const ce=e("settings.providerTab.selectModelRequired");if(a.setFields([{name:["defaults","chat"],errors:[ce]}]),(k==null?void 0:k.showMessage)!==!1&&n.error(ce),k!=null&&k.throwOnError)throw new Error(ce);return}const ge=H.providers;for(const ce of fs){const oe=ge[ce];if(!oe)continue;const Ne=oe.request_overrides_json;if(typeof Ne!="string")continue;const vt=Ne.trim();if(!vt)delete oe.request_overrides;else try{oe.request_overrides=JSON.parse(vt)}catch($t){const Bt=e("settings.providerTab.invalidRequestOverridesJson",{provider:ce,error:$t.message});if(a.setFields([{name:["providers",ce,"request_overrides_json"],errors:[Bt]}]),(k==null?void 0:k.showMessage)!==!1&&n.error(Bt),k!=null&&k.throwOnError)throw $t;return}delete oe.request_overrides_json}const be={...H.providers||{}},Ie=H.provider,je=(V=H.defaults)==null?void 0:V.chat;if(je!=null&&je.model&&Ie&&Fo(be,Ie,je.model),ie){const ce=at.getInstance(),oe={defaults:H.defaults,features:{...H.features||{},provider_model_ref:!0}};ot("[Provider]","Saving instance-mode config:",oe),await ce.setBambooConfig(oe)}else{const oe={provider:H.provider||u,defaults:H.defaults,providers:be,features:H.features},Ne=await Ms(H);if(!Ne.valid){const vt=Ne.message||e("settings.providerTab.invalidConfig");if((k==null?void 0:k.showMessage)!==!1&&n.error(`${e("settings.providerTab.invalidConfigPrefix")}: ${vt}`),k!=null&&k.throwOnError)throw new Error(vt);return}ot("[Provider]","Saving provider config:",oe),await fe.saveProviderConfig(oe)}(k==null?void 0:k.showMessage)!==!1&&n.success(e("settings.providerTab.saveConfigSuccess"))}catch(H){const me=xe(H);if((k==null?void 0:k.showMessage)!==!1&&n.error(me?`${e("settings.providerTab.saveConfigErrorPrefix")}: ${me}`:e("settings.providerTab.saveConfigFailed")),console.error("Failed to save configuration:",H),k!=null&&k.throwOnError)throw H}finally{i(!1)}},ut=async v=>{var k,J,V,H,me;try{d(!0);const{useProviderStore:ge}=await Ys(async()=>{const{useProviderStore:qt}=await import("./App-BE03KO2t.js").then(Rs=>Rs.ak);return{useProviderStore:qt}},__vite__mapDeps([4,1,2,3,5,6,7,8]),import.meta.url),{useAppStore:be}=await Ys(async()=>{const{useAppStore:qt}=await import("./App-BE03KO2t.js").then(Rs=>Rs.al);return{useAppStore:qt}},__vite__mapDeps([4,1,2,3,5,6,7,8]),import.meta.url),Ie=(k=ge.getState().providerConfig.defaults)==null?void 0:k.chat;ie?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=be.getState().currentSessionId,oe=ce&&be.getState().chats.find(qt=>qt.id===ce)||null,Ne=Ie?`${Ie.provider}/${Ie.model}`:null,vt=je?`${je.provider}/${je.model}`:null,$t=(V=oe==null?void 0:oe.config)!=null&&V.model_ref?`${oe.config.model_ref.provider}/${oe.config.model_ref.model}`:null,Bt=((me=(H=oe==null?void 0:oe.config)==null?void 0:H.model)==null?void 0:me.trim())||null;!!(ce&&(oe!=null&&oe.config)&&je&&vt!==Ne&&(!$t||$t===Ne)&&(!Bt||Bt===(Ie==null?void 0:Ie.model)))&&ce&&(oe!=null&&oe.config)&&je&&be.getState().updateSession(ce,{config:{...oe.config,model:je.model,model_ref:je}}),(v==null?void 0:v.showMessage)!==!1&&n.success(e("settings.providerTab.applyConfigSuccess"))}catch(ge){const be=xe(ge);if((v==null?void 0:v.showMessage)!==!1&&n.error(be?`${e("settings.providerTab.applyConfigErrorPrefix")}: ${be}`:e("settings.providerTab.applyConfigFailed")),console.error("Failed to apply configuration:",ge),v!=null&&v.throwOnError)throw ge}finally{d(!1)}},Es=async v=>{try{const k=a.getFieldsValue(!0);await Nt(k,{throwOnError:!0}),await ut({throwOnError:!0})}catch{}},Ds=async(v,k)=>{if(!(v==="chat"&&!k)&&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,[v]:k},await Nt(J,{showMessage:!1,throwOnError:!0}),await ut({showMessage:!1,throwOnError:!0}),te("success"),n.success(e("settings.providerTab.modelUpdated"))}catch(J){const V=xe(J);te("error"),Pe(V),n.error(V?`${e("settings.providerTab.updateModelErrorPrefix")}: ${V}`:e("settings.providerTab.updateModelFailed"))}}},Ps=async(v,k)=>{if(X!=="saving"){te("saving"),Pe(null);try{if(ie){const J=A.find(V=>V.id===v);if(!J)throw new Error(e("settings.providerTab.providerNotConfigured"));await fe.updateProviderInstance(J.id,{config:{reasoning_effort:k??null}}),await ze(),await et.getState().loadProviderInstances()}else{const J=a.getFieldsValue(!0);await Nt(J,{showMessage:!1,throwOnError:!0}),await ut({showMessage:!1,throwOnError:!0})}te("success"),n.success(e("settings.providerTab.reasoningEffortUpdated"))}catch(J){const V=xe(J);te("error"),Pe(V),n.error(V?`${e("settings.providerTab.updateReasoningEffortErrorPrefix")}: ${V}`:e("settings.providerTab.updateReasoningEffortFailed"))}}},us=(v,k)=>{if(!v)return null;const J=$(v)||v,V=a.getFieldValue(["providers",v,"reasoning_effort"]),H=(k==null?void 0:k.emphasis)==="subtle",me=(k==null?void 0:k.label)||e("settings.providerTab.reasoningEffortOptional"),ge=(k==null?void 0:k.helperText)||e("settings.providerTab.reasoningEffortHelp");return t.jsx("div",{style:{marginTop:(k==null?void 0:k.marginTop)??8,width:"100%"},children:t.jsxs(R,{direction:"vertical",size:H?6:4,style:{width:"100%"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,flexWrap:"wrap"},children:[t.jsx(Ye,{strong:!H,type:H?"secondary":void 0,style:H?{fontSize:s.fontSizeSM,lineHeight:1.4}:void 0,children:me}),k!=null&&k.showProviderLabel?t.jsx(Ye,{type:"secondary",style:{fontSize:s.fontSizeSM,lineHeight:1.4},children:J}):null]}),Pt(e,{value:V,disabled:X==="saving",size:(k==null?void 0:k.size)??(H?"small":void 0),style:{width:"100%"},"data-testid":k==null?void 0:k.dataTestId,onChange:be=>{a.setFieldValue(["providers",v,"reasoning_effort"],be),k!=null&&k.autoSave&&Ps(v,be)}}),t.jsx(Ye,{type:"secondary",style:H?{fontSize:s.fontSizeSM,lineHeight:1.5}:void 0,children:ge})]})})},Is=o.useCallback(v=>{const k=a.getFieldValue(["providers",v]);return k?v==="copilot"?(h==null?void 0:h.authenticated)??!1:!!k.api_key:!1},[a,h]),Fs=()=>{const v=J=>{const V=a.getFieldValue(["defaults",J]);return t.jsx(ka,{value:V,dataTestId:`model-preference-${J}-picker`,appearance:"contrast",disabled:X==="saving",onChange:H=>{a.setFieldValue(["defaults",J],H),Ds(J,H)}})},k=(J,V,H)=>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(Ye,{strong:!0,children:V}),v(J),H?t.jsx(Ye,{type:"secondary",children:H}):null]})}),t.jsx("div",{style:{flex:"0 1 320px",minWidth:280},children:t.jsx(_.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(O,{size:"small",title:e("settings.providerTab.modelPreferences"),style:{marginBottom:16},children:[t.jsx(_.Item,{name:["defaults","chat"],noStyle:!0,preserve:!0,children:t.jsx(Dt,{})}),t.jsx(_.Item,{name:["defaults","fast"],noStyle:!0,preserve:!0,children:t.jsx(Dt,{})}),t.jsx(_.Item,{name:["defaults","task_summary"],noStyle:!0,preserve:!0,children:t.jsx(Dt,{})}),t.jsx(_.Item,{name:["defaults","memory_background"],noStyle:!0,preserve:!0,children:t.jsx(Dt,{})}),t.jsx(_.Item,{name:["defaults","sub_agent"],noStyle:!0,preserve:!0,children:t.jsx(Dt,{})}),t.jsx(_.Item,{name:["defaults","vision"],noStyle:!0,preserve:!0,children:t.jsx(Dt,{})}),t.jsxs(R,{direction:"vertical",size:16,style:{width:"100%"},children:[k("chat",e("settings.providerTab.defaultModel")),k("fast",e("settings.providerTab.fastModel"),e("settings.providerTab.fastModelHelp")),k("task_summary",e("settings.providerTab.taskSummaryModel"),e("settings.providerTab.taskSummaryModelHelp")),k("memory_background",e("settings.providerTab.memoryBackgroundModel"),e("settings.providerTab.memoryBackgroundModelHelp")),k("sub_agent",e("settings.providerTab.subAgentModel"),e("settings.providerTab.subAgentModelHelp")),k("vision",e("settings.providerTab.visionModel"),e("settings.providerTab.visionModelHelp"))]})]})},bt=v=>{const k=j.map(V=>V.name);return t.jsx(_.Item,{name:["providers",v,"request_overrides_json"],label:e("settings.providerTab.advancedRequestOverrides"),extra:t.jsxs(R,{direction:"vertical",size:4,children:[t.jsx(Ye,{type:"secondary",children:e("settings.providerTab.advancedRequestOverridesHelp")}),t.jsxs(Ye,{type:"secondary",children:[e("settings.providerTab.envVarInjection")," ",t.jsx(Ye,{code:!0,children:'{ "type": "env_ref", "name": "YOUR_ENV_NAME" }'})]}),k.length>0&&t.jsx(R,{wrap:!0,size:[6,6],children:k.map(V=>t.jsx(re,{children:V},V))})]}),children:t.jsx(q.TextArea,{autoSize:{minRows:8,maxRows:20},placeholder:`{
4
4
  "common": {
5
5
  "headers": {
6
6
  "x-request-id": { "type": "generated", "generator": "uuid" },