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