@bigduu/lotus 2026.7.7 → 2026.7.8
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-CH_iNVyb.js → App-DlBGZjWK.js} +9 -9
- package/dist/assets/{MetricsService-DpXFjto6.js → MetricsService-BGNLv7xq.js} +1 -1
- package/dist/assets/{SubAgentsPanel-DkdkzHTa.js → SubAgentsPanel-Dgr8kIQZ.js} +1 -1
- package/dist/assets/{architectureDiagram-3BPJPVTR-Pa9A_GeZ.js → architectureDiagram-3BPJPVTR-BSB-cdZk.js} +1 -1
- package/dist/assets/{blockDiagram-GPEHLZMM-BrTopsFG.js → blockDiagram-GPEHLZMM-y-xdnYHR.js} +1 -1
- package/dist/assets/{c4Diagram-AAUBKEIU-DolJWmm5.js → c4Diagram-AAUBKEIU-DtRmWGQQ.js} +1 -1
- package/dist/assets/{chunk-2J33WTMH-DFRfsnwX.js → chunk-2J33WTMH-BYUqrt94.js} +1 -1
- package/dist/assets/{chunk-4BX2VUAB-BRHfAH23.js → chunk-4BX2VUAB-CptxQEEc.js} +1 -1
- package/dist/assets/{chunk-55IACEB6-Dpi6fPZs.js → chunk-55IACEB6-C50KVJku.js} +1 -1
- package/dist/assets/{chunk-727SXJPM-Cd5XWlyk.js → chunk-727SXJPM-sWjNfyOn.js} +1 -1
- package/dist/assets/{chunk-AQP2D5EJ-DGcXnZoj.js → chunk-AQP2D5EJ-jtnQV_yw.js} +1 -1
- package/dist/assets/{chunk-FMBD7UC4-DhZ0prpG.js → chunk-FMBD7UC4-Cd5GJLqe.js} +1 -1
- package/dist/assets/{chunk-ND2GUHAM-DL2nbZLb.js → chunk-ND2GUHAM-BXbHLihN.js} +1 -1
- package/dist/assets/{chunk-QZHKN3VN-DalupEUz.js → chunk-QZHKN3VN-_LLeuAzc.js} +1 -1
- package/dist/assets/classDiagram-4FO5ZUOK-BsDXh2bb.js +1 -0
- package/dist/assets/classDiagram-v2-Q7XG4LA2-BsDXh2bb.js +1 -0
- package/dist/assets/{cose-bilkent-S5V4N54A-CHX5fY5N.js → cose-bilkent-S5V4N54A-Dne7EKbx.js} +1 -1
- package/dist/assets/{dagre-BM42HDAG-B7351yll.js → dagre-BM42HDAG-BMxXKvd2.js} +1 -1
- package/dist/assets/{diagram-2AECGRRQ-DMEhSoRB.js → diagram-2AECGRRQ-CRx2cvB_.js} +1 -1
- package/dist/assets/{diagram-5GNKFQAL-_oUgeGBQ.js → diagram-5GNKFQAL-BB7GVXD4.js} +1 -1
- package/dist/assets/{diagram-KO2AKTUF-GdRQxJvE.js → diagram-KO2AKTUF-CEjjUzr2.js} +1 -1
- package/dist/assets/{diagram-LMA3HP47-CZNmi6mu.js → diagram-LMA3HP47-C7KOK4je.js} +1 -1
- package/dist/assets/{diagram-OG6HWLK6-CvCKP0Ao.js → diagram-OG6HWLK6-B69WmFUR.js} +1 -1
- package/dist/assets/{erDiagram-TEJ5UH35-DnB_LGjj.js → erDiagram-TEJ5UH35-C6-fg1qh.js} +1 -1
- package/dist/assets/{flowDiagram-I6XJVG4X-Cr8MwrRD.js → flowDiagram-I6XJVG4X-CjhLMhCM.js} +1 -1
- package/dist/assets/{ganttDiagram-6RSMTGT7-BuEAiskm.js → ganttDiagram-6RSMTGT7-dGLfWTBv.js} +1 -1
- package/dist/assets/{gitGraphDiagram-PVQCEYII-DBy041Sw.js → gitGraphDiagram-PVQCEYII-Y439D8Wq.js} +1 -1
- package/dist/assets/{index-CU7lQMqL.js → index-25kMCkUW.js} +1 -1
- package/dist/assets/{index-DKcVOIn3.js → index-2KR2Un7m.js} +1 -1
- package/dist/assets/{index-Cur8quEC.js → index-BCJ3Fg76.js} +1 -1
- package/dist/assets/{index-CpIxq-rS.js → index-BZHwr2e5.js} +1 -1
- package/dist/assets/{index-B4FC2zTb.js → index-CL0QO9Jc.js} +1 -1
- package/dist/assets/{index-B-I26ShO.js → index-Cbt2yWDF.js} +1 -1
- package/dist/assets/{index-BKm-Y6g1.js → index-CeT4FJ1T.js} +1 -1
- package/dist/assets/{index-Ccwc-6DE.js → index-Cr8UK1Lt.js} +1 -1
- package/dist/assets/{index-CLzNVEbw.js → index-Cs_7v182.js} +1 -1
- package/dist/assets/{index-x60LEDTE.js → index-EtPFAWY2.js} +1 -1
- package/dist/assets/{index-BUO2Zcn6.js → index-asUlqrXo.js} +3 -3
- package/dist/assets/{index-BlKENLxs.js → index-xp5F7K7U.js} +1 -1
- package/dist/assets/{infoDiagram-5YYISTIA-Cig6E2Y-.js → infoDiagram-5YYISTIA-78hduiro.js} +1 -1
- package/dist/assets/{ishikawaDiagram-YF4QCWOH-BaU9GirD.js → ishikawaDiagram-YF4QCWOH-BfRGCYZ2.js} +1 -1
- package/dist/assets/{journeyDiagram-JHISSGLW-Bu7AjxgD.js → journeyDiagram-JHISSGLW-CN1yeRpH.js} +1 -1
- package/dist/assets/{kanban-definition-UN3LZRKU-BxTBoFam.js → kanban-definition-UN3LZRKU-BOIHsGDZ.js} +1 -1
- package/dist/assets/{main-bnHa9vH1.js → main-CMR1cQYD.js} +3 -3
- package/dist/assets/{mindmap-definition-RKZ34NQL-9STdRJ65.js → mindmap-definition-RKZ34NQL-DkfmIv-_.js} +1 -1
- package/dist/assets/{pieDiagram-4H26LBE5-BhM8ytbm.js → pieDiagram-4H26LBE5-DNojxwsW.js} +1 -1
- package/dist/assets/{quadrantDiagram-W4KKPZXB-DlKlRsBQ.js → quadrantDiagram-W4KKPZXB-C5h5m2Xx.js} +1 -1
- package/dist/assets/{requirementDiagram-4Y6WPE33-Qm51Houd.js → requirementDiagram-4Y6WPE33-6uoBKG4w.js} +1 -1
- package/dist/assets/{sankeyDiagram-5OEKKPKP-DPVIX2yw.js → sankeyDiagram-5OEKKPKP-Buu5QlGi.js} +1 -1
- package/dist/assets/{sequenceDiagram-3UESZ5HK-xE5cm0Ad.js → sequenceDiagram-3UESZ5HK-BV_AuMRg.js} +1 -1
- package/dist/assets/{stateDiagram-AJRCARHV-C9Mlf8x6.js → stateDiagram-AJRCARHV-CPAxQVEd.js} +1 -1
- package/dist/assets/{stateDiagram-v2-BHNVJYJU-CeWi3ly8.js → stateDiagram-v2-BHNVJYJU-FwEssQ3h.js} +1 -1
- package/dist/assets/{timeline-definition-PNZ67QCA-CVzX8KRM.js → timeline-definition-PNZ67QCA-BXGPTHhK.js} +1 -1
- package/dist/assets/{vendor-charts-DMoAsaKk.js → vendor-charts-BoAlA5Ii.js} +1 -1
- package/dist/assets/{vendor-mermaid-BWwfm-Vj.js → vendor-mermaid-1Fp-_2HG.js} +3 -3
- package/dist/assets/{vendor-pdf-D6AjS6qD.js → vendor-pdf-BBDeU1Hh.js} +3 -3
- package/dist/assets/{vennDiagram-CIIHVFJN-BORIhifm.js → vennDiagram-CIIHVFJN-Bu9maUJJ.js} +1 -1
- package/dist/assets/{wardley-L42UT6IY-D3k90lJL.js → wardley-L42UT6IY-r0-Bx1ue.js} +1 -1
- package/dist/assets/{wardleyDiagram-YWT4CUSO-iHR9JFh-.js → wardleyDiagram-YWT4CUSO-CvpQrw4E.js} +1 -1
- package/dist/assets/{xychartDiagram-2RQKCTM6-iBAl4dM9.js → xychartDiagram-2RQKCTM6-DYwG904X.js} +1 -1
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/dist/assets/classDiagram-4FO5ZUOK-DG03s0su.js +0 -1
- package/dist/assets/classDiagram-v2-Q7XG4LA2-DG03s0su.js +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-
|
|
2
|
-
var mn=Object.defineProperty;var pn=(e,s,a)=>s in e?mn(e,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[s]=a;var la=(e,s,a)=>pn(e,typeof s!="symbol"?s+"":s,a);import{j as t}from"./vendor-markdown-CARODNj-.js";import{a as i,u as ae,R as ca,i as oe}from"./vendor-i18n-Dm-c3D_C.js";import{J as hn,u as Ke,b as fn,T as yn,g as xn,U as sa,d as st,B as ct,V as bn,W as ft,X as Re,Y as vn,Z as jn,_ as Tn,$ as _n,a0 as Xa,a1 as it,a2 as de,H as da,a as Ye,a3 as Ya,G as aa,m as Sn,l as Ys,q as kn,a4 as wn,a5 as yt,k as vs,a6 as Cn,a7 as Mn,a8 as ua,a9 as En,aa as ga,ab as ma,ac as pa,ad as ha,o as Pn,ae as Dn,A as In,af as Fn,ag as An,ah as Rn,ai as zn,aj as Ln}from"./App-CH_iNVyb.js";import{U as N,o as L,I as qe,j as ue,a9 as H,B as z,t as Te,a4 as y,a3 as as,aI as Ts,aJ as te,aK as fe,aL as Me,J as Xe,aM as Je,aN as me,D as ke,aO as Ue,aP as On,aG as Le,Q as X,aQ as ks,aR as Nn,a6 as Rt,a7 as Et,ao as Vn,aS as $n,A as ut,aT as ws,p as is,a5 as dt,x as re,aU as fa,aV as at,a8 as Qe,Z as Bn,aw as zt,a2 as Lt,n as Ft,aW as qn,an as Hn,aX as ya,aY as ze,a0 as He,av as Za,aZ as Un,a_ as gt,a$ as Ee,y as Kn,b0 as xa,b1 as Wn,X as Gn,z as Zs,W as Jn,b2 as Xn,b3 as Yn,b4 as Qa,b5 as xt,b6 as ba,b7 as Zn,ah as Qn,aC as er,b8 as tr}from"./vendor-antd-C-pjKgeW.js";import{_ as Qs}from"./vendor-mermaid-BWwfm-Vj.js";import{r as sr}from"./onboardingStorage-BVcEpmTy.js";import"./main-bnHa9vH1.js";import{m as ts}from"./MetricsService-DpXFjto6.js";import{R as Ot,B as na,C as os,X as ls,Y as cs,T as Nt,L as ra,a as _s,b as en,c as At,P as ar,d as nr,e as rr}from"./vendor-charts-DMoAsaKk.js";function ir(e){return e instanceof hn}function or(){const{chats:e,currentSessionId:s,currentChat:a,addMessage:n,selectSession:r,deleteSession:o,deleteSessions:l,deleteMessage:u,updateSession:g,persistSessionTitle:m,pinSession:c,unpinSession:b,loadChats:p}=Ke(fn(C=>({chats:C.chats,currentSessionId:C.currentSessionId,currentChat:yn(C),addMessage:C.addMessage,selectSession:C.selectSession,deleteSession:C.deleteSession,deleteSessions:C.deleteSessions,deleteMessage:C.deleteMessage,updateSession:C.updateSession,persistSessionTitle:C.persistSessionTitle,pinSession:C.pinSession,unpinSession:C.unpinSession,loadChats:C.loadChats}))),S=Ke(xn(s)),v=i.useMemo(()=>(a==null?void 0:a.messages)||[],[a]),x=i.useMemo(()=>e.filter(C=>C.pinned),[e]),R=i.useMemo(()=>e.filter(C=>!C.pinned),[e]),P=e.length;return{chats:e,currentSessionId:s,currentChat:a,isProcessing:S,baseMessages:v,pinnedChats:x,unpinnedChats:R,chatCount:P,addMessage:n,deleteMessage:u,selectSession:r,deleteSession:o,deleteSessions:l,pinSession:c,unpinSession:b,updateSession:g,persistSessionTitle:m,loadChats:p}}function lr(e){const s=Ke(p=>p.addChat),a=Ke(p=>p.lastSelectedPromptId),n=Ke(p=>p.systemPrompts),r=sa.getInstance(),o=i.useCallback(async(p,S)=>{var P,C;const v=n.find(I=>I.id===a),x=(v==null?void 0:v.id)||(n.length>0?((P=n.find(I=>I.id==="general_assistant"))==null?void 0:P.id)||n[0].id:""),R={title:p||"New Session",createdAt:Date.now(),messages:[],config:{systemPromptId:x,baseSystemPrompt:(v==null?void 0:v.content)||(n.length>0?((C=n.find(I=>I.id==="general_assistant"))==null?void 0:C.content)||n[0].content:""),lastUsedEnhancedPrompt:null,...st.getState().isProviderModelRefEnabled()?{model_ref:st.getState().selectedModelRef}:{}},...S};await s(R)},[s,a,n]),l=i.useCallback(async p=>{ct("[ChatOps]","[useChatOperations] createChatWithSystemPrompt started with prompt:",p);const S={title:`New Session - ${p.name}`,createdAt:Date.now(),messages:[],config:{systemPromptId:p.id,baseSystemPrompt:p.content,lastUsedEnhancedPrompt:null}};ct("[ChatOps]","[useChatOperations] Calling addChat with newChatData.config:",S.config),await s(S)},[s]),u=i.useCallback(p=>{const S=e.chats.find(v=>v.id===p);S&&(S.pinned?e.unpinSession(p):e.pinSession(p))},[e]),g=i.useCallback((p,S)=>{e.updateSession(p,{title:S})},[e]),m=i.useCallback(async()=>{await r.cleanupSessions("empty",!0),await Ke.getState().loadChats()},[r]),c=i.useCallback(async()=>{await r.cleanupSessions("all",!0),await Ke.getState().loadChats()},[r]),b=i.useCallback(async()=>{await r.cleanupSessions("all",!1),await Ke.getState().loadChats()},[r]);return{createNewChat:o,createChatWithSystemPrompt:l,toggleChatPin:u,updateChatTitle:g,deleteEmptyChats:m,deleteAllUnpinnedChats:c,deleteAllChats:b}}function cr(e,s){const a=i.useMemo(()=>e.baseMessages,[e.baseMessages]),n=i.useCallback(async()=>{var m;if(!e.currentSessionId||!e.currentChat)return;const r=[...e.baseMessages];if(r.length===0)return;const o=r[r.length-1];let l=r;if((o==null?void 0:o.role)==="assistant"){if(!(await e.deleteMessage(e.currentSessionId,o.id)).success)return;l=r.slice(0,-1)}const u=[...l].reverse().find(c=>c.role==="user");if(!u)return;const g="content"in u?u.content:u.displayText;typeof g=="string"&&await((m=s==null?void 0:s.onRetry)==null?void 0:m.call(s,g))},[e,s]);return{currentMessages:a,retryLastMessage:n}}const dr=()=>{const e=or(),s=lr(e),a=bn({sessionId:e.currentSessionId,addMessage:e.addMessage,updateSession:e.updateSession}),n=cr(e,{onRetry:a.sendMessage});return{chats:e.chats,currentSessionId:e.currentSessionId,currentChat:e.currentChat,pinnedChats:e.pinnedChats,unpinnedChats:e.unpinnedChats,chatCount:e.chatCount,currentMessages:n.currentMessages,agentAvailable:a.agentAvailable,addMessage:e.addMessage,deleteMessage:e.deleteMessage,selectSession:e.selectSession,deleteSession:e.deleteSession,deleteSessions:e.deleteSessions,pinSession:e.pinSession,unpinSession:e.unpinSession,updateSession:e.updateSession,loadChats:e.loadChats,createNewChat:s.createNewChat,createChatWithSystemPrompt:s.createChatWithSystemPrompt,toggleChatPin:s.toggleChatPin,updateChatTitle:s.updateChatTitle,deleteEmptyChats:s.deleteEmptyChats,deleteAllUnpinnedChats:s.deleteAllUnpinnedChats,deleteAllChats:s.deleteAllChats,retryLastMessage:n.retryLastMessage,sendMessage:a.sendMessage,cancelMessage:a.cancel}},{Text:ps}=ue,{useToken:ur}=Te,gr=({httpProxy:e,httpsProxy:s,onHttpProxyChange:a,onHttpsProxyChange:n,onReload:r,onSave:o,isLoading:l})=>{const{t:u}=ae(),{token:g}=ur(),m=ft(h=>h.proxyAuthStatus),c=ft(h=>h.isLoadingProxyAuthStatus),b=ft(h=>h.loadProxyAuthStatus),p=ft(h=>h.applyProxyAuth),S=ft(h=>h.clearProxyAuth),[v,x]=i.useState({username:"",password:""}),[R,P]=i.useState(!1);i.useEffect(()=>{b()},[b]);const C=async()=>{const h=v.username.trim();if(h){P(!0);try{await p({username:h,password:v.password}),x({username:"",password:""})}catch(k){console.error("Failed to apply proxy auth:",k)}finally{P(!1)}}},I=async()=>{P(!0);try{await S()}catch(h){console.error("Failed to clear proxy auth:",h)}finally{P(!1)}};return t.jsx(N,{size:"small",title:t.jsx(ps,{strong:!0,children:u("settings.networkCard.title")}),className:"lotus-settings-card",children:t.jsxs(L,{direction:"vertical",size:g.marginSM,style:{width:"100%"},children:[t.jsx(qe,{message:u("settings.networkCard.guideTip"),type:"info",showIcon:!0}),t.jsxs(L,{direction:"vertical",size:g.marginXXS,style:{width:"100%"},children:[t.jsx(ps,{type:"secondary",children:u("settings.networkCard.httpProxy")}),t.jsx(H,{"data-testid":"proxy-url",style:{width:"100%"},value:e,onChange:h=>a(h.target.value),placeholder:u("settings.networkCard.proxyPlaceholder"),disabled:l})]}),t.jsxs(L,{direction:"vertical",size:g.marginXXS,style:{width:"100%"},children:[t.jsx(ps,{type:"secondary",children:u("settings.networkCard.httpsProxy")}),t.jsx(H,{style:{width:"100%"},value:s,onChange:h=>n(h.target.value),placeholder:u("settings.networkCard.proxyPlaceholder"),disabled:l})]}),t.jsx(N,{size:"small",title:u("settings.networkCard.proxyAuthTitle"),className:"lotus-settings-card",style:{marginTop:g.marginSM},children:m!=null&&m.configured?t.jsxs(L,{direction:"vertical",style:{width:"100%"},children:[t.jsx(qe,{type:"success",message:u("settings.networkCard.proxyConfiguredForUser",{username:m.username??""}),showIcon:!0}),t.jsx(z,{onClick:I,loading:R||c,danger:!0,children:u("settings.networkCard.clearCredentials")})]}):t.jsxs(L,{direction:"vertical",size:g.marginXS,style:{width:"100%"},children:[t.jsx(H,{placeholder:u("settings.networkCard.username"),value:v.username,onChange:h=>x(k=>({...k,username:h.target.value}))}),t.jsx(H.Password,{placeholder:u("settings.networkCard.password"),value:v.password,onChange:h=>x(k=>({...k,password:h.target.value}))}),t.jsx(z,{type:"primary",onClick:C,loading:R||c,disabled:!v.username.trim(),children:u("settings.networkCard.apply")})]})}),t.jsx(ps,{type:"secondary",style:{fontSize:g.fontSizeSM},children:u("settings.networkCard.credentialsStorageNote")}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:g.marginSM},children:[t.jsx(z,{onClick:()=>Promise.resolve(r()).finally(()=>b({force:!0})),disabled:l,children:u("settings.networkCard.reload")}),t.jsx(z,{"data-testid":"save-proxy-settings",type:"primary",onClick:()=>Promise.resolve(o()).finally(()=>b({force:!0})),disabled:l,children:u("settings.networkCard.save")})]})]})})};function tn(e){return typeof e=="object"&&e!==null&&"errorFields"in e}const{Text:mr}=ue,{useToken:pr}=Te,hr=({msgApi:e})=>{const{t:s}=ae(),{token:a}=pr(),[n]=y.useForm(),[r,o]=i.useState(!1),[l,u]=i.useState(!1),[g,m]=i.useState(!1),[c,b]=i.useState(!1),[p,S]=i.useState(null),v=g&&!c,x=i.useMemo(()=>s(g?c?"settings.configTab.accessPassword.helperLocalBypass":"settings.configTab.accessPassword.helperRemote":"settings.configTab.accessPassword.helperNotEnabled"),[c,g,s]),R=i.useCallback(async()=>{o(!0),S(null);try{const C=await Re.getAccessStatus();m(C.password_enabled),b(C.local_bypass)}catch(C){const I=C instanceof Error?C.message:s("settings.configTab.accessPassword.loadStatusFailed","Failed to load access status");S(I)}finally{o(!1)}},[s]);i.useEffect(()=>{R()},[R]);const P=async()=>{var C;try{const I=await n.validateFields();u(!0),await Re.updateAccessPassword({current_password:((C=I.currentPassword)==null?void 0:C.trim())||void 0,new_password:I.newPassword.trim()}),e.success(s(g?"settings.configTab.accessPassword.updated":"settings.configTab.accessPassword.enabled")),n.resetFields(),await R()}catch(I){if(tn(I))return;const h=I instanceof Error?I.message:s("settings.configTab.accessPassword.updateFailed","Failed to update access password");e.error(h)}finally{u(!1)}};return t.jsx(N,{size:"small",className:"lotus-settings-card",title:t.jsx(mr,{strong:!0,children:s("settings.configTab.accessPasswordTitle")}),children:t.jsxs(L,{direction:"vertical",size:a.marginMD,style:{width:"100%"},children:[t.jsx(qe,{type:g?"info":"warning",showIcon:!0,message:s(g?"settings.configTab.accessPassword.statusEnabled":"settings.configTab.accessPassword.statusDisabled"),description:x}),p?t.jsx(qe,{type:"error",showIcon:!0,message:p}):null,t.jsxs(y,{form:n,layout:"vertical",disabled:r||l,children:[v?t.jsx(y.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(y.Item,{label:s(g?"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(y.Item,{label:s("settings.configTab.accessPassword.confirmPasswordLabel"),name:"confirmPassword",dependencies:["newPassword"],rules:[{required:!0,message:s("settings.configTab.accessPassword.validation.confirmPasswordRequired")},({getFieldValue:C})=>({validator(I,h){return!h||C("newPassword")===h?Promise.resolve():Promise.reject(new Error(s("settings.configTab.accessPassword.validation.passwordMismatch")))}})],children:t.jsx(H.Password,{autoComplete:"new-password"})}),t.jsx(z,{type:"primary",loading:l,onClick:()=>void P(),children:s(g?"settings.configTab.accessPassword.updateAction":"settings.configTab.accessPassword.enableAction")})]})]})})},{Text:Be}=ue,{useToken:fr}=Te,va="http://127.0.0.1:9562/v1",Qt=e=>[...new Set(e.map(s=>s.trim()).filter(s=>s.length>0))].sort(),yr=e=>{var a;const s=(a=e.tools)==null?void 0:a.disabled;return Array.isArray(s)?Qt(s.filter(n=>typeof n=="string")):[]},xr=({msgApi:e,locale:s,onLocaleChange:a})=>{const{t:n}=ae(),{token:r}=fr(),[o,l]=i.useState({http_proxy:"",https_proxy:"",memory:{auto_dream_enabled:!1},subagents:{}}),[u,g]=i.useState(va),[m,c]=i.useState([]),[b,p]=i.useState([]),[S,v]=i.useState([]),[x,R]=i.useState(!1),[P,C]=i.useState(!1),I=i.useCallback(async()=>{var O,Y;R(!0);try{const[G,ne]=await Promise.all([Re.getBambooConfig(),Re.getBambooTools()]);l({http_proxy:G.http_proxy||"",https_proxy:G.https_proxy||"",memory:{auto_dream_enabled:((O=G.memory)==null?void 0:O.auto_dream_enabled)??!1},subagents:{max_concurrent:(Y=G.subagents)==null?void 0:Y.max_concurrent}});const ie=yr(G);p(ie),v(ie),c(Qt(ne.tools||[]))}catch(G){console.error("Failed to load config:",G),e.error(n("settings.configTab.loadConfigFailed"))}finally{R(!1)}},[e,n]);i.useEffect(()=>{I()},[I]);const h=O=>{l(Y=>({...Y,http_proxy:O}))},k=O=>{l(Y=>({...Y,https_proxy:O}))},V=O=>{l(Y=>({...Y,memory:{...Y.memory,auto_dream_enabled:O}}))},F=O=>{l(Y=>({...Y,subagents:{...Y.subagents,max_concurrent:O!==null&&Number.isFinite(O)&&O>0?O:void 0}}))},U=async O=>{var Y,G;R(!0);try{let ne;O==="network"?ne={http_proxy:o.http_proxy,https_proxy:o.https_proxy}:O==="memory"?ne={memory:{auto_dream_enabled:o.memory.auto_dream_enabled}}:ne={subagents:{max_concurrent:o.subagents.max_concurrent}};const ie=await Re.validateBambooConfigPatch(ne);if(!ie.valid){const d=((G=(Y=ie.errors)==null?void 0:Y.proxy)==null?void 0:G[0])??Object.values(ie.errors||{}).flat().filter(Boolean)[0];e.error((d==null?void 0:d.message)||n("settings.configTab.invalidConfig"));return}await Re.setBambooConfig(ne),e.success(n("settings.configTab.saveConfigSuccess"))}catch(ne){console.error("Failed to save config:",ne);const ie=ne instanceof Error&&ne.message.trim()?ne.message:n("settings.configTab.saveConfigFailed");e.error(ie)}finally{R(!1)}},ee=async()=>{e.success(n("settings.configTab.backendSaved"))},$=()=>{g(va),e.success(n("settings.configTab.backendResetDefault"))},j=(O,Y)=>{p(G=>{const ne=new Set(G);return Y?ne.delete(O):ne.add(O),Qt([...ne])})},T=async()=>{C(!0);try{const O=await Re.getBambooTools();c(Qt(O.tools||[])),e.success(n("settings.configTab.toolsReloadSuccess"))}catch(O){console.error("Failed to reload tools:",O),e.error(n("settings.configTab.toolsLoadFailed"))}finally{C(!1)}},D=async()=>{C(!0);try{const O=Qt(b);await Re.setBambooConfig({tools:{disabled:O}}),p(O),v(O),e.success(n("settings.configTab.toolsSaveSuccess"))}catch(O){console.error("Failed to save tool settings:",O),e.error(n("settings.configTab.toolsSaveFailed"))}finally{C(!1)}},A=JSON.stringify(b)!==JSON.stringify(S),Q=new Set(b);return t.jsx(as,{spinning:x,tip:n("settings.common.loading"),children:t.jsx(Ts,{items:[{key:"general",label:n("settings.configTab.tabs.general"),children:t.jsxs(L,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[t.jsx(gr,{httpProxy:o.http_proxy,httpsProxy:o.https_proxy,onHttpProxyChange:h,onHttpsProxyChange:k,onReload:I,onSave:()=>U("network"),isLoading:x}),t.jsx(N,{size:"small",className:"lotus-settings-card",title:t.jsx(Be,{strong:!0,children:n("settings.configTab.language")}),children:t.jsx(te,{value:s,style:{width:260},options:[{label:n("settings.configTab.languageEnglish"),value:"en-US"},{label:n("settings.configTab.languageChinese"),value:"zh-CN"},{label:n("settings.configTab.languageTraditionalChinese"),value:"zh-TW"},{label:n("settings.configTab.languageFrench"),value:"fr-FR"},{label:n("settings.configTab.languageJapanese"),value:"ja-JP"},{label:n("settings.configTab.languageHindi"),value:"hi-IN"}],onChange:O=>a(O)})}),t.jsx(N,{size:"small",className:"lotus-settings-card",title:t.jsx(Be,{strong:!0,children:n("settings.configTab.memoryTitle")}),children:t.jsxs(L,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[t.jsx(Be,{type:"secondary",children:n("settings.configTab.memoryDescription")}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:r.marginMD,flexWrap:"wrap"},children:[t.jsxs("div",{children:[t.jsx(Be,{strong:!0,children:n("settings.configTab.autoDreamEnabled")}),t.jsx("div",{children:t.jsx(Be,{type:"secondary",style:{fontSize:r.fontSizeSM},children:n("settings.configTab.autoDreamEnabledHint")})})]}),t.jsx(fe,{"data-testid":"auto-dream-toggle",checked:o.memory.auto_dream_enabled,onChange:V})]}),t.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:t.jsx(z,{"data-testid":"save-memory-settings",type:"primary",onClick:()=>U("memory"),loading:x,children:n("settings.configTab.save")})})]})}),t.jsx(N,{size:"small",className:"lotus-settings-card",title:t.jsx(Be,{strong:!0,children:n("settings.configTab.subagentsTitle")}),children:t.jsxs(L,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[t.jsx(Be,{type:"secondary",children:n("settings.configTab.subagentsDescription")}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:r.marginMD,flexWrap:"wrap"},children:[t.jsxs("div",{children:[t.jsx(Be,{strong:!0,children:n("settings.configTab.subagentMaxConcurrent")}),t.jsx("div",{children:t.jsx(Be,{type:"secondary",style:{fontSize:r.fontSizeSM},children:n("settings.configTab.subagentMaxConcurrentHint")})})]}),t.jsx(Me,{"data-testid":"subagent-max-concurrent",style:{width:120},min:1,step:1,precision:0,placeholder:"8",value:o.subagents.max_concurrent??null,onChange:O=>F(typeof O=="number"?O:null)})]}),t.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:t.jsx(z,{"data-testid":"save-subagent-settings",type:"primary",onClick:()=>U("subagents"),loading:x,children:n("settings.configTab.save")})})]})}),t.jsx(N,{size:"small",title:t.jsx(Be,{strong:!0,children:n("settings.configTab.backendApiBaseUrlTitle")}),children:t.jsxs(L,{direction:"vertical",size:r.marginSM,style:{width:"100%"},children:[t.jsx(L,{direction:"vertical",size:r.marginXXS,style:{width:"100%"},children:t.jsx(H,{style:{width:"100%"},value:u,onChange:O=>g(O.target.value),placeholder:n("settings.configTab.backendApiPlaceholder")})}),t.jsx(Be,{type:"secondary",style:{fontSize:r.fontSizeSM},children:n("settings.configTab.backendApiHint")}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:r.marginSM},children:[t.jsx(z,{"data-testid":"reset-to-defaults",onClick:$,children:n("settings.configTab.resetToDefault")}),t.jsx(z,{"data-testid":"save-api-settings",type:"primary",onClick:ee,children:n("settings.configTab.save")})]})]})}),t.jsx(hr,{msgApi:e})]})},{key:"tools",label:n("settings.configTab.tabs.tools"),children:t.jsx(N,{size:"small",title:t.jsx(Be,{strong:!0,children:n("settings.configTab.toolsTitle")}),children:t.jsxs(L,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[t.jsx(Be,{type:"secondary",children:n("settings.configTab.toolsDescription")}),m.length===0?t.jsx(qe,{type:"info",showIcon:!0,message:n("settings.configTab.toolsEmpty")}):t.jsx(Xe,{bordered:!0,dataSource:m,renderItem:O=>t.jsx(Xe.Item,{actions:[t.jsx(fe,{checked:!Q.has(O),onChange:Y=>j(O,Y)},`${O}-switch`)],children:t.jsx(Be,{code:!0,children:O})})}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:r.marginSM},children:[t.jsx(z,{onClick:T,loading:P,children:n("settings.configTab.reloadTools")}),t.jsx(z,{type:"primary",onClick:D,loading:P,disabled:!A,children:n("settings.configTab.save")})]})]})})}]})})},{Title:br,Text:Ls}=ue,{useToken:vr}=Te,jr=()=>{const{t:e}=ae(),{token:s}=vr(),a=vn(),n=jn(),r=Tn(),[o]=y.useForm(),l=ca.useRef(a);ca.useEffect(()=>{l.current!==a&&(o.setFieldsValue(a),l.current=a)},[a,o]);const u=m=>{l.current={...l.current,...m},n(m)},g=()=>{r(),o.resetFields()};return t.jsxs("div",{style:{padding:"24px",maxWidth:"1200px",margin:"0 auto"},children:[t.jsx(br,{level:3,style:{marginBottom:"8px"},children:e("settings.mermaidTab.title")}),t.jsx(Ls,{type:"secondary",style:{display:"block",marginBottom:"24px"},children:e("settings.mermaidTab.description")}),t.jsxs(y,{form:o,layout:"vertical",initialValues:a,onValuesChange:u,children:[t.jsxs(N,{title:e("settings.mermaidTab.themeCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:[t.jsx(Je,{gutter:16,children:t.jsx(me,{span:24,children:t.jsx(y.Item,{name:"theme",label:t.jsxs(L,{children:[e("settings.mermaidTab.themeLabel"),t.jsx(ke,{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(Ls,{type:"secondary",style:{display:"block",marginTop:"8px"},children:[t.jsx("strong",{children:e("settings.mermaidTab.themeDescriptionsTitle")}),t.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.default"),t.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.neutral"),t.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.dark"),t.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.forest"),t.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.base")]})]}),t.jsxs(N,{title:e("settings.mermaidTab.globalCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:[t.jsxs(Je,{gutter:16,children:[t.jsx(me,{span:12,children:t.jsx(y.Item,{name:"fontSize",label:t.jsxs(L,{children:[e("settings.mermaidTab.fontSizeLabel"),t.jsx(ke,{title:e("settings.mermaidTab.fontSizeTooltip"),children:t.jsx(Ue,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:10,max:32,step:1,style:{width:"100%"},addonAfter:"px"})})}),t.jsx(me,{span:12,children:t.jsx(y.Item,{name:"defaultScale",label:t.jsxs(L,{children:[e("settings.mermaidTab.defaultZoomLabel"),t.jsx(ke,{title:e("settings.mermaidTab.defaultZoomTooltip"),children:t.jsx(Ue,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:.1,max:3,step:.1,style:{width:"100%"}})})})]}),t.jsx(y.Item,{name:"useMaxWidth",label:t.jsxs(L,{children:[e("settings.mermaidTab.responsiveWidthLabel"),t.jsx(ke,{title:e("settings.mermaidTab.responsiveWidthTooltip"),children:t.jsx(Ue,{style:{color:s.colorTextSecondary}})})]}),valuePropName:"checked",children:t.jsx(fe,{})})]}),t.jsx(N,{title:e("settings.mermaidTab.flowchartCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsxs(Je,{gutter:16,children:[t.jsx(me,{span:8,children:t.jsx(y.Item,{name:"flowchartNodeSpacing",label:t.jsxs(L,{children:[e("settings.mermaidTab.flowchartNodeSpacingLabel"),t.jsx(ke,{title:e("settings.mermaidTab.flowchartNodeSpacingTooltip"),children:t.jsx(Ue,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:20,max:200,step:10,style:{width:"100%"}})})}),t.jsx(me,{span:8,children:t.jsx(y.Item,{name:"flowchartRankSpacing",label:t.jsxs(L,{children:[e("settings.mermaidTab.flowchartRankSpacingLabel"),t.jsx(ke,{title:e("settings.mermaidTab.flowchartRankSpacingTooltip"),children:t.jsx(Ue,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:20,max:200,step:10,style:{width:"100%"}})})}),t.jsx(me,{span:8,children:t.jsx(y.Item,{name:"flowchartCurve",label:t.jsxs(L,{children:[e("settings.mermaidTab.flowchartCurveTypeLabel"),t.jsx(ke,{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(N,{title:e("settings.mermaidTab.sequenceCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsxs(Je,{gutter:16,children:[t.jsx(me,{span:6,children:t.jsx(y.Item,{name:"sequenceActorMargin",label:t.jsxs(L,{children:[e("settings.mermaidTab.sequenceActorMarginLabel"),t.jsx(ke,{title:e("settings.mermaidTab.sequenceActorMarginTooltip"),children:t.jsx(Ue,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:20,max:200,step:10,style:{width:"100%"}})})}),t.jsx(me,{span:6,children:t.jsx(y.Item,{name:"sequenceMessageMargin",label:t.jsxs(L,{children:[e("settings.mermaidTab.sequenceMessageMarginLabel"),t.jsx(ke,{title:e("settings.mermaidTab.sequenceMessageMarginTooltip"),children:t.jsx(Ue,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:10,max:100,step:5,style:{width:"100%"}})})}),t.jsx(me,{span:6,children:t.jsx(y.Item,{name:"sequenceWidth",label:t.jsxs(L,{children:[e("settings.mermaidTab.sequenceActorWidthLabel"),t.jsx(ke,{title:e("settings.mermaidTab.sequenceActorWidthTooltip"),children:t.jsx(Ue,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:100,max:300,step:10,style:{width:"100%"}})})}),t.jsx(me,{span:6,children:t.jsx(y.Item,{name:"sequenceHeight",label:t.jsxs(L,{children:[e("settings.mermaidTab.sequenceActorHeightLabel"),t.jsx(ke,{title:e("settings.mermaidTab.sequenceActorHeightTooltip"),children:t.jsx(Ue,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:40,max:150,step:5,style:{width:"100%"}})})})]})}),t.jsx(N,{title:e("settings.mermaidTab.ganttCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsxs(Je,{gutter:16,children:[t.jsx(me,{span:12,children:t.jsx(y.Item,{name:"ganttBarHeight",label:t.jsxs(L,{children:[e("settings.mermaidTab.ganttBarHeightLabel"),t.jsx(ke,{title:e("settings.mermaidTab.ganttBarHeightTooltip"),children:t.jsx(Ue,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:10,max:50,step:5,style:{width:"100%"},addonAfter:"px"})})}),t.jsx(me,{span:12,children:t.jsx(y.Item,{name:"ganttTopPadding",label:t.jsxs(L,{children:[e("settings.mermaidTab.ganttTopPaddingLabel"),t.jsx(ke,{title:e("settings.mermaidTab.ganttTopPaddingTooltip"),children:t.jsx(Ue,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:20,max:100,step:10,style:{width:"100%"}})})})]})}),t.jsx(L,{children:t.jsx(z,{icon:t.jsx(On,{}),onClick:g,children:e("settings.mermaidTab.resetToDefaults")})}),t.jsx(Le,{}),t.jsx(N,{title:e("settings.mermaidTab.previewTitle"),styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsx(Ls,{type:"secondary",children:e("settings.mermaidTab.previewDescription")})})]})]})},Tr=i.lazy(()=>Qs(()=>import("./index-Cur8quEC.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8]),import.meta.url)),{Text:jt}=ue,{useToken:_r}=Te,Sr=({promptEnhancement:e,onPromptEnhancementChange:s,mermaidEnhancementEnabled:a,taskEnhancementEnabled:n,showCopilotConclusionWithOptionsEnhancement:r,copilotConclusionWithOptionsEnhancementEnabled:o,onMermaidToggle:l,onTaskToggle:u,onCopilotConclusionWithOptionsToggle:g,onSaveEnhancement:m})=>{const{t:c}=ae(),{token:b}=_r(),p=b.marginLG;return t.jsxs(X,{vertical:!0,gap:p,children:[t.jsx(N,{size:"small",className:"lotus-settings-card",children:t.jsx(i.Suspense,{fallback:t.jsx(as,{size:"small"}),children:t.jsx(Tr,{})})}),t.jsx(N,{size:"small",className:"lotus-settings-card",children:t.jsxs(L,{direction:"vertical",size:b.marginXS,style:{width:"100%"},children:[t.jsx(jt,{strong:!0,children:c("settings.promptsTab.title")}),t.jsxs(X,{align:"center",gap:b.marginSM,children:[t.jsx(jt,{strong:!0,children:c("settings.promptsTab.mermaidEnhancement")}),t.jsx(fe,{checked:a,onChange:l})]}),t.jsxs(X,{align:"center",gap:b.marginSM,children:[t.jsx(jt,{strong:!0,children:c("settings.promptsTab.taskListRules")}),t.jsx(fe,{checked:n,onChange:u})]}),r&&t.jsxs(L,{direction:"vertical",size:b.marginXXS,style:{width:"100%"},children:[t.jsxs(X,{align:"center",gap:b.marginSM,children:[t.jsx(jt,{strong:!0,children:c("settings.promptsTab.copilotConclusionWithOptionsBeforeFinish")}),t.jsx(fe,{checked:o,onChange:g})]}),t.jsx(jt,{type:"secondary",style:{fontSize:b.fontSizeSM},children:c("settings.promptsTab.copilotConclusionWithOptionsBeforeFinishDescription",{defaultValue:_n()})})]}),t.jsx(H.TextArea,{rows:6,placeholder:c("settings.promptsTab.enhancementPlaceholder"),value:e,onChange:S=>s(S.target.value)}),t.jsx(X,{justify:"flex-end",children:t.jsx(z,{type:"primary",onClick:m,children:c("settings.promptsTab.saveEnhancement")})}),t.jsx(jt,{type:"secondary",style:{fontSize:b.fontSizeSM},children:c("settings.promptsTab.description")})]})}),a&&t.jsx(ks,{size:"small",items:[{key:"mermaid",label:t.jsx(jt,{strong:!0,children:c("settings.mermaidTab.title")}),children:t.jsx(jr,{})}]})]})},{Text:pt}=ue,{useToken:kr}=Te,wr=({themeMode:e,onThemeModeChange:s,vdiSafeMode:a,onVdiSafeModeToggle:n,onClearLocalStorage:r,onResetApp:o,isResetting:l,darkModeKey:u})=>{const{t:g}=ae(),{token:m}=kr();return t.jsx(N,{size:"small",className:"lotus-settings-card",children:t.jsxs(L,{direction:"vertical",size:m.marginSM,style:{width:"100%"},children:[t.jsxs(X,{align:"center",justify:"space-between",gap:m.marginSM,children:[t.jsx(pt,{strong:!0,children:g("settings.appTab.runningVersion","Running version")}),t.jsxs(pt,{code:!0,"data-testid":"settings-app-version",children:["v",Xa]})]}),t.jsx(pt,{type:"secondary",style:{fontSize:m.fontSizeSM},children:g("settings.appTab.runningVersionDesc","This is the currently running Lotus frontend version.")}),t.jsxs(X,{align:"center",gap:m.marginSM,children:[t.jsx(pt,{strong:!0,children:g("settings.appTab.darkMode")}),t.jsx(fe,{"data-testid":"dark-mode-toggle",checked:e==="dark",onChange:c=>{const b=c?"dark":"light";s(b),localStorage.setItem(u,b)}})]}),t.jsxs(X,{align:"center",gap:m.marginSM,children:[t.jsx(pt,{strong:!0,children:g("settings.appTab.vdiSafeMode","Graphics compatibility mode")}),t.jsx(fe,{"data-testid":"vdi-safe-mode-toggle",checked:a,onChange:n})]}),t.jsx(pt,{type:"secondary",style:{fontSize:m.fontSizeSM},children:g("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(Nn,{}),onClick:()=>{sr(),window.location.reload()},children:g("settings.appTab.resetStepReplayGuide")}),t.jsx(Rt,{title:g("settings.appTab.clearLocalStorageTitle"),description:g("settings.appTab.clearLocalStorageDescription"),onConfirm:r,okText:g("settings.appTab.confirmClear"),cancelText:g("settings.appTab.cancel"),placement:"top",children:t.jsx(z,{danger:!0,block:!0,icon:t.jsx(Et,{}),children:g("settings.appTab.clearLocalStorageButton")})}),t.jsx(Le,{style:{margin:`${m.marginSM}px 0`}}),t.jsxs(X,{align:"center",gap:m.marginSM,children:[t.jsx(Vn,{style:{color:m.colorError}}),t.jsx(pt,{strong:!0,style:{color:m.colorError},children:g("settings.appTab.dangerZone")})]}),t.jsx(pt,{type:"secondary",style:{fontSize:m.fontSizeSM},children:g("settings.appTab.dangerDescription")}),t.jsx(Rt,{title:g("settings.appTab.resetApplicationTitle"),description:t.jsxs("div",{children:[t.jsx("p",{children:g("settings.appTab.resetApplicationIntro")}),t.jsxs("ul",{style:{margin:0,paddingLeft:16},children:[t.jsx("li",{children:g("settings.appTab.resetStepDeleteAllSessions")}),t.jsx("li",{children:g("settings.appTab.resetStepClearStorage")}),t.jsx("li",{children:g("settings.appTab.resetStepResetConfig")}),t.jsx("li",{children:g("settings.appTab.resetStepSetupFlow")}),t.jsx("li",{children:g("settings.appTab.resetStepReload")})]})]}),onConfirm:o,okText:g("settings.appTab.resetConfirm"),cancelText:g("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($n,{}),loading:l,children:g("settings.appTab.resetButton")})})]})})},{Text:Tt}=ue,{useToken:Cr}=Te,ja=[{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,}"}],Mr=(e,s,a)=>{if(!s)return{masked:e};if(a==="exact")return{masked:e.split(s).join("[MASKED]")};try{const n=new RegExp(s,"g");return{masked:e.replace(n,"[MASKED]")}}catch(n){return{masked:e,error:n instanceof Error?n.message:oe.t("settings.keywordMaskingTab.invalidRegexPattern")}}},Er=()=>{const{t:e}=ae(),{message:s}=ut.useApp(),{token:a}=Cr(),[n,r]=i.useState([]),[o,l]=i.useState(!1),[u,g]=i.useState(null),[m,c]=i.useState(""),[b,p]=i.useState("exact"),[S,v]=i.useState(!0),[x,R]=i.useState(),[P,C]=i.useState("My token is sk-123"),I=i.useCallback(async()=>{try{l(!0);const D=await it.getInstance().getKeywordMaskingConfig();r(D.entries)}catch(T){s.error(e("settings.keywordMaskingTab.loadFailed")),console.error(T)}finally{l(!1)}},[s,e]);i.useEffect(()=>{I()},[I]);const h=async T=>{try{const D=it.getInstance(),A=await D.validateKeywordEntries(T);if(!A.valid&&A.errors){const O=A.errors.map(Y=>`Entry ${Y.index+1}: ${Y.message}`).join("; ");return s.error(`${e("settings.keywordMaskingTab.validationFailedPrefix")}: ${O}`),!1}const Q=await D.updateKeywordMaskingConfig(T);return r(Q.entries),s.success(e("settings.keywordMaskingTab.saveSuccess")),!0}catch(D){return s.error(D instanceof Error?D.message:e("settings.keywordMaskingTab.saveFailed")),!1}},k=async()=>{const T={pattern:"",match_type:"exact",enabled:!0},D=[...n,T];r(D),g(D.length-1),c(""),p("exact"),v(!0),R(void 0)},V=T=>{const D=n[T];g(T),c(D.pattern),p(D.match_type),v(D.enabled),R(void 0)},F=async()=>{if(u===null)return;if(!m.trim()){s.error(e("settings.keywordMaskingTab.patternRequired"));return}const T=[...n];T[u]={pattern:m.trim(),match_type:b,enabled:S},await h(T)&&g(null)},U=()=>{var T;u!==null&&!((T=n[u])!=null&&T.pattern)&&r(n.filter((D,A)=>A!==u)),g(null)},ee=async T=>{const D=n.filter((A,Q)=>Q!==T);await h(D)},$=async(T,D)=>{const A=[...n];A[T]={...A[T],enabled:D},await h(A)},j=Mr(P,m,b);return t.jsx(N,{className:"lotus-settings-card",title:e("settings.keywordMaskingTab.title"),extra:t.jsx(z,{"data-testid":"add-keyword",type:"primary",icon:t.jsx(dt,{}),onClick:k,loading:o,children:e("settings.keywordMaskingTab.addKeyword")}),children:t.jsxs(L,{direction:"vertical",style:{width:"100%"},size:"large",children:[t.jsx(Tt,{type:"secondary",children:e("settings.keywordMaskingTab.description")}),t.jsx(Xe,{loading:o,dataSource:n,locale:{emptyText:e("settings.keywordMaskingTab.empty")},renderItem:(T,D)=>t.jsx(Xe.Item,{style:{backgroundColor:a.colorFillAlter,marginBottom:8,borderRadius:a.borderRadius,padding:12},actions:u===D?[t.jsx(z,{"data-testid":"save-keyword",type:"primary",icon:t.jsx(ws,{}),onClick:F,"aria-label":e("settings.keywordMaskingTab.save")},"save"),t.jsx(z,{onClick:U,children:e("settings.keywordMaskingTab.cancel")},"cancel")]:[t.jsx(z,{icon:t.jsx(is,{}),onClick:()=>V(D),"aria-label":e("settings.keywordMaskingTab.edit")},"edit"),t.jsx(z,{"data-testid":`delete-keyword-${D}`,danger:!0,icon:t.jsx(Et,{}),onClick:()=>ee(D),"aria-label":e("settings.keywordMaskingTab.delete")},"delete")],children:t.jsx(X,{vertical:!0,style:{width:"100%"},gap:8,children:u===D?t.jsxs(t.Fragment,{children:[t.jsx(H,{"data-testid":"keyword-pattern-input",placeholder:e("settings.keywordMaskingTab.patternPlaceholder"),value:m,onChange:A=>c(A.target.value),autoFocus:!0}),t.jsxs(X,{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:x,onChange:A=>{R(A);const Q=ja.find(O=>O.value===A);Q&&(c(Q.pattern),p(Q.match_type))},options:ja.map(A=>({value:A.value,label:e(A.labelKey)})),style:{minWidth:220}}),t.jsx(te,{value:b,onChange:p,options:[{value:"exact",label:e("settings.keywordMaskingTab.exactMatch")},{value:"regex",label:e("settings.keywordMaskingTab.regexPattern")}],style:{width:150}}),t.jsx(fe,{checked:S,onChange:v})]}),t.jsxs(X,{vertical:!0,gap:6,children:[t.jsx(Tt,{type:"secondary",children:e("settings.keywordMaskingTab.sampleText")}),t.jsx(H,{placeholder:e("settings.keywordMaskingTab.sampleTextPlaceholder"),value:P,onChange:A=>C(A.target.value)}),t.jsx(Tt,{type:"secondary",children:e("settings.keywordMaskingTab.maskedPreview")}),t.jsx(H,{readOnly:!0,value:j.masked,status:j.error?"error":void 0}),j.error&&t.jsx(Tt,{type:"danger",children:j.error})]})]}):t.jsxs(X,{justify:"space-between",align:"center",children:[t.jsxs(X,{vertical:!0,gap:4,children:[t.jsx(Tt,{strong:!0,children:T.pattern||e("settings.keywordMaskingTab.emptyPattern")}),t.jsxs(X,{gap:8,children:[t.jsx(Tt,{type:"secondary",style:{fontSize:12},children:T.match_type==="regex"?e("settings.keywordMaskingTab.regexPattern"):e("settings.keywordMaskingTab.exactMatch")}),!T.enabled&&t.jsx(Tt,{type:"warning",style:{fontSize:12},children:e("settings.keywordMaskingTab.disabled")})]})]}),t.jsx(fe,{checked:T.enabled,onChange:A=>$(D,A),size:"small"})]})})})})]})})},{Text:Ta,Paragraph:Pr}=ue,Dr=["Bash(rm -rf *)","Bash(git push *)","Bash(sudo *)","Write(/etc/**)"],Ir=()=>{const{t:e}=ae(),{message:s}=ut.useApp(),[a,n]=i.useState([]),[r,o]=i.useState(""),[l,u]=i.useState(!1),[g,m]=i.useState(!1),c=i.useCallback(async()=>{try{u(!0),n(await de.getPermissionAskRules())}catch(v){s.error(e("settings.permissionsTab.loadFailed")),console.error(v)}finally{u(!1)}},[s,e]);i.useEffect(()=>{c()},[c]);const b=i.useCallback(async v=>{try{m(!0);const x=await de.updatePermissionAskRules(v);return n(x),s.success(e("settings.permissionsTab.saveSuccess")),!0}catch(x){return s.error(x instanceof Error?x.message:e("settings.permissionsTab.saveFailed")),!1}finally{m(!1)}},[s,e]),p=i.useCallback(async v=>{const x=v.trim();if(!x)return;if(a.includes(x)){s.info(e("settings.permissionsTab.duplicate"));return}await b([...a,x])&&o("")},[a,b,s,e]),S=i.useCallback(v=>b(a.filter(x=>x!==v)),[a,b]);return t.jsx(N,{className:"lotus-settings-card",title:e("settings.permissionsTab.title"),extra:t.jsx(z,{type:"primary",icon:t.jsx(dt,{}),loading:g,disabled:!r.trim(),onClick:()=>void p(r),children:e("settings.permissionsTab.add")}),children:t.jsxs(L,{direction:"vertical",style:{width:"100%"},size:"large",children:[t.jsx(Pr,{type:"secondary",style:{marginBottom:0},children:e("settings.permissionsTab.description")}),t.jsx(H,{value:r,onChange:v=>o(v.target.value),onPressEnter:()=>void p(r),placeholder:e("settings.permissionsTab.placeholder"),allowClear:!0}),t.jsxs(X,{gap:8,wrap:"wrap",align:"center",children:[t.jsx(Ta,{type:"secondary",style:{fontSize:12},children:e("settings.permissionsTab.examples")}),Dr.map(v=>t.jsx(re.CheckableTag,{checked:a.includes(v),onChange:()=>{a.includes(v)||p(v)},children:v},v))]}),t.jsx(Xe,{loading:l,dataSource:a,locale:{emptyText:e("settings.permissionsTab.empty")},renderItem:v=>t.jsx(Xe.Item,{actions:[t.jsx(z,{danger:!0,size:"small",icon:t.jsx(Et,{}),loading:g,onClick:()=>void S(v),"aria-label":e("settings.permissionsTab.remove")},"delete")],children:t.jsx(Ta,{code:!0,children:v})})})]})})},{Text:Pt,Paragraph:Fr}=ue,Ar=/^[A-Za-z_][A-Za-z0-9_]*$/,Rr=()=>{const{t:e}=ae(),{message:s}=ut.useApp(),[a,n]=i.useState([]),[r,o]=i.useState(!1),[l,u]=i.useState(!1),[g,m]=i.useState(null),[c]=y.useForm(),b=i.useCallback(async()=>{o(!0);try{const C=await de.getEnvVars();n(C.entries)}catch{s.error(e("settings.envVars.fetchError","Failed to load environment variables"))}finally{o(!1)}},[s,e]);i.useEffect(()=>{b()},[b]);const p=async C=>{var h;const I={name:C.name.trim(),value:C.value,secret:C.secret??!1,description:((h=C.description)==null?void 0:h.trim())||void 0};try{const k=await de.upsertEnvVar(I);n(k.entries),s.success(g?e("settings.envVars.updated","Variable updated"):e("settings.envVars.created","Variable created")),R()}catch(k){s.error((k instanceof Error?k.message:void 0)||e("settings.envVars.saveError","Failed to save variable"))}},S=async C=>{try{const I=await de.deleteEnvVar(C);n(I.entries),s.success(e("settings.envVars.deleted","Variable deleted"))}catch(I){s.error((I instanceof Error?I.message:void 0)||e("settings.envVars.deleteError","Failed to delete variable"))}},v=()=>{m(null),c.resetFields(),c.setFieldsValue({secret:!1}),u(!0)},x=C=>{m(C.name),c.setFieldsValue({name:C.name,value:"",secret:C.secret,description:C.description??""}),u(!0)},R=()=>{u(!1),m(null),c.resetFields()},P=[{title:e("settings.envVars.name","Name"),dataIndex:"name",key:"name",render:C=>t.jsx(Pt,{code:!0,children:C})},{title:e("settings.envVars.value","Value"),dataIndex:"value",key:"value",render:(C,I)=>I.secret?t.jsxs(Pt,{type:"secondary",children:[t.jsx(fa,{style:{marginRight:4}}),I.has_value?"••••••••":e("settings.envVars.notSet","(not set)")]}):t.jsx(Pt,{children:C||t.jsx(Pt,{type:"secondary",children:e("settings.envVars.empty","(empty)")})})},{title:e("settings.envVars.type","Type"),key:"secret",width:100,render:(C,I)=>I.secret?t.jsx(re,{color:"warning",icon:t.jsx(fa,{}),children:e("settings.envVars.secret","Secret")}):t.jsx(re,{color:"processing",children:e("settings.envVars.plain","Plain")})},{title:e("settings.envVars.descriptionCol","Description"),dataIndex:"description",key:"description",ellipsis:!0,render:C=>C?t.jsx(Pt,{type:"secondary",children:C}):t.jsx(Pt,{type:"secondary",italic:!0,children:"—"})},{title:e("settings.envVars.actions","Actions"),key:"actions",width:120,render:(C,I)=>t.jsxs(L,{size:"small",children:[t.jsx(z,{type:"text",size:"small",icon:t.jsx(is,{}),onClick:()=>x(I),"aria-label":e("settings.envVars.edit","Edit")}),t.jsx(Rt,{title:e("settings.envVars.deleteConfirm","Delete this variable?"),onConfirm:()=>S(I.name),okText:e("settings.envVars.yes","Yes"),cancelText:e("settings.envVars.no","No"),children:t.jsx(z,{type:"text",size:"small",danger:!0,icon:t.jsx(Et,{}),"aria-label":e("settings.envVars.delete","Delete")})})]})}];return t.jsxs("div",{style:{maxWidth:900},children:[t.jsxs(N,{className:"lotus-settings-card",title:e("settings.envVars.title","Environment Variables"),extra:t.jsx(z,{type:"primary",icon:t.jsx(dt,{}),onClick:v,children:e("settings.envVars.addButton","Add Variable")}),children:[t.jsx(Fr,{type:"secondary",style:{marginBottom:16},children:e("settings.envVars.description","Variables are injected into Bash tool processes. Secret variables are encrypted at rest.")}),t.jsx(at,{dataSource:a,columns:P,rowKey:"name",size:"small",pagination:!1,loading:r,locale:{emptyText:e("settings.envVars.noVars","No environment variables configured")}})]}),t.jsx(Qe,{title:g?e("settings.envVars.editTitle","Edit Variable"):e("settings.envVars.addTitle","Add Environment Variable"),open:l,onCancel:R,onOk:()=>c.submit(),okText:e("settings.envVars.save","Save"),cancelText:e("settings.envVars.cancel","Cancel"),destroyOnClose:!0,children:t.jsxs(y,{form:c,layout:"vertical",onFinish:p,initialValues:{secret:!1},children:[t.jsx(y.Item,{name:"name",label:e("settings.envVars.name","Name"),rules:[{required:!0,message:e("settings.envVars.nameRequired","Variable name is required")},{pattern:Ar,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:g!==null,autoFocus:g===null})}),t.jsx(y.Item,{name:"value",label:e("settings.envVars.value","Value"),rules:[{required:g===null,message:e("settings.envVars.valueRequired","Value is required for new variables")}],extra:g?e("settings.envVars.valueEditHint","Leave empty to keep the existing value"):void 0,children:t.jsx(H.Password,{placeholder:g?e("settings.envVars.valuePlaceholderEdit","Enter new value or leave empty"):e("settings.envVars.valuePlaceholder","Enter value"),visibilityToggle:!0})}),t.jsx(y.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(fe,{})}),t.jsx(y.Item,{name:"description",label:e("settings.envVars.descriptionField","Description"),children:t.jsx(H,{placeholder:e("settings.envVars.descriptionPlaceholder","Optional description")})})]})})]})},{Text:Ut,Paragraph:zr}=ue,Os="****...****",Lr={not_deployed:"default",deploying:"processing",running:"success",unreachable:"warning",stopped:"default",failed:"error"},Or=e=>{if(!e)return"";const s=new Date(e).getTime();if(Number.isNaN(s))return"";const a=Math.max(0,Math.floor((Date.now()-s)/1e3));if(a<60)return`${a}s ago`;const n=Math.floor(a/60);if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`},Nr=3e4,Vr=()=>{const{t:e}=ae(),{message:s}=ut.useApp(),[a,n]=i.useState([]),[r,o]=i.useState([]),[l,u]=i.useState(!1),[g,m]=i.useState(!1),[c,b]=i.useState(null),[p]=y.useForm(),[S,v]=i.useState(!1),[x,R]=i.useState(null),[P,C]=i.useState(""),[I,h]=i.useState(!1),k=y.useWatch("placement_type",p),V=y.useWatch("auth_method",p),F=i.useRef(0),U=i.useCallback(async(d=!1)=>{const E=++F.current;d||u(!0);try{const M=await de.listNodes();if(E!==F.current)return;n(M.nodes),o(M.clusters)}catch{d||s.error(e("settings.clusters.fetchError","Failed to load clusters"))}finally{d||u(!1)}},[s,e]);i.useEffect(()=>{U()},[U]),i.useEffect(()=>{const d=()=>{document.visibilityState==="visible"&&!g&&!S&&U(!0)},E=window.setInterval(d,Nr);return document.addEventListener("visibilitychange",d),()=>{window.clearInterval(E),document.removeEventListener("visibilitychange",d)}},[U,g,S]);const ee=i.useMemo(()=>{const d=new Map;for(const E of r)for(const M of E.node_ids)d.has(M)||d.set(M,E.name);return d},[r]),$=()=>{b(null),p.resetFields(),p.setFieldsValue({placement_type:"ssh",port:22,auth_method:"password",enabled:!0}),m(!0)},j=d=>{var K,se,pe;b(d.id);const M=d.placement.type==="ssh"?d.placement:void 0;p.setFieldsValue({label:d.label,placement_type:d.placement.type,host:M==null?void 0:M.host,port:(M==null?void 0:M.port)??22,username:M==null?void 0:M.username,auth_method:(M==null?void 0:M.auth.method)??"password",password:"",private_key:"",private_key_path:(M==null?void 0:M.auth.method)==="private_key"?M.auth.private_key_path:void 0,passphrase:"",artifact_path:(K=d.deploy)==null?void 0:K.artifact_path,default_role:(se=d.deploy)==null?void 0:se.default_role,auto_recover:((pe=d.deploy)==null?void 0:pe.auto_recover)??!1,cluster_name:(()=>{const ye=ee.get(d.id);return ye?[ye]:[]})(),enabled:d.enabled}),m(!0)},T=()=>{m(!1),b(null),p.resetFields()},D=d=>{var pe,ye;if(d.placement_type==="local")return{type:"local"};const E=c?a.find(je=>je.id===c):void 0,M=(E==null?void 0:E.placement.type)==="ssh"?E.placement.auth:void 0,K=(je,B)=>!!je&&!B;let se;if(d.auth_method==="system_ssh_config")se={method:"system_ssh_config"};else if(d.auth_method==="private_key"){const je=(M==null?void 0:M.method)==="private_key"?M.private_key:void 0,B=(M==null?void 0:M.method)==="private_key"?M.passphrase:void 0;se={method:"private_key",private_key:K(je,d.private_key)?Os:d.private_key||void 0,private_key_path:d.private_key_path||void 0,passphrase:K(B,d.passphrase)?Os:d.passphrase||void 0}}else{const je=(M==null?void 0:M.method)==="password"?M.password:void 0;se={method:"password",password:K(je,d.password)?Os:d.password}}return{type:"ssh",host:((pe=d.host)==null?void 0:pe.trim())??"",port:d.port??22,username:((ye=d.username)==null?void 0:ye.trim())??"",auth:se}},A=async d=>{var M,K;const E={label:d.label.trim(),placement:D(d),enabled:d.enabled??!0,deploy:{artifact_path:((M=d.artifact_path)==null?void 0:M.trim())||void 0,default_role:((K=d.default_role)==null?void 0:K.trim())||void 0,auto_recover:d.auto_recover??!1}};try{const se=c?await de.updateNode(c,E):await de.createNode(E),pe=Array.isArray(d.cluster_name)?d.cluster_name[0]:d.cluster_name;try{await Q(se.id,pe)}catch(ye){s.warning((ye instanceof Error?ye.message:void 0)||e("settings.clusters.membershipError","Node saved, but updating cluster membership failed")),T(),U();return}s.success(c?e("settings.clusters.updated","Node updated"):e("settings.clusters.created","Node created")),T(),U()}catch(se){s.error((se instanceof Error?se.message:void 0)||e("settings.clusters.saveError","Failed to save node"))}},Q=async(d,E)=>{const M=E==null?void 0:E.trim();for(const se of r){const pe=se.name===M,ye=se.node_ids.includes(d);!pe&&ye&&await de.updateCluster(se.name,{name:se.name,description:se.description,node_ids:se.node_ids.filter(je=>je!==d)})}if(!M)return;const K=r.find(se=>se.name===M);K?K.node_ids.includes(d)||await de.updateCluster(M,{name:M,description:K.description,node_ids:[...K.node_ids,d]}):await de.createCluster({name:M,node_ids:[d]})},O=async d=>{try{await de.deleteNode(d),s.success(e("settings.clusters.deleted","Node deleted")),U()}catch(E){s.error((E instanceof Error?E.message:void 0)||e("settings.clusters.deleteError","Failed to delete node"))}},Y=async(d,E)=>{try{const M=await de.nodeAction(d,E),K=E==="test"&&M&&typeof M=="object"&&"preflight"in M?String(M.preflight??""):"";s.success(K?e("settings.clusters.testOk","Reachable: {{info}}",{info:K}):e("settings.clusters.actionOk","Action triggered")),U()}catch(M){s.error((M instanceof Error?M.message:void 0)||e("settings.clusters.actionFailed","Action failed"))}},G=async d=>{R(d),v(!0),h(!0),C("");try{const E=await de.nodeLogs(d.id,200);C(E.logs||e("settings.clusters.logsEmpty","(no log output yet)"))}catch(E){C((E instanceof Error?E.message:void 0)||e("settings.clusters.logsError","Failed to read logs"))}finally{h(!1)}},ne=[{title:e("settings.clusters.label","Label"),dataIndex:"label",key:"label",render:(d,E)=>t.jsxs(L,{children:[t.jsx(Bn,{}),t.jsx(Ut,{strong:!0,children:d}),!E.enabled&&t.jsx(re,{children:e("settings.clusters.disabled","disabled")})]})},{title:e("settings.clusters.target","Target"),key:"target",render:(d,E)=>E.placement.type==="ssh"?t.jsxs(Ut,{code:!0,children:[E.placement.username,"@",E.placement.host,":",E.placement.port]}):t.jsx(re,{color:"blue",children:e("settings.clusters.local","local")})},{title:e("settings.clusters.cluster","Cluster"),key:"cluster",render:(d,E)=>{const M=ee.get(E.id);return M?t.jsx(re,{children:M}):t.jsx(Ut,{type:"secondary",children:"—"})}},{title:e("settings.clusters.status","Status"),key:"status",render:(d,E)=>{var ye,je,B;const M=((ye=E.state)==null?void 0:ye.status)??"not_deployed",K=(je=E.state)==null?void 0:je.last_error,se=Or((B=E.state)==null?void 0:B.last_health),pe=t.jsx(re,{color:Lr[M],children:M.replace(/_/g," ")});return t.jsxs(L,{direction:"vertical",size:0,children:[K&&(M==="unreachable"||M==="failed")?t.jsx(ke,{title:K,children:pe}):pe,se&&t.jsx(Ut,{type:"secondary",style:{fontSize:11},children:e("settings.clusters.lastSeen","seen {{ago}}",{ago:se})})]})}},{title:e("settings.clusters.actions","Actions"),key:"actions",width:320,render:(d,E)=>t.jsxs(L,{size:"small",wrap:!0,children:[t.jsx(z,{size:"small",onClick:()=>Y(E.id,"test"),children:e("settings.clusters.test","Test")}),t.jsx(z,{size:"small",type:"primary",ghost:!0,onClick:()=>Y(E.id,"deploy"),children:e("settings.clusters.deploy","Deploy")}),t.jsx(z,{size:"small",onClick:()=>Y(E.id,"stop"),children:e("settings.clusters.stop","Stop")}),t.jsx(z,{size:"small",onClick:()=>G(E),children:e("settings.clusters.logs","Logs")}),t.jsx(z,{type:"text",size:"small",icon:t.jsx(is,{}),onClick:()=>j(E),"aria-label":e("settings.clusters.edit","Edit")}),t.jsx(Rt,{title:e("settings.clusters.deleteConfirm","Delete this node?"),onConfirm:()=>O(E.id),okText:e("settings.clusters.yes","Yes"),cancelText:e("settings.clusters.no","No"),children:t.jsx(z,{type:"text",size:"small",danger:!0,icon:t.jsx(Et,{}),"aria-label":e("settings.clusters.delete","Delete")})})]})}],ie=k!=="local",be=c?a.find(d=>d.id===c):void 0;return t.jsxs("div",{style:{maxWidth:1e3},children:[t.jsxs(N,{className:"lotus-settings-card",title:e("settings.clusters.title","Remote Clusters"),extra:t.jsx(z,{type:"primary",icon:t.jsx(dt,{}),onClick:$,children:e("settings.clusters.addButton","Add Node")}),children:[t.jsx(zr,{type:"secondary",style:{marginBottom:16},children:e("settings.clusters.description","Register machines (local or over SSH) to deploy worker agents onto. SSH credentials are encrypted at rest and never sent to the agent. Deploy/Test/Stop are wired but the deploy engine ships in a later phase.")}),t.jsx(at,{dataSource:a,columns:ne,rowKey:"id",size:"small",pagination:!1,loading:l,locale:{emptyText:e("settings.clusters.noNodes","No nodes registered")}})]}),t.jsx(Qe,{title:c?e("settings.clusters.editTitle","Edit Node"):e("settings.clusters.addTitle","Add Node"),open:g,onCancel:T,onOk:()=>p.submit(),okText:e("settings.clusters.save","Save"),cancelText:e("settings.clusters.cancel","Cancel"),width:560,destroyOnClose:!0,children:t.jsxs(y,{form:p,layout:"vertical",onFinish:A,children:[t.jsx(y.Item,{name:"label",label:e("settings.clusters.label","Label"),rules:[{required:!0,message:e("settings.clusters.labelRequired","Label is required")}],children:t.jsx(H,{placeholder:"gpu-1",autoFocus:!0})}),t.jsx(y.Item,{name:"placement_type",label:e("settings.clusters.placement","Placement"),children:t.jsx(te,{options:[{value:"ssh",label:e("settings.clusters.ssh","SSH (remote)")},{value:"local",label:e("settings.clusters.localhost","Local (this host)")}]})}),ie&&t.jsxs(t.Fragment,{children:[t.jsxs(L.Compact,{block:!0,children:[t.jsx(y.Item,{name:"host",label:e("settings.clusters.host","Host"),style:{width:"70%"},rules:[{required:!0,message:e("settings.clusters.hostRequired","Host is required")}],children:t.jsx(H,{placeholder:"10.0.0.5"})}),t.jsx(y.Item,{name:"port",label:e("settings.clusters.port","Port"),style:{width:"30%"},children:t.jsx(Me,{min:1,max:65535,style:{width:"100%"}})})]}),t.jsx(y.Item,{name:"username",label:e("settings.clusters.username","Username"),rules:[{required:!0,message:e("settings.clusters.usernameRequired","Username is required")}],children:t.jsx(H,{placeholder:"deploy"})}),t.jsx(y.Item,{name:"auth_method",label:e("settings.clusters.authMethod","Auth method"),children:t.jsx(te,{options:[{value:"password",label:e("settings.clusters.password","Password")},{value:"private_key",label:e("settings.clusters.privateKey","Private key")},{value:"system_ssh_config",label:e("settings.clusters.systemSsh","Use host's SSH config")}]})}),V==="password"&&t.jsx(y.Item,{name:"password",label:e("settings.clusters.password","Password"),extra:be?e("settings.clusters.secretEditHint","Leave empty to keep the existing secret"):void 0,rules:[{required:!be,message:e("settings.clusters.passwordRequired","Password is required")}],children:t.jsx(H.Password,{visibilityToggle:!0,placeholder:be?e("settings.clusters.keepSecret","Enter new password or leave empty"):void 0})}),V==="private_key"&&t.jsxs(t.Fragment,{children:[t.jsx(y.Item,{name:"private_key_path",label:e("settings.clusters.privateKeyPath","Private key file path (on this host)"),children:t.jsx(H,{placeholder:"~/.ssh/id_ed25519"})}),t.jsx(y.Item,{name:"private_key",label:e("settings.clusters.privateKeyInline","…or paste key (PEM)"),dependencies:["private_key_path"],extra:be?e("settings.clusters.secretEditHint","Leave empty to keep the existing secret"):void 0,rules:[{validator:async()=>{var K,se;const d=(K=p.getFieldValue("private_key_path"))==null?void 0:K.trim(),E=(se=p.getFieldValue("private_key"))==null?void 0:se.trim();if(d||E)return;const M=(be==null?void 0:be.placement.type)==="ssh"?be.placement.auth:void 0;if(!((M==null?void 0:M.method)==="private_key"&&(M.private_key||M.private_key_path)))throw new Error(e("settings.clusters.privateKeyRequired","Provide a key file path or paste a private key"))}}],children:t.jsx(H.TextArea,{rows:3,placeholder:"-----BEGIN OPENSSH PRIVATE KEY-----"})}),t.jsx(y.Item,{name:"passphrase",label:e("settings.clusters.passphrase","Passphrase"),children:t.jsx(H.Password,{visibilityToggle:!0})})]})]}),t.jsx(y.Item,{name:"artifact_path",label:e("settings.clusters.artifactPath","Artifact path (binary to upload)"),extra:e("settings.clusters.artifactHint","Path on this host to the correct-arch bamboo binary; used at deploy time (P2)."),children:t.jsx(H,{placeholder:"/path/to/bamboo-linux-x64"})}),t.jsx(y.Item,{name:"default_role",label:e("settings.clusters.role","Default role"),children:t.jsx(H,{placeholder:"worker"})}),t.jsx(y.Item,{name:"auto_recover",label:e("settings.clusters.autoRecover","Auto-recover"),valuePropName:"checked",extra:e("settings.clusters.autoRecoverHint","Redeploy this node automatically if the health monitor finds its worker gone."),children:t.jsx(fe,{})}),t.jsx(y.Item,{name:"cluster_name",label:e("settings.clusters.cluster","Cluster"),children:t.jsx(te,{allowClear:!0,showSearch:!0,mode:"tags",maxCount:1,placeholder:e("settings.clusters.clusterPlaceholder","Pick or type a cluster name"),options:r.map(d=>({value:d.name,label:d.name}))})}),t.jsx(y.Item,{name:"enabled",label:e("settings.clusters.enabled","Enabled"),valuePropName:"checked",children:t.jsx(fe,{})})]})}),t.jsx(Qe,{title:e("settings.clusters.logsTitle","Logs — {{label}}",{label:(x==null?void 0:x.label)??""}),open:S,onCancel:()=>v(!1),onOk:()=>x&&G(x),okText:e("settings.clusters.refresh","Refresh"),cancelText:e("settings.clusters.close","Close"),width:760,destroyOnClose:!0,children:I?t.jsx(Ut,{type:"secondary",children:e("settings.clusters.loading","Loading…")}):t.jsx("pre",{style:{maxHeight:420,overflow:"auto",fontSize:12,whiteSpace:"pre-wrap",wordBreak:"break-all",margin:0},children:P})})]})},Ct=class Ct{constructor(){}static getInstance(){return Ct.instance||(Ct.instance=new Ct),Ct.instance}async listWorkflows(){try{ct("[WorkflowManager]","[WorkflowManagerService] Listing workflows");const s=await da.get("bamboo/workflows"),a=Array.isArray(s)?s:[];return ct("[WorkflowManager]","[WorkflowManagerService] Listed workflows:",a),a.map(n=>({name:String(n.name||""),filename:String(n.filename||(n.name||"workflow")+".md"),size:Number(n.size||0),modified_at:typeof n.modified_at=="string"?n.modified_at:void 0,source:"global"}))}catch(s){throw console.error("[WorkflowManagerService] Failed to list workflows:",s),s}}async getWorkflow(s){try{ct("[WorkflowManager]","[WorkflowManagerService] Getting workflow: "+s);const a=await da.get("bamboo/workflows/"+encodeURIComponent(s)),n=a!=null&&a.name?String(a.name):s,r={name:n,filename:String((a==null?void 0:a.filename)||n+".md"),size:Number((a==null?void 0:a.size)||0),modified_at:a==null?void 0:a.modified_at,source:"global"};return ct("[WorkflowManager]","[WorkflowManagerService] Got workflow:",a),{name:n,content:String((a==null?void 0:a.content)||""),metadata:r}}catch(a){throw console.error("[WorkflowManagerService] Failed to get workflow "+s+":",a),ir(a)&&a.status===404?new Error("Workflow '"+s+"' not found"):a instanceof Error&&a.message.includes("404")?new Error("Workflow '"+s+"' not found"):a}}};la(Ct,"instance");let ea=Ct;const{Text:Ns}=ue,{TextArea:$r}=H,{useToken:Br}=Te,qr=e=>!(!e||e.includes("/")||e.includes("\\")||e.includes("..")),Hr=()=>{const{t:e}=ae(),{token:s}=Br(),[a,n]=zt.useMessage(),[r,o]=i.useState([]),[l,u]=i.useState(!1),[g,m]=i.useState(!1),[c,b]=i.useState(!1),[p,S]=i.useState(null),[v,x]=i.useState(""),[R,P]=i.useState(""),[C,I]=i.useState(!1),h=i.useMemo(()=>ea.getInstance(),[]),k=i.useCallback(async()=>{u(!0);try{const $=await h.listWorkflows();return o($),$}catch{return a.error(e("settings.workflowsTab.loadFailed")),[]}finally{u(!1)}},[a,e,h]);i.useEffect(()=>{k()},[k]);const V=i.useCallback(async $=>{S($),x($.name),I(!1),m(!0);try{const j=await h.getWorkflow($.name);P(j.content??"")}catch{a.error(e("settings.workflowsTab.loadContentFailed")),P("")}finally{m(!1)}},[a,e,h]),F=()=>{S(null),x(""),P(""),I(!1)},U=i.useCallback(async()=>{if(!qr(v)){a.error(e("settings.workflowsTab.invalidName"));return}const $=r.some(j=>j.name===v);if(!p&&$){a.error(e("settings.workflowsTab.nameAlreadyExists"));return}b(!0);try{await it.getInstance().saveWorkflow(v,R),a.success(e("settings.workflowsTab.saved")),I(!1);const D=(await k()).find(A=>A.name===v);D&&S(D)}catch(j){a.error(j instanceof Error?j.message:e("settings.workflowsTab.saveFailed"))}finally{b(!1)}},[R,v,k,a,p,e,r]),ee=i.useCallback(async $=>{try{await it.getInstance().deleteWorkflow($.name),a.success(e("settings.workflowsTab.deleted")),(p==null?void 0:p.name)===$.name&&F(),await k()}catch(j){a.error(j instanceof Error?j.message:e("settings.workflowsTab.deleteFailed"))}},[k,a,p,e]);return t.jsxs("div",{style:{padding:"24px"},children:[n,t.jsxs(N,{title:e("settings.workflowsTab.title"),extra:t.jsxs(L,{children:[t.jsx(z,{icon:t.jsx(Lt,{}),onClick:k,loading:l,children:e("settings.workflowsTab.refresh")}),t.jsx(z,{"data-testid":"create-workflow",icon:t.jsx(dt,{}),onClick:F,children:e("settings.workflowsTab.newWorkflow")}),t.jsx(z,{"data-testid":"save-workflow",type:"primary",icon:t.jsx(ws,{}),onClick:U,loading:c,disabled:!C,children:e("settings.workflowsTab.save")})]}),children:[t.jsx(Ns,{type:"secondary",children:e("settings.workflowsTab.description")}),t.jsxs(X,{gap:s.marginLG,style:{marginTop:s.marginLG},children:[t.jsx("div",{style:{width:320,flexShrink:0},children:t.jsx(Xe,{loading:l,dataSource:r,locale:{emptyText:e("settings.workflowsTab.empty")},renderItem:$=>t.jsx(Xe.Item,{style:{cursor:"pointer",backgroundColor:(p==null?void 0:p.name)===$.name?s.colorFillSecondary:"transparent",borderRadius:s.borderRadius,padding:s.paddingSM},onClick:()=>V($),actions:[t.jsx(z,{"data-testid":`delete-workflow-${$.name}`,type:"text",danger:!0,size:"small",icon:t.jsx(Et,{}),onClick:j=>{j.stopPropagation(),ee($)},"aria-label":e("settings.workflowsTab.delete")},"delete")],children:t.jsxs(L,{direction:"vertical",size:0,children:[t.jsxs(Ns,{strong:!0,children:["/",$.name]}),t.jsx(Ns,{type:"secondary",style:{fontSize:12},children:$.filename})]})})})}),t.jsx("div",{style:{flex:1},children:t.jsxs(L,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(H,{"data-testid":"workflow-name",placeholder:e("settings.workflowsTab.namePlaceholder"),value:v,onChange:$=>{x($.target.value),I(!0)},disabled:!!p,prefix:t.jsx(is,{})}),t.jsx($r,{"data-testid":"workflow-content",placeholder:e("settings.workflowsTab.contentPlaceholder"),value:R,onChange:$=>{P($.target.value),I(!0)},autoSize:{minRows:12},disabled:g})]})})]})]})]})};var W=(e=>(e.Connecting="connecting",e.Ready="ready",e.Degraded="degraded",e.Stopped="stopped",e.Error="error",e))(W||{});const ds=6e4,us=3e4,ns=2e4,Ss=1e4,Cs=e=>({id:e,enabled:!0,transport:{type:"stdio",command:"",args:[],env:{},startup_timeout_ms:ns},request_timeout_ms:ds,healthcheck_interval_ms:us,allowed_tools:[],denied_tools:[]}),Ur=()=>({status:"stopped",tool_count:0,restart_count:0}),Kr=e=>{switch(typeof e=="string"?e.trim().toLowerCase():""){case W.Connecting:return W.Connecting;case W.Ready:return W.Ready;case W.Degraded:return W.Degraded;case W.Error:return W.Error;case W.Stopped:default:return W.Stopped}},ot=(e,s)=>{if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const a=Number(e);if(Number.isFinite(a))return a}return s},Wr=(e,s)=>{if(!e||typeof e!="object")return s;const a=e;if(a.type==="sse"){const o=Array.isArray(a.headers)?a.headers.map(l=>{if(!l||typeof l!="object")return null;const u=l;return typeof u.name!="string"||typeof u.value!="string"?null:{name:u.name,value:u.value}}).filter(l=>!!l):[];return{type:"sse",url:typeof a.url=="string"?a.url:"",headers:o,connect_timeout_ms:ot(a.connect_timeout_ms,Ss)}}const n=Array.isArray(a.args)?a.args.filter(o=>typeof o=="string"):[],r=a.env&&typeof a.env=="object"?Object.entries(a.env):[];return{type:"stdio",command:typeof a.command=="string"?a.command:"",args:n,cwd:typeof a.cwd=="string"?a.cwd:void 0,env:r.reduce((o,[l,u])=>(typeof u=="string"&&(o[l]=u),o),{}),startup_timeout_ms:ot(a.startup_timeout_ms,ns)}},Gr=(e,s)=>{const a=Cs(e.id),n=s??{};return{...a,...n,id:e.id,name:typeof n.name=="string"?n.name:typeof e.name=="string"?e.name:void 0,enabled:typeof e.enabled=="boolean"?e.enabled:typeof n.enabled=="boolean"?n.enabled:!0,request_timeout_ms:ot(n.request_timeout_ms,ds),healthcheck_interval_ms:ot(n.healthcheck_interval_ms,us),allowed_tools:Array.isArray(n.allowed_tools)?n.allowed_tools.filter(o=>typeof o=="string"):[],denied_tools:Array.isArray(n.denied_tools)?n.denied_tools.filter(o=>typeof o=="string"):[],reconnect:n.reconnect&&typeof n.reconnect=="object"?{enabled:typeof n.reconnect.enabled=="boolean"?n.reconnect.enabled:!0,initial_backoff_ms:ot(n.reconnect.initial_backoff_ms,1e3),max_backoff_ms:ot(n.reconnect.max_backoff_ms,3e4),max_attempts:ot(n.reconnect.max_attempts,0)}:void 0,transport:Wr(n.transport,a.transport)}},Jr=e=>{const s=Ur(),n=e.runtime??{},r=n.status??e.status;return{status:Kr(r),last_error:typeof n.last_error=="string"?n.last_error:typeof e.last_error=="string"?e.last_error:void 0,connected_at:typeof n.connected_at=="string"?n.connected_at:void 0,disconnected_at:typeof n.disconnected_at=="string"?n.disconnected_at:void 0,tool_count:ot(n.tool_count??e.tool_count,s.tool_count),restart_count:ot(n.restart_count??e.restart_count,s.restart_count),last_ping_at:typeof n.last_ping_at=="string"?n.last_ping_at:void 0}},Xr=e=>{const s=Gr(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:Jr(e)}},Yr=(e,s)=>`mcp__${e}__${s}`,Zr=e=>{if(!e.startsWith("mcp__"))return null;const s=e.slice(5),a=s.indexOf("__");if(a<=0)return null;const n=s.slice(0,a),r=s.slice(a+2);return!n||!r?null:{server_id:n,original_name:r}},Qr=(e,s,a=0)=>{if(!e||typeof e!="object")return null;const n=e,r=typeof n.alias=="string"?n.alias:typeof n.name=="string"&&n.name.startsWith("mcp__")?n.name:void 0,o=r&&typeof r=="string"?Zr(r):null,l=(typeof n.server_id=="string"?n.server_id:void 0)??(typeof n.serverId=="string"?n.serverId:void 0)??(o==null?void 0:o.server_id)??s??"",u=(typeof n.original_name=="string"?n.original_name:void 0)??(typeof n.originalName=="string"?n.originalName:void 0)??(o==null?void 0:o.original_name)??(typeof n.name=="string"?n.name:void 0)??"",g=r??(l&&u?Yr(l,u):""),m=typeof n.description=="string"?n.description:"",c=n,b="parameters"in c?c.parameters:"inputSchema"in c?c.inputSchema:"input_schema"in c?c.input_schema:void 0,p=g||u||`mcp_tool_${a}`;return{alias:p,server_id:l||"unknown",original_name:u||p,description:m,parameters:b}};class ei{async getServers(){const s=await Ye.get("mcp/servers");return Array.isArray(s.servers)?s.servers.map(Xr):[]}async addServer(s){return Ye.post("mcp/servers",s)}async updateServer(s,a){const n={...a,id:s};return Ye.put(`mcp/servers/${s}`,n)}async deleteServer(s){return Ye.delete(`mcp/servers/${s}`)}async connectServer(s){return Ye.post(`mcp/servers/${s}/connect`)}async disconnectServer(s){return Ye.post(`mcp/servers/${s}/disconnect`)}async refreshTools(s){return Ye.post(`mcp/servers/${s}/refresh`)}async getTools(s){const a=s?`mcp/servers/${s}/tools`:"mcp/tools",n=await Ye.get(a);return(Array.isArray(n.tools)?n.tools:[]).map((o,l)=>Qr(o,s,l)).filter(o=>!!o)}async importServers(s){return Ye.post("mcp/servers/import",s)}}const sn=new ei,ti=5e3,nt=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,_a=(e,s)=>`${e}:${s}`,si=(e={})=>{const{service:s=sn,autoRefreshMs:a=ti,autoRefreshEnabled:n=!0}=e,[r,o]=i.useState([]),[l,u]=i.useState(null),[g,m]=i.useState({}),[c,b]=i.useState({}),[p,S]=i.useState({}),[v,x]=i.useState(!1),[R,P]=i.useState(!1),[C,I]=i.useState(!1),[h,k]=i.useState(null),V=i.useRef({}),F=i.useCallback(d=>{const E=new Set(d.map(K=>K.id)),M=d.map(K=>{const pe=V.current[K.id]??K.config,ye={...pe,id:K.id,name:pe.name??K.name};return V.current[K.id]=ye,{...K,name:K.name||ye.name||K.id,enabled:K.enabled??ye.enabled,config:ye}});return Object.keys(V.current).forEach(K=>{E.has(K)||delete V.current[K]}),M},[]),U=i.useCallback(async({silent:d=!1}={})=>{d||x(!0);try{const E=await s.getServers(),M=F(E);o(M),u(K=>{var se;return K&&M.some(pe=>pe.id===K)?K:((se=M[0])==null?void 0:se.id)??null}),k(null)}catch(E){throw k(nt(E,"Failed to load MCP servers")),E}finally{d||x(!1)}},[F,s]),ee=i.useCallback(async(d,E=!1)=>{if(!d)return[];if(!E&&g[d])return g[d];b(M=>({...M,[d]:!0}));try{const M=await s.getTools(d);return m(K=>({...K,[d]:M})),k(null),M}catch(M){throw k(nt(M,"Failed to load MCP tools")),M}finally{b(M=>({...M,[d]:!1}))}},[s,g]),$=i.useCallback((d,E,M)=>{const K=_a(d,E);S(se=>({...se,[K]:M}))},[]),j=i.useCallback(async d=>{P(!0);try{await s.addServer(d),V.current[d.id]=d,await U()}catch(E){throw k(nt(E,"Failed to add MCP server")),E}finally{P(!1)}},[U,s]),T=i.useCallback(async(d,E)=>{P(!0);try{const M={...E,id:d};await s.updateServer(d,M),V.current[d]=M,await U()}catch(M){throw k(nt(M,"Failed to update MCP server")),M}finally{P(!1)}},[U,s]),D=i.useCallback(async d=>{$(d,"delete",!0);try{await s.deleteServer(d),m(E=>{const M={...E};return delete M[d],M}),delete V.current[d],await U()}catch(E){throw k(nt(E,"Failed to delete MCP server")),E}finally{$(d,"delete",!1)}},[U,s,$]),A=i.useCallback(async d=>{$(d,"connect",!0);try{await s.connectServer(d),await U({silent:!0})}catch(E){throw k(nt(E,"Failed to connect MCP server")),E}finally{$(d,"connect",!1)}},[U,s,$]),Q=i.useCallback(async d=>{$(d,"disconnect",!0);try{await s.disconnectServer(d),await U({silent:!0})}catch(E){throw k(nt(E,"Failed to disconnect MCP server")),E}finally{$(d,"disconnect",!1)}},[U,s,$]),O=i.useCallback(async d=>{$(d,"refresh",!0);try{await s.refreshTools(d),await ee(d,!0),await U({silent:!0})}catch(E){throw k(nt(E,"Failed to refresh MCP tools")),E}finally{$(d,"refresh",!1)}},[ee,U,s,$]),Y=i.useCallback(async()=>{I(!0);try{const d=r.map(E=>E.id);await Promise.all(d.map(async E=>{try{await s.refreshTools(E)}catch{}})),await U(),l&&await ee(l,!0)}catch(d){throw k(nt(d,"Failed to refresh MCP status")),d}finally{I(!1)}},[ee,U,l,r,s]),G=i.useCallback(d=>{u(d)},[]),ne=i.useCallback((d,E)=>!!p[_a(d,E)],[p]),ie=i.useMemo(()=>l?g[l]??[]:[],[l,g]),be=i.useMemo(()=>l?!!c[l]:!1,[l,c]);return i.useEffect(()=>{U().catch(()=>{})},[U]),i.useEffect(()=>{if(!n||a<=0)return;const d=window.setInterval(()=>{U({silent:!0}).catch(()=>{})},a);return()=>{window.clearInterval(d)}},[n,a,U]),i.useEffect(()=>{l&&ee(l).catch(()=>{})},[ee,l]),{servers:r,selectedServerId:l,selectedServerTools:ie,isLoadingServers:v,isMutatingConfig:R,isRefreshingAll:C,isSelectedServerToolsLoading:be,error:h,setSelectedServerId:G,refreshServers:U,addServer:j,updateServer:T,deleteServer:D,connectServer:A,disconnectServer:Q,refreshServerTools:O,refreshAll:Y,isServerActionLoading:ne}},ai={[W.Connecting]:"blue",[W.Ready]:"green",[W.Degraded]:"orange",[W.Stopped]:"default",[W.Error]:"red"},ni=e=>e===W.Connecting||e===W.Ready||e===W.Degraded,ri=e=>{if(!e)return;const s=e.replace(/\s+/g," ").trim();if(s)return s.length>180?`${s.slice(0,180)}...`:s},ii=({servers:e,loading:s=!1,selectedServerId:a,onSelectServer:n,onEditServer:r,onDeleteServer:o,onConnectServer:l,onDisconnectServer:u,onRefreshTools:g,isServerActionLoading:m})=>{const{t:c}=ae(),{token:b}=Te.useToken(),p=i.useMemo(()=>({[W.Connecting]:c("settings.mcpTab.statusHelp.connecting"),[W.Ready]:c("settings.mcpTab.statusHelp.ready"),[W.Degraded]:c("settings.mcpTab.statusHelp.degraded"),[W.Stopped]:c("settings.mcpTab.statusHelp.stopped"),[W.Error]:c("settings.mcpTab.statusHelp.error")}),[c]),S=i.useMemo(()=>[{key:"name",title:c("settings.mcpServerTable.columns.name"),render:(v,x)=>x.name||x.id},{key:"transport",title:c("settings.mcpServerTable.columns.transportType"),render:(v,x)=>x.config.transport.type==="sse"?c("settings.mcpServerTable.transportOptions.sse"):c("settings.mcpServerTable.transportOptions.stdio"),width:140},{key:"status",title:c("settings.mcpServerTable.columns.status"),render:(v,x)=>{var h,k;const R=((h=x.runtime)==null?void 0:h.status)??W.Stopped,P=ri((k=x.runtime)==null?void 0:k.last_error),C=p[R],I={[W.Connecting]:c("settings.mcpTab.status.connecting"),[W.Ready]:c("settings.mcpTab.status.ready"),[W.Degraded]:c("settings.mcpTab.status.degraded"),[W.Stopped]:c("settings.mcpTab.status.stopped"),[W.Error]:c("settings.mcpTab.status.error")};return t.jsx(ke,{title:P?`${C} ${c("settings.mcpTab.statusLastError",{error:P})}`:C,children:t.jsx(re,{color:R===W.Stopped?void 0:ai[R],style:{marginInlineEnd:0,cursor:"help",...R===W.Stopped?{background:b.colorFillSecondary,borderColor:b.colorBorderSecondary,color:b.colorTextSecondary}:void 0},children:I[R]})})},width:120},{key:"toolCount",title:c("settings.mcpServerTable.columns.toolCount"),render:(v,x)=>{var R;return((R=x.runtime)==null?void 0:R.tool_count)??0},width:100},{key:"actions",title:c("settings.mcpServerTable.columns.actions"),width:360,render:(v,x)=>{var C;const R=((C=x.runtime)==null?void 0:C.status)??W.Stopped,P=ni(R);return t.jsxs(L,{size:b.marginXS,children:[t.jsx(z,{size:"small",onClick:I=>{I.stopPropagation(),r==null||r(x)},children:c("settings.mcpServerTable.actions.edit")}),t.jsx(Rt,{title:c("settings.mcpServerTable.deleteTitle"),description:c("settings.mcpServerTable.deleteDescription",{name:x.name||x.id}),onConfirm:()=>o==null?void 0:o(x),okText:c("settings.mcpServerTable.actions.delete"),okButtonProps:{danger:!0,loading:m==null?void 0:m(x.id,"delete")},children:t.jsx(z,{size:"small",danger:!0,loading:m==null?void 0:m(x.id,"delete"),onClick:I=>I.stopPropagation(),children:c("settings.mcpServerTable.actions.delete")})}),P?t.jsx(z,{size:"small",onClick:I=>{I.stopPropagation(),u==null||u(x)},loading:m==null?void 0:m(x.id,"disconnect"),children:c("settings.mcpServerTable.actions.disconnect")}):t.jsx(z,{size:"small",type:"primary",ghost:!0,onClick:I=>{I.stopPropagation(),l==null||l(x)},loading:m==null?void 0:m(x.id,"connect"),children:c("settings.mcpServerTable.actions.connect")}),t.jsx(z,{size:"small",onClick:I=>{I.stopPropagation(),g==null||g(x)},loading:m==null?void 0:m(x.id,"refresh"),children:c("settings.mcpServerTable.actions.refreshTools")})]})}}],[m,l,o,u,r,g,p,c,b.colorBorderSecondary,b.colorFillSecondary,b.colorTextSecondary,b.marginXS]);return t.jsx(at,{rowKey:"id",columns:S,dataSource:e,loading:s,pagination:!1,locale:{emptyText:c("settings.mcpServerTable.empty")},onRow:v=>({onClick:()=>n==null?void 0:n(v.id),style:{cursor:n?"pointer":"default",backgroundColor:a===v.id?b.colorFillSecondary:void 0}})})},{Text:Sa}=ue,{TextArea:oi}=H,ka=e=>{const s=e??Cs(""),a=s.transport,n=a.type==="stdio"?Object.entries(a.env??{}).map(([o,l])=>({key:o,value:l})):[],r=a.type==="sse"?a.headers.map(o=>({name:o.name,value:o.value})):[];return{id:s.id,name:s.name,enabled:s.enabled,transportType:a.type,command:a.type==="stdio"?a.command:void 0,args:a.type==="stdio"?a.args:[],envEntries:n,url:a.type==="sse"?a.url:void 0,headerEntries:r,requestTimeoutMs:s.request_timeout_ms||ds,healthcheckIntervalMs:s.healthcheck_interval_ms||us,allowedTools:s.allowed_tools||[],deniedTools:s.denied_tools||[]}},li=e=>e.reduce((s,a)=>{var r;const n=(r=a.key)==null?void 0:r.trim();return n&&(s[n]=a.value??""),s},{}),ci=e=>e.filter(s=>{var a;return(a=s.name)==null?void 0:a.trim()}).map(s=>{var a;return{name:((a=s.name)==null?void 0:a.trim())||"",value:s.value??""}}),wa=(e,s,a)=>{var c,b,p;const n=s==="edit"&&(a==null?void 0:a.id)||e.id,r=(c=e.name)==null?void 0:c.trim(),o=typeof e.requestTimeoutMs=="number"?e.requestTimeoutMs:(a==null?void 0:a.request_timeout_ms)??ds,l=typeof e.healthcheckIntervalMs=="number"?e.healthcheckIntervalMs:(a==null?void 0:a.healthcheck_interval_ms)??us,u=Array.isArray(e.allowedTools)?e.allowedTools:(a==null?void 0:a.allowed_tools)??[],g=Array.isArray(e.deniedTools)?e.deniedTools:(a==null?void 0:a.denied_tools)??[],m=e.transportType==="sse"?{type:"sse",url:((b=e.url)==null?void 0:b.trim())||"",headers:ci(e.headerEntries||[]),connect_timeout_ms:(a==null?void 0:a.transport.type)==="sse"?a.transport.connect_timeout_ms??Ss:Ss}:{type:"stdio",command:((p=e.command)==null?void 0:p.trim())||"",args:e.args||[],env:li(e.envEntries||[]),cwd:(a==null?void 0:a.transport.type)==="stdio"?a.transport.cwd:void 0,startup_timeout_ms:(a==null?void 0:a.transport.type)==="stdio"?a.transport.startup_timeout_ms??ns:ns};return{id:n,name:r||void 0,enabled:e.enabled,transport:m,request_timeout_ms:o,healthcheck_interval_ms:l,allowed_tools:u,denied_tools:g,reconnect:a==null?void 0:a.reconnect}},Ca=e=>JSON.stringify(e||Cs(""),null,2),Vs=(e,s)=>{try{const a=JSON.parse(e);if(!a||typeof a!="object")return{valid:!1,error:s("settings.mcpServerForm.jsonMustBeObject")};const n=a;if(n.mcpServers&&typeof n.mcpServers=="object")return{valid:!1,error:s("settings.mcpServerForm.detectedBulkConfig")};const r=typeof n.id=="string"?n.id:"";if(!r.trim())return{valid:!1,error:s("settings.mcpServerForm.missingIdField")};if(n.transport&&typeof n.transport=="object"){const b=n;return!b.transport||typeof b.transport!="object"?{valid:!1,error:s("settings.mcpServerForm.missingTransportField")}:{valid:!0,config:b}}const o=typeof n.enabled=="boolean"?n.enabled:typeof n.disabled=="boolean"?!n.disabled:!0,l=typeof n.request_timeout_ms=="number"?n.request_timeout_ms:ds,u=typeof n.healthcheck_interval_ms=="number"?n.healthcheck_interval_ms:us,g=Array.isArray(n.allowed_tools)?n.allowed_tools.filter(b=>typeof b=="string"):[],m=Array.isArray(n.denied_tools)?n.denied_tools.filter(b=>typeof b=="string"):[],c=typeof n.name=="string"?n.name:void 0;if(typeof n.url=="string"){const b=n.headers,p=Array.isArray(b)?b.map(v=>{if(!v||typeof v!="object")return null;const x=v,R=typeof x.name=="string"?x.name:"",P=typeof x.value=="string"?x.value:"";return R.trim()?{name:R,value:P}:null}).filter(v=>!!v):b&&typeof b=="object"?Object.entries(b).filter(([v])=>v.trim()).map(([v,x])=>({name:v,value:typeof x=="string"?x:""})):[],S=typeof n.connect_timeout_ms=="number"?n.connect_timeout_ms:Ss;return{valid:!0,config:{id:r,name:c,enabled:o,transport:{type:"sse",url:n.url,headers:p,connect_timeout_ms:S},request_timeout_ms:l,healthcheck_interval_ms:u,allowed_tools:g,denied_tools:m,reconnect:void 0}}}if(typeof n.command=="string"){const b=Array.isArray(n.args)?n.args.filter(x=>typeof x=="string"):[],p=n.env,S=p&&typeof p=="object"?Object.entries(p).reduce((x,[R,P])=>(typeof P=="string"&&(x[R]=P),x),{}):{},v=typeof n.startup_timeout_ms=="number"?n.startup_timeout_ms:ns;return{valid:!0,config:{id:r,name:c,enabled:o,transport:{type:"stdio",command:n.command,args:b,cwd:typeof n.cwd=="string"?n.cwd:void 0,env:S,startup_timeout_ms:v},request_timeout_ms:l,healthcheck_interval_ms:u,allowed_tools:g,denied_tools:m,reconnect:void 0}}}return{valid:!1,error:s("settings.mcpServerForm.missingTransportInfo")}}catch(a){return{valid:!1,error:s("settings.mcpServerForm.invalidJson",{message:a instanceof Error?a.message:s("settings.mcpServerForm.unknownError")})}}},di=({open:e,mode:s,initialConfig:a,confirmLoading:n=!1,onCancel:r,onSubmit:o})=>{const{t:l}=ae(),[u]=y.useForm(),[g,m]=i.useState("form"),[c,b]=i.useState(""),[p,S]=i.useState(null),v=i.useMemo(()=>ka(a),[a]),x=y.useWatch("transportType",u)??"stdio";i.useEffect(()=>{e&&(u.setFieldsValue(v),b(Ca(a)),S(null),m("form"))},[u,v,a,e]);const R=()=>{u.resetFields(),b(""),S(null),r()},P=async()=>{if(g==="json"){const h=Vs(c,l);if(!h.valid){S(h.error);return}S(null);try{await o(h.config),b("")}catch(k){console.error("MCP server JSON submission error:",k)}return}try{const h=await u.validateFields(),k=wa(h,s,a);await o(k),u.resetFields()}catch(h){console.error("MCP server form submission error:",h)}},C=h=>{b(h),p&&Vs(h,l).valid&&S(null)},I=h=>{if(h==="json")try{const k=u.getFieldsValue(),V=wa(k,s,a);b(JSON.stringify(V,null,2))}catch{b(Ca(a))}else{const k=Vs(c,l);k.valid&&u.setFieldsValue(ka(k.config))}m(h),S(null)};return t.jsxs(Qe,{title:l(s==="edit"?"settings.mcpServerForm.editTitle":"settings.mcpServerForm.addTitle"),open:e,onCancel:R,onOk:()=>{P()},okText:l("settings.mcpServerForm.save"),destroyOnClose:!0,forceRender:!0,confirmLoading:n,width:720,children:[t.jsx("div",{style:{marginBottom:16},children:t.jsxs(Ft.Group,{value:g,onChange:h=>I(h.target.value),optionType:"button",buttonStyle:"solid",children:[t.jsxs(Ft.Button,{value:"form",children:[t.jsx(qn,{})," ",l("settings.mcpServerForm.modeForm")]}),t.jsxs(Ft.Button,{value:"json",children:[t.jsx(Hn,{})," ",l("settings.mcpServerForm.modeJson")]})]})}),g==="json"&&p&&t.jsx(qe,{type:"error",message:l("settings.mcpServerForm.jsonError"),description:p,showIcon:!0,style:{marginBottom:16},closable:!0,onClose:()=>S(null)}),g==="json"?t.jsx(oi,{value:c,onChange:h=>C(h.target.value),rows:20,style:{fontFamily:"monospace",fontSize:13},placeholder:JSON.stringify(Cs("example-server"),null,2)}):t.jsxs(y,{layout:"vertical",form:u,preserve:!0,initialValues:v,children:[t.jsx(y.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(y.Item,{name:"name",label:l("settings.mcpServerForm.displayName"),children:t.jsx(H,{placeholder:"Filesystem MCP",autoComplete:"off"})}),t.jsx(y.Item,{name:"enabled",label:l("settings.mcpServerForm.enabled"),valuePropName:"checked",extra:l("settings.mcpServerForm.enabledHelp"),children:t.jsx(fe,{})}),t.jsx(y.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"}]})}),x==="stdio"?t.jsxs(t.Fragment,{children:[t.jsx(y.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(y.Item,{name:"args",label:l("settings.mcpServerForm.arguments"),children:t.jsx(te,{mode:"tags",tokenSeparators:[","],placeholder:l("settings.mcpServerForm.argumentsPlaceholder"),open:!1})}),t.jsx(y.List,{name:"envEntries",children:(h,{add:k,remove:V})=>t.jsxs(L,{direction:"vertical",style:{width:"100%"},children:[t.jsxs(L,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[t.jsx(Sa,{strong:!0,children:l("settings.mcpServerForm.envVars")}),t.jsx(z,{icon:t.jsx(dt,{}),onClick:()=>k({key:"",value:""}),type:"dashed",children:l("settings.mcpServerForm.addEnv")})]}),h.map(F=>t.jsxs(L,{align:"baseline",style:{display:"flex"},children:[t.jsx(y.Item,{...F,name:[F.name,"key"],rules:[{required:!0,message:l("settings.mcpServerForm.keyRequired")}],children:t.jsx(H,{placeholder:"MCP_ROOT",autoComplete:"off"})}),t.jsx(y.Item,{...F,name:[F.name,"value"],children:t.jsx(H,{placeholder:"/Users/me/workspace",autoComplete:"off"})}),t.jsx(z,{danger:!0,type:"text",icon:t.jsx(ya,{}),onClick:()=>V(F.name),"aria-label":l("settings.mcpServerForm.removeEnv","Remove environment variable")})]},F.key))]})})]}):t.jsxs(t.Fragment,{children:[t.jsx(y.Item,{name:"url",label:l("settings.mcpServerForm.sseUrl"),rules:[{required:!0,message:l("settings.mcpServerForm.sseUrlRequired")},{validator:async(h,k)=>{if(k)try{new URL(k)}catch{throw new Error(l("settings.mcpServerForm.validUrlRequired"))}}}],children:t.jsx(H,{placeholder:"http://localhost:4000/sse",autoComplete:"off"})}),t.jsx(y.List,{name:"headerEntries",children:(h,{add:k,remove:V})=>t.jsxs(L,{direction:"vertical",style:{width:"100%"},children:[t.jsxs(L,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[t.jsx(Sa,{strong:!0,children:l("settings.mcpServerForm.headers")}),t.jsx(z,{icon:t.jsx(dt,{}),onClick:()=>k({name:"",value:""}),type:"dashed",children:l("settings.mcpServerForm.addHeader")})]}),h.map(F=>t.jsxs(L,{align:"baseline",style:{display:"flex"},children:[t.jsx(y.Item,{...F,name:[F.name,"name"],rules:[{required:!0,message:l("settings.mcpServerForm.headerNameRequired")}],children:t.jsx(H,{placeholder:"Authorization",autoComplete:"off"})}),t.jsx(y.Item,{...F,name:[F.name,"value"],children:t.jsx(H,{placeholder:"Bearer token",autoComplete:"off"})}),t.jsx(z,{danger:!0,type:"text",icon:t.jsx(ya,{}),onClick:()=>V(F.name),"aria-label":l("settings.mcpServerForm.removeHeader","Remove header")})]},F.key))]})})]})]})]})},js=e=>!!e&&typeof e=="object"&&!Array.isArray(e),_t=(e,s)=>{const a=e[s];return typeof a=="string"?a:void 0},Ma=(e,s)=>{const a=e[s];return typeof a=="boolean"?a:void 0},ui=(e,s)=>{const a=e[s];return Array.isArray(a)?a:void 0},es=e=>{if(!js(e))return"any";const s=e.type;if(typeof s=="string"){if(s==="array"){const o=e.items;return`array<${es(o)}>`}return s==="object"?"object":s}if(Array.isArray(s)){const o=s.filter(l=>typeof l=="string").map(l=>l==="array"?"array<any>":l);return o.length>0?o.join(" | "):"any"}const a=Array.isArray(e.oneOf)?e.oneOf:null;if(a)return a.map(es).join(" | ")||"any";const n=Array.isArray(e.anyOf)?e.anyOf:null;if(n)return n.map(es).join(" | ")||"any";const r=Array.isArray(e.allOf)?e.allOf:null;return r&&r.map(es).join(" & ")||"any"},gi=e=>{if(!js(e))return null;const s=e.properties;if(!js(s))return{schemaUri:_t(e,"$schema"),title:_t(e,"title"),description:_t(e,"description"),additionalProperties:Ma(e,"additionalProperties"),fields:[]};const a=new Set((ui(e,"required")??[]).filter(r=>typeof r=="string").map(r=>r)),n=Object.entries(s).map(([r,o])=>{const l=js(o)?o:void 0;return{name:r,type:es(o),required:a.has(r),description:l?_t(l,"description"):void 0,defaultValue:l?l.default:void 0,enumValues:l&&Array.isArray(l.enum)?l.enum:void 0}});return n.sort((r,o)=>r.required!==o.required?r.required?-1:1:r.name.localeCompare(o.name)),{schemaUri:_t(e,"$schema"),title:_t(e,"title"),description:_t(e,"description"),additionalProperties:Ma(e,"additionalProperties"),fields:n}},{Text:et}=ue,mi=e=>e===void 0?"":e===null?"null":typeof e=="string"?e:Ya(e,0),pi=({schema:e})=>{const{token:s}=Te.useToken(),{t:a}=ae(),n=i.useMemo(()=>gi(e),[e]);if(!n)return t.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:Ya(e,2)});const r=[{title:a("components.jsonSchema.field"),dataIndex:"name",key:"name",width:180,render:l=>t.jsx(et,{code:!0,children:l})},{title:a("components.jsonSchema.type"),dataIndex:"type",key:"type",width:140,render:l=>t.jsx(et,{children:l})},{title:a("components.jsonSchema.required"),dataIndex:"required",key:"required",width:110,render:l=>l?t.jsx(et,{strong:!0,style:{color:s.colorError},children:a("components.jsonSchema.yes")}):t.jsx(et,{type:"secondary",children:a("components.jsonSchema.no")})},{title:a("components.jsonSchema.default"),dataIndex:"defaultValue",key:"default",width:160,render:l=>l===void 0?t.jsx(et,{type:"secondary",children:"-"}):t.jsx(et,{children:mi(l)})},{title:a("components.jsonSchema.description"),dataIndex:"description",key:"description",render:l=>l?t.jsx(et,{style:{whiteSpace:"pre-wrap"},children:l}):t.jsx(et,{type:"secondary",children:"-"})}],o=(n.fields??[]).map(l=>({...l,key:l.name}));return t.jsxs("div",{style:{width:"100%"},children:[t.jsx(ze,{size:"small",column:1,items:[n.schemaUri?{key:"schema",label:"$schema",children:t.jsx(et,{code:!0,children:n.schemaUri})}:null,typeof n.additionalProperties=="boolean"?{key:"additionalProperties",label:"additionalProperties",children:t.jsx(et,{children:n.additionalProperties?"true":"false"})}:null].filter(Boolean)}),t.jsx(at,{size:"small",pagination:!1,columns:r,dataSource:o,locale:{emptyText:a("components.jsonSchema.noProperties")},style:{marginTop:s.marginSM}})]})},{Text:Kt}=ue,hi=(e,s)=>`mcp__${e}__${s}`,fi=({server:e,tools:s,loading:a=!1})=>{const{t:n}=ae();return t.jsx(N,{title:n("settings.mcpToolList.title"),size:"small",children:e?t.jsx(Xe,{loading:a,dataSource:s,locale:{emptyText:n("settings.mcpToolList.empty")},renderItem:r=>{const o=hi(r.server_id,r.original_name);return t.jsx(Xe.Item,{children:t.jsxs(L,{direction:"vertical",size:2,style:{width:"100%"},children:[t.jsx(Kt,{strong:!0,children:r.original_name}),t.jsx(Kt,{type:"secondary",children:r.description||n("settings.mcpToolList.noDescription")}),t.jsx(Kt,{code:!0,children:r.alias}),t.jsxs(Kt,{type:"secondary",children:[n("settings.mcpToolList.aliasMapping"),": ",t.jsx(Kt,{code:!0,children:o})]}),r.parameters!==void 0&&t.jsx(ks,{size:"small",items:[{key:"schema",label:n("settings.mcpToolList.parametersSchema"),children:t.jsx(pi,{schema:r.parameters})}]})]})})}}):t.jsx(He,{image:He.PRESENTED_IMAGE_SIMPLE,description:n("settings.mcpToolList.selectServerHint")})})},{Text:Wt}=ue,{useToken:yi}=Te,{TextArea:xi}=H,Ea={[W.Connecting]:"processing",[W.Ready]:"success",[W.Degraded]:"warning",[W.Stopped]:"default",[W.Error]:"error"},bi=()=>({[W.Connecting]:0,[W.Ready]:0,[W.Degraded]:0,[W.Stopped]:0,[W.Error]:0}),St=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,vi=e=>{var a,n,r;const s={};for(const o of e){const l=(a=o.id)==null?void 0:a.trim();if(!l)continue;const g=!(o.enabled??o.config.enabled),m=o.config.transport;if(m.type==="sse"){const b={};for(const S of m.headers??[]){const v=(n=S.name)==null?void 0:n.trim();v&&(b[v]=S.value??"")}const p={url:m.url};g&&(p.disabled=!0),Object.keys(b).length&&(p.headers=b),s[l]=p;continue}const c={command:m.command};g&&(c.disabled=!0),(r=m.args)!=null&&r.length&&(c.args=m.args),m.cwd&&(c.cwd=m.cwd),m.env&&Object.keys(m.env).length&&(c.env=m.env),s[l]=c}return{mcpServers:s}},ji=()=>{const{t:e}=ae(),{token:s}=yi(),[a,n]=zt.useMessage(),{servers:r,selectedServerId:o,selectedServerTools:l,isLoadingServers:u,isMutatingConfig:g,isRefreshingAll:m,isSelectedServerToolsLoading:c,error:b,setSelectedServerId:p,addServer:S,updateServer:v,deleteServer:x,connectServer:R,disconnectServer:P,refreshServerTools:C,refreshAll:I,isServerActionLoading:h}=si(),k=i.useMemo(()=>({[W.Connecting]:e("settings.mcpTab.status.connecting"),[W.Ready]:e("settings.mcpTab.status.ready"),[W.Degraded]:e("settings.mcpTab.status.degraded"),[W.Stopped]:e("settings.mcpTab.status.stopped"),[W.Error]:e("settings.mcpTab.status.error")}),[e]),V=i.useMemo(()=>({[W.Connecting]:e("settings.mcpTab.statusHelp.connecting"),[W.Ready]:e("settings.mcpTab.statusHelp.ready"),[W.Degraded]:e("settings.mcpTab.statusHelp.degraded"),[W.Stopped]:e("settings.mcpTab.statusHelp.stopped"),[W.Error]:e("settings.mcpTab.statusHelp.error")}),[e]),[F,U]=i.useState(!1),[ee,$]=i.useState("create"),[j,T]=i.useState(null),[D,A]=i.useState(!1),[Q,O]=i.useState("merge"),[Y,G]=i.useState(""),[ne,ie]=i.useState(null),[be,d]=i.useState(!1),E=i.useMemo(()=>o?r.find(f=>f.id===o)??null:null,[o,r]),M=i.useMemo(()=>{const f=bi();let ce=0;return r.forEach(ve=>{var _e,Ve;const Ne=((_e=ve.runtime)==null?void 0:_e.status)??W.Stopped;f[Ne]+=1,ce+=((Ve=ve.runtime)==null?void 0:Ve.tool_count)??0}),{byStatus:f,totalServers:r.length,totalTools:ce}},[r]),K={background:s.colorFillSecondary,borderColor:s.colorBorderSecondary,color:s.colorTextSecondary},se=async f=>{try{await x(f.id),a.success(e("settings.mcpTab.serverDeleted"))}catch(ce){a.error(St(ce,e("settings.mcpTab.deleteServerFailed")))}},pe=async f=>{try{await R(f.id),a.success(e("settings.mcpTab.connectedTo",{name:f.name||f.id}))}catch(ce){a.error(St(ce,e("settings.mcpTab.connectServerFailed")))}},ye=async f=>{try{await P(f.id),a.success(e("settings.mcpTab.disconnected",{name:f.name||f.id}))}catch(ce){a.error(St(ce,e("settings.mcpTab.disconnectServerFailed")))}},je=async f=>{try{await C(f.id),a.success(e("settings.mcpTab.toolsRefreshedFor",{name:f.name||f.id}))}catch(ce){a.error(St(ce,e("settings.mcpTab.refreshToolsFailed")))}},B=async()=>{try{await I(),a.success(e("settings.mcpTab.statusRefreshed"))}catch(f){a.error(St(f,e("settings.mcpTab.refreshStatusFailed")))}},we=()=>{T(null),$("create"),U(!0)},We=f=>{T(f),$("edit"),U(!0)},Ie=async f=>{try{if(ee==="edit"){if(!j){a.error(e("settings.mcpTab.noServerForEditing"));return}await v(j.id,f),a.success(e("settings.mcpTab.savedServer",{name:j.name||j.id}))}else await S(f),a.success(e("settings.mcpTab.addedServer",{name:f.name||f.id}));U(!1),T(null)}catch(ce){a.error(St(ce,e("settings.mcpTab.saveServerFailed")))}},Oe=()=>{A(!0),ie(null),O("merge"),G("")},Pe=async()=>{const f=vi(r),ce=JSON.stringify(f,null,2);try{await aa(ce),a.success(e("settings.mcpTab.copiedConfig"))}catch{A(!0),ie(null),O("merge"),G(ce),a.warning(e("settings.mcpTab.clipboardUnavailable"))}},Ge=async()=>{var Ne;ie(null);let f;try{f=JSON.parse(Y)}catch(_e){ie(`${e("settings.mcpTab.invalidJsonPrefix")}: ${_e instanceof Error?_e.message:e("settings.mcpTab.unknownError")}`);return}if(!f||typeof f!="object"){ie(e("settings.mcpTab.jsonMustBeObject"));return}const ve=f.mcpServers;if(!ve||typeof ve!="object"){ie(e("settings.mcpTab.missingMcpServers"));return}d(!0);try{const _e=await sn.importServers({mcpServers:ve,mode:Q}),Ve=((Ne=_e.start_errors)==null?void 0:Ne.length)??0;a.success(e("settings.mcpTab.importSummary",{count:_e.server_ids.length,added:_e.added,updated:_e.updated,removed:_e.removed,failed:Ve})),Ve&&a.warning(e("settings.mcpTab.importStartFailures")),A(!1),G(""),await B()}catch(_e){ie(St(_e,e("settings.mcpTab.importFailed")))}finally{d(!1)}};return t.jsxs(L,{direction:"vertical",size:s.marginMD,style:{width:"100%"},children:[n,b?t.jsx(qe,{type:"error",showIcon:!0,message:b}):null,t.jsx(N,{size:"small",title:e("settings.mcpTab.overviewTitle"),children:t.jsxs(L,{direction:"vertical",size:s.marginXS,style:{width:"100%"},children:[t.jsx(Wt,{type:"secondary",children:e("settings.mcpTab.overviewDescription")}),t.jsxs(L,{wrap:!0,children:[t.jsx(re,{style:K,children:e("settings.mcpTab.totalServers",{count:M.totalServers})}),t.jsx(re,{style:K,children:e("settings.mcpTab.totalTools",{count:M.totalTools})}),Object.values(W).map(f=>t.jsx(ke,{title:V[f],children:t.jsxs(re,{color:f===W.Stopped?void 0:Ea[f],style:{cursor:"help",...f===W.Stopped?K:void 0},children:[k[f],": ",M.byStatus[f]]})},f))]}),t.jsx(Wt,{type:"secondary",children:e("settings.mcpTab.statusGuideTitle")}),t.jsx(L,{direction:"vertical",size:2,style:{width:"100%"},children:Object.values(W).map(f=>t.jsxs(Wt,{type:"secondary",children:[t.jsx(re,{color:f===W.Stopped?void 0:Ea[f],style:{marginInlineEnd:8,...f===W.Stopped?K:void 0},children:k[f]}),V[f]]},`guide-${f}`))})]})}),t.jsx(N,{size:"small",title:e("settings.mcpTab.serversTitle"),extra:t.jsxs(L,{children:[t.jsx(z,{type:"primary",onClick:we,children:e("settings.mcpTab.addServer")}),t.jsx(z,{icon:t.jsx(Lt,{}),loading:m,onClick:()=>{B()},children:e("settings.mcpTab.refreshAll")}),t.jsx(z,{icon:t.jsx(Za,{}),onClick:()=>void Pe(),children:e("settings.mcpTab.export")}),t.jsx(z,{icon:t.jsx(Un,{}),onClick:Oe,children:e("settings.mcpTab.import")})]}),children:t.jsx(ii,{servers:r,loading:u,selectedServerId:o,onSelectServer:p,onEditServer:We,onDeleteServer:se,onConnectServer:pe,onDisconnectServer:ye,onRefreshTools:je,isServerActionLoading:h})}),t.jsx(fi,{server:E,tools:l,loading:c}),t.jsx(di,{open:F,mode:ee,initialConfig:(j==null?void 0:j.config)??null,confirmLoading:g,onCancel:()=>{g||(U(!1),T(null))},onSubmit:f=>void Ie(f)}),t.jsx(Qe,{open:D,title:e("settings.mcpTab.importModalTitle"),okText:e("settings.mcpTab.import"),onOk:()=>void Ge(),okButtonProps:{loading:be},onCancel:()=>{be||(A(!1),ie(null))},width:800,destroyOnClose:!1,children:t.jsxs(L,{direction:"vertical",style:{width:"100%"},size:"middle",children:[t.jsxs(Wt,{type:"secondary",children:[e("settings.mcpTab.importHint"),t.jsx("br",{}),t.jsx(Wt,{code:!0,children:'{ "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "..."] } } }'})]}),t.jsxs(Ft.Group,{value:Q,onChange:f=>O(f.target.value),optionType:"button",buttonStyle:"solid",children:[t.jsx(Ft.Button,{value:"merge",children:e("settings.mcpTab.importModeMerge")}),t.jsx(Ft.Button,{value:"replace",children:e("settings.mcpTab.importModeReplace")})]}),Q==="replace"?t.jsx(qe,{type:"warning",showIcon:!0,message:e("settings.mcpTab.replaceWarning")}):null,ne?t.jsx(qe,{type:"error",showIcon:!0,message:ne}):null,t.jsx(xi,{value:Y,onChange:f=>G(f.target.value),rows:14,placeholder:'{"mcpServers": { "filesystem": { "command": "...", "args": [], "env": {} } }}',spellCheck:!1})]})})]})},an=1,Ti=365,nn=e=>Number.isFinite(e)?Math.min(Ti,Math.max(an,Math.floor(e??30))):30,$s=e=>{if(!e)return null;const s=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!s)return null;const a=Number(s[1]),n=Number(s[2]),r=Number(s[3]),o=new Date(Date.UTC(a,n-1,r));return o.getUTCFullYear()!==a||o.getUTCMonth()!==n-1||o.getUTCDate()!==r?null:o},Gt=e=>e.toISOString().slice(0,10),_i=(e,s)=>{const a=new Date(e.getTime());return a.setUTCDate(a.getUTCDate()+s),a},Si=(e,s)=>{const a=s.getTime()-e.getTime(),n=Math.floor(a/864e5)+1;return nn(n)},ia=(e,s=new Date)=>{const a=nn(e.days),n=Gt(s),r=$s(e.endDate)??$s(n);if(!r)return{startDate:n,endDate:n,days:an};const o=$s(e.startDate);if(o){const u=r<o?o:r;return{startDate:Gt(o),endDate:Gt(u),days:Si(o,u)}}const l=_i(r,-(a-1));return{startDate:Gt(l),endDate:Gt(r),days:a}},ki=15e3,wi=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,Ci=(e={})=>{const{filters:s,autoRefreshMs:a=ki}=e,n=i.useMemo(()=>({startDate:s==null?void 0:s.startDate,endDate:s==null?void 0:s.endDate,days:(s==null?void 0:s.days)??30,endpoint:s==null?void 0:s.endpoint,model:s==null?void 0:s.model,limit:(s==null?void 0:s.limit)??100}),[s==null?void 0:s.startDate,s==null?void 0:s.endDate,s==null?void 0:s.days,s==null?void 0:s.endpoint,s==null?void 0:s.model,s==null?void 0:s.limit]),r=i.useMemo(()=>ia({startDate:n.startDate,endDate:n.endDate,days:n.days}),[n.days,n.endDate,n.startDate]),[o,l]=i.useState(null),[u,g]=i.useState([]),[m,c]=i.useState([]),[b,p]=i.useState(!1),[S,v]=i.useState(!1),[x,R]=i.useState(null),P=i.useCallback(async I=>{I?p(!0):v(!0);try{const h={startDate:r.startDate,endDate:r.endDate,endpoint:n.endpoint,model:n.model,limit:n.limit},[k,V,F]=await Promise.all([ts.getForwardSummary(h),ts.getForwardByEndpoint(h),ts.getForwardRequests(h)]);l(k),g(V),c(F),R(null)}catch(h){R(wi(h,"Failed to load forward metrics"))}finally{I?p(!1):v(!1)}},[n.endpoint,n.model,n.limit,r.endDate,r.startDate]),C=i.useCallback(async()=>{await P(!1)},[P]);return i.useEffect(()=>{P(!0)},[P]),i.useEffect(()=>{if(a<=0)return;const I=window.setInterval(()=>{P(!1)},a);return()=>{window.clearInterval(I)}},[a,P]),{summary:o,endpointMetrics:u,requests:m,isLoading:b,isRefreshing:S,error:x,refresh:C}},Mi=15e3,Pa=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,Ei=(e={})=>{const{filters:s,autoRefreshMs:a=Mi,service:n=ts}=e,r=i.useMemo(()=>({startDate:s==null?void 0:s.startDate,endDate:s==null?void 0:s.endDate,model:s==null?void 0:s.model,days:(s==null?void 0:s.days)??30,granularity:(s==null?void 0:s.granularity)??"daily",sessionLimit:(s==null?void 0:s.sessionLimit)??200}),[s==null?void 0:s.startDate,s==null?void 0:s.endDate,s==null?void 0:s.model,s==null?void 0:s.days,s==null?void 0:s.granularity,s==null?void 0:s.sessionLimit]),o=i.useMemo(()=>ia({startDate:r.startDate,endDate:r.endDate,days:r.days}),[r.days,r.endDate,r.startDate]),[l,u]=i.useState(null),[g,m]=i.useState([]),[c,b]=i.useState([]),[p,S]=i.useState([]),[v,x]=i.useState(null),[R,P]=i.useState([]),[C,I]=i.useState(null),[h,k]=i.useState(!1),[V,F]=i.useState(!1),[U,ee]=i.useState(!1),[$,j]=i.useState(null),T=i.useCallback(async O=>{O?F(!0):ee(!0);try{const Y=n.getMemorySummary?n.getMemorySummary().catch(()=>null):Promise.resolve(null),G=n.getMemoryTimeline?n.getMemoryTimeline({days:o.days,endDate:o.endDate,granularity:r.granularity}).catch(()=>[]):Promise.resolve([]),[ne,ie,be,d,E,M]=await Promise.all([n.getSummary({startDate:o.startDate,endDate:o.endDate}),n.getByModel({startDate:o.startDate,endDate:o.endDate}),n.getSessions({startDate:o.startDate,endDate:o.endDate,model:r.model,limit:r.sessionLimit}),n.getDaily({days:o.days,endDate:o.endDate,granularity:r.granularity}),Y,G]);u(ne),m(ie),b(be),S(d),x(E),P(M),j(null)}catch(Y){j(Pa(Y,"Failed to load metrics"))}finally{O?F(!1):ee(!1)}},[r.granularity,r.model,r.sessionLimit,o.days,o.endDate,o.startDate,n]),D=i.useCallback(async()=>{await T(!1)},[T]),A=i.useCallback(async O=>{k(!0);try{const Y=await n.getSessionDetail(O);I(Y)}catch(Y){j(Pa(Y,"Failed to load session detail"))}finally{k(!1)}},[n]),Q=i.useCallback(()=>{I(null)},[]);return i.useEffect(()=>{T(!0)},[T]),i.useEffect(()=>{if(a<=0)return;const O=window.setInterval(()=>{T(!1)},a);return()=>{window.clearInterval(O)}},[a,T]),{summary:l,modelMetrics:g,sessions:c,timeline:p,memorySummary:v,memoryTimeline:R,sessionDetail:C,isLoading:V,isRefreshing:U,isSessionDetailLoading:h,error:$,refresh:D,loadSessionDetail:A,clearSessionDetail:Q}},Pi=15e3,Di=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,Ii=(e={})=>{const{filters:s,autoRefreshMs:a=Pi}=e,n=i.useMemo(()=>({startDate:s==null?void 0:s.startDate,endDate:s==null?void 0:s.endDate,days:(s==null?void 0:s.days)??30,model:s==null?void 0:s.model}),[s==null?void 0:s.days,s==null?void 0:s.endDate,s==null?void 0:s.model,s==null?void 0:s.startDate]),r=i.useMemo(()=>ia({startDate:n.startDate,endDate:n.endDate,days:n.days}),[n.days,n.endDate,n.startDate]),[o,l]=i.useState(null),[u,g]=i.useState(!1),[m,c]=i.useState(!1),[b,p]=i.useState(null),S=i.useCallback(async x=>{x?g(!0):c(!0);try{const R=await ts.getUsageBreakdown({startDate:r.startDate,endDate:r.endDate,model:n.model});l(R),p(null)}catch(R){p(Di(R,"Failed to load usage breakdown"))}finally{x?g(!1):c(!1)}},[n.model,r.endDate,r.startDate]),v=i.useCallback(async()=>{await S(!1)},[S]);return i.useEffect(()=>{S(!0)},[S]),i.useEffect(()=>{if(a<=0)return;const x=window.setInterval(()=>{S(!1)},a);return()=>{window.clearInterval(x)}},[a,S]),{data:o,isLoading:u,isRefreshing:m,error:b,refresh:v}},{useToken:Fi}=Te,Ai=({data:e,loading:s})=>{const{t:a}=ae(),{token:n}=Fi();if(s)return t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.charts.endpointDistribution"),children:t.jsx("div",{style:{width:"100%",height:240},children:t.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100%",color:n.colorTextSecondary},children:a("settings.common.loading")})})});if(e.length===0)return t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.charts.endpointDistribution"),children:t.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:240,color:n.colorTextSecondary},children:a("settings.charts.noForwardMetrics")})});const r=e.map(o=>({endpoint:o.endpoint.split(".").pop()||o.endpoint,requests:o.requests,successful:o.successful,failed:o.failed}));return t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.charts.endpointDistribution"),children:t.jsx("div",{style:{width:"100%",height:240},children:t.jsx(Ot,{children:t.jsxs(na,{data:r,children:[t.jsx(os,{strokeDasharray:"3 3"}),t.jsx(ls,{dataKey:"endpoint"}),t.jsx(cs,{}),t.jsx(Nt,{formatter:(o,l)=>[`${o}`,l.charAt(0).toUpperCase()+l.slice(1)]}),t.jsx(ra,{}),t.jsx(_s,{dataKey:"successful",fill:"var(--lotus-chart-secondary)",name:a("settings.common.successful"),fillOpacity:.9,radius:[4,4,0,0]}),t.jsx(_s,{dataKey:"failed",fill:"var(--lotus-chart-danger)",name:a("settings.common.failed"),fillOpacity:.9,radius:[4,4,0,0]})]})})})})},Bs=e=>e.replace(/\.0$/,""),rn=e=>e.toLocaleString(),on=e=>Number.isFinite(e)?e.toLocaleString(void 0,{maximumFractionDigits:20}):String(e),oa=e=>{if(!Number.isFinite(e))return String(e);const s=Math.abs(e);if(s>=1e9){const a=s>=1e10?0:1;return`${Bs((e/1e9).toFixed(a))}B`}if(s>=1e6){const a=s>=1e7?0:1;return`${Bs((e/1e6).toFixed(a))}M`}if(s>=1e3){const a=s>=1e4?0:1;return`${Bs((e/1e3).toFixed(a))}K`}return rn(e)},Ri=e=>Number.isFinite(e)&&Math.abs(e)>=1e3,ln=e=>on(e),rs=e=>{if(!Number.isFinite(e))return String(e);const s=oa(e);return Ri(e)?t.jsx(ke,{title:t.jsx("div",{children:on(e)}),children:t.jsx("span",{children:s})}):s},lt=e=>{const s=Number(e??0);return Number.isFinite(s)?rs(s):e==null?"-":String(e)},{useToken:zi}=Te,Li=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),a=Math.floor(s/60),n=s%60;if(a>=60){const r=Math.floor(a/60),o=a%60;return`${r}h ${o}m`}return a>0?`${a}m ${n}s`:`${n}s`},Da=({summary:e,loading:s})=>{const{t:a}=ae(),{token:n}=zi();if(s)return t.jsx(gt,{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(Je,{gutter:[n.marginSM,n.marginSM],children:[t.jsx(me,{xs:24,sm:12,xl:6,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:a("settings.forwardMetricsCards.totalForwardRequests"),value:(e==null?void 0:e.total_requests)??0,precision:0,formatter:lt,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),t.jsx(me,{xs:24,sm:12,xl:6,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:a("settings.forwardMetricsCards.successRate"),value:r,suffix:"%",valueStyle:{color:Number(r)>=95?"var(--lotus-chart-secondary)":Number(r)>=80?"var(--lotus-chart-accent)":"var(--lotus-chart-danger)"}})})}),t.jsx(me,{xs:24,sm:12,xl:6,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:a("settings.forwardMetricsCards.forwardTokens"),value:(e==null?void 0:e.total_tokens.total_tokens)??0,precision:0,formatter:lt,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})}),t.jsx(me,{xs:24,sm:12,xl:6,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:a("settings.forwardMetricsCards.avgResponseTime"),value:Li(e==null?void 0:e.avg_duration_ms),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:kt}=ue,Oi=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),a=Math.floor(s/60),n=s%60;return a>0?`${a}m ${n}s`:`${n}s`},Ni=e=>new Date(e).toLocaleString(),Vi=({requests:e,loading:s})=>{const{t:a}=ae(),n=[{title:a("settings.metricsTable.forward.columns.id"),dataIndex:"forward_id",key:"forward_id",width:120,render:r=>t.jsxs(kt,{style:{fontSize:12},copyable:!0,children:[r.slice(0,8),"..."]})},{title:a("settings.metricsTable.forward.columns.endpoint"),dataIndex:"endpoint",key:"endpoint",width:150,render:r=>t.jsx(re,{color:"processing",children:r.split(".").pop()||r})},{title:a("settings.metricsTable.forward.columns.model"),dataIndex:"model",key:"model",width:120},{title:a("settings.metricsTable.forward.columns.type"),dataIndex:"is_stream",key:"is_stream",width:80,render:r=>t.jsx(re,{color:r?"purple":"processing",children:a(r?"settings.metricsTable.forward.typeStream":"settings.metricsTable.forward.typeSync")})},{title:a("settings.metricsTable.forward.columns.status"),key:"status",width:100,render:(r,o)=>{const l=o.status==="success"?"success":o.status==="error"?"error":"default";return t.jsx(Kn,{status:l,text:o.status_code?t.jsxs("span",{children:[o.status,t.jsxs(kt,{type:"secondary",style:{marginLeft:4},children:["(",o.status_code,")"]})]}):o.status||"-"})}},{title:a("settings.metricsTable.forward.columns.tokens"),key:"tokens",width:100,render:(r,o)=>o.token_usage?t.jsx(kt,{children:rs(o.token_usage.total_tokens)}):t.jsx(kt,{type:"secondary",children:"-"})},{title:a("settings.metricsTable.forward.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",width:100,render:r=>Oi(r)},{title:a("settings.metricsTable.forward.columns.started"),dataIndex:"started_at",key:"started_at",width:160,render:r=>t.jsx(kt,{type:"secondary",style:{fontSize:12},children:Ni(r)})},{title:a("settings.metricsTable.forward.columns.error"),dataIndex:"error",key:"error",width:200,render:r=>r?t.jsx(kt,{type:"danger",ellipsis:!0,style:{maxWidth:180},children:r}):t.jsx(kt,{type:"secondary",children:"-"})}];return t.jsx(at,{rowKey:"forward_id",className:"lotus-metric-table",columns:n,dataSource:e,loading:s,size:"small",pagination:{pageSize:10,showSizeChanger:!0,showTotal:r=>a("settings.metricsTable.forward.totalRequests",{total:r}),pageSizeOptions:["10","20","50","100"]},scroll:{x:1200},locale:{emptyText:a("settings.metricsTable.forward.empty")}})},{useToken:$i}=Te,Bi=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString()},Ia=({summary:e,loading:s})=>{const{t:a}=ae(),{token:n}=$i();return s?t.jsx(gt,{active:!0,paragraph:{rows:1}}):t.jsxs(Je,{gutter:[n.marginSM,n.marginSM],children:[t.jsx(me,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:a("settings.unifiedMetricsCards.totalMemories"),value:(e==null?void 0:e.total_memories)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:a("settings.unifiedMetricsCards.staleCandidates"),value:(e==null?void 0:e.stale_candidate_count)??0,precision:0,valueStyle:{color:((e==null?void 0:e.stale_candidate_count)??0)>0?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:a("settings.unifiedMetricsCards.memoryProjects"),value:(e==null?void 0:e.project_count)??0,precision:0,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:a("settings.unifiedMetricsCards.lastReindex"),value:Bi(e==null?void 0:e.last_reindex_at),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:qi}=ue,Hi=({data:e,loading:s})=>{const{t:a}=ae();return s?t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.charts.memoryTrendTitle"),children:t.jsx(gt,{active:!0,paragraph:{rows:5}})}):t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.charts.memoryTrendTitle"),children:e.length===0?t.jsx(He,{image:He.PRESENTED_IMAGE_SIMPLE,description:a("settings.charts.noMemoryTrend")}):t.jsxs(t.Fragment,{children:[t.jsx(qi,{type:"secondary",children:a("settings.charts.memoryTrendDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(Ot,{children:t.jsxs(en,{data:e,children:[t.jsx(os,{strokeDasharray:"3 3"}),t.jsx(ls,{dataKey:"label",minTickGap:24}),t.jsx(cs,{allowDecimals:!1}),t.jsx(Nt,{}),t.jsx(ra,{}),t.jsx(At,{type:"monotone",dataKey:"total_memories",name:a("settings.charts.totalMemories"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),t.jsx(At,{type:"monotone",dataKey:"created_memories",name:a("settings.charts.createdMemories"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),t.jsx(At,{type:"monotone",dataKey:"updated_memories",name:a("settings.charts.updatedMemories"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{useToken:Ui}=Te,Ki=e=>{const s=Math.floor(e/1e3),a=Math.floor(s/60),n=s%60;return a>0?`${a}m ${n}s`:`${n}s`},Wi=e=>{const s=e.filter(n=>typeof n.duration_ms=="number"&&n.duration_ms>0);if(s.length===0)return 0;const a=s.reduce((n,r)=>n+(r.duration_ms??0),0);return Math.floor(a/s.length)},Fa=({summary:e,sessions:s,loading:a})=>{const{t:n}=ae(),{token:r}=Ui();if(a)return t.jsx(gt,{active:!0,paragraph:{rows:1}});const o=Wi(s);return t.jsxs(Je,{gutter:[r.marginSM,r.marginSM],children:[t.jsx(me,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:n("settings.metricsCards.syncMismatches",{defaultValue:"Sync Mismatches"}),value:(e==null?void 0:e.total_sync_mismatches)??0,precision:0,valueStyle:{color:((e==null?void 0:e.total_sync_mismatches)??0)>0?"var(--lotus-chart-danger)":"var(--lotus-chart-secondary)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:n("settings.metricsCards.totalSessions"),value:(e==null?void 0:e.total_sessions)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:n("settings.metricsCards.chatTokens"),value:(e==null?void 0:e.total_tokens.total_tokens)??0,precision:0,formatter:lt,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:n("settings.metricsCards.totalToolCalls"),value:(e==null?void 0:e.total_tool_calls)??0,precision:0,formatter:lt,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:n("settings.metricsCards.tokensSaved",{defaultValue:"Saved Tokens"}),value:(e==null?void 0:e.total_tokens_saved)??0,precision:0,formatter:lt,valueStyle:{color:"var(--lotus-chart-cyan)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:n("settings.metricsCards.toolContextSavedTokens",{defaultValue:"Tool Context Saved Tokens"}),value:(e==null?void 0:e.tool_context_tokens_saved)??0,precision:0,formatter:lt,valueStyle:{color:"var(--lotus-chart-accent)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:n("settings.metricsCards.compressionEvents",{defaultValue:"Compression Events"}),value:(e==null?void 0:e.total_compression_events)??0,precision:0,formatter:lt,valueStyle:{color:"var(--lotus-chart-secondary)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:n("settings.metricsCards.avgSessionDuration"),value:o>0?Ki(o):"-",valueStyle:{color:"var(--lotus-chart-accent)"}})})})]})},{Text:Gi}=ue,Aa=["var(--lotus-chart-primary)","var(--lotus-chart-secondary)","var(--lotus-chart-accent)","var(--lotus-chart-purple)","var(--lotus-chart-cyan)"],Ji=({data:e,loading:s})=>{const{t:a}=ae();if(s)return t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.charts.modelDistribution"),children:t.jsx(gt,{active:!0,paragraph:{rows:5}})});const n=e.map(r=>({name:r.model,value:r.tokens.total_tokens}));return t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.charts.modelDistribution"),children:n.length===0?t.jsx(He,{image:He.PRESENTED_IMAGE_SIMPLE,description:a("settings.charts.noModelMetrics")}):t.jsxs(t.Fragment,{children:[t.jsx(Gi,{type:"secondary",children:a("settings.charts.modelDistributionDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(Ot,{children:t.jsxs(ar,{children:[t.jsx(nr,{data:n,cx:"50%",cy:"50%",outerRadius:90,fill:"var(--lotus-chart-primary)",dataKey:"value",nameKey:"name",label:!0,children:n.map((r,o)=>t.jsx(rr,{fill:Aa[o%Aa.length]},`${r.name}-${o}`))}),t.jsx(Nt,{formatter:r=>ln(r)})]})})})]})})},Xi=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?"-":s.toLocaleString()},Yi=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),a=Math.floor(s/60),n=s%60;if(a>=60){const r=Math.floor(a/60),o=a%60;return`${r}h ${o}m`}return a>0?`${a}m ${n}s`:`${n}s`},Zi=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"}},Qi=(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}},eo=({sessions:e,loading:s,onSelectSession:a})=>{const{t:n}=ae(),r=[{title:n("settings.metricsTable.session.columns.session"),dataIndex:"session_id",key:"session_id",render:o=>t.jsx(ke,{title:o,children:t.jsxs("span",{children:[o.slice(0,8),"..."]})}),width:120},{title:n("settings.metricsTable.session.columns.model"),dataIndex:"model",key:"model",width:160},{title:n("settings.metricsTable.session.columns.status"),dataIndex:"status",key:"status",width:120,render:o=>t.jsx(re,{color:Zi(o),children:Qi(o,n)})},{title:n("settings.metricsTable.session.columns.started"),dataIndex:"started_at",key:"started_at",render:o=>Xi(o),width:200,sorter:(o,l)=>new Date(o.started_at).getTime()-new Date(l.started_at).getTime(),defaultSortOrder:"descend"},{title:n("settings.metricsTable.session.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",render:o=>Yi(o),width:120},{title:n("settings.metricsTable.session.columns.tokens"),key:"tokens",render:(o,l)=>rs(l.total_token_usage.total_tokens),width:120,sorter:(o,l)=>o.total_token_usage.total_tokens-l.total_token_usage.total_tokens},{title:n("settings.metricsTable.session.columns.toolCalls"),dataIndex:"tool_call_count",key:"tool_call_count",width:120,sorter:(o,l)=>o.tool_call_count-l.tool_call_count},{title:n("settings.metricsTable.session.columns.messages"),dataIndex:"message_count",key:"message_count",width:120,sorter:(o,l)=>o.message_count-l.message_count},{title:n("settings.metricsTable.session.columns.action"),key:"action",fixed:"right",width:120,render:(o,l)=>t.jsx(z,{type:"link",onClick:()=>{a(l.session_id)},children:n("settings.metricsTable.session.view")})}];return t.jsx(at,{rowKey:"session_id",size:"small",className:"lotus-metric-table",columns:r,loading:s,dataSource:e,pagination:{pageSize:10,showSizeChanger:!1},scroll:{x:1100}})},{Text:to}=ue,Ra={message_count:"Message Count",last_message_id:"Last Message",pending_question:"Pending Question"},so=e=>Ra[e]?Ra[e]:e.split("_").map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "),ao=({breakdown:e,loading:s})=>{const{t:a}=ae();if(s)return t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),children:t.jsx(gt,{active:!0,paragraph:{rows:5}})});const n=Object.entries(e??{}).map(([r,o])=>({reason:r,label:a(`settings.syncMismatchReasons.${r}`,{defaultValue:so(r)}),count:o})).sort((r,o)=>o.count-r.count);return t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),extra:t.jsx(to,{type:"secondary",children:a("settings.metricsDashboard.syncMismatchBreakdownSubtitle",{defaultValue:"Grouped by execute sync mismatch reason"})}),children:n.length===0?t.jsx(He,{image:He.PRESENTED_IMAGE_SIMPLE,description:a("settings.metricsDashboard.noSyncMismatchBreakdown",{defaultValue:"No sync mismatches recorded for the selected range"})}):t.jsx("div",{style:{width:"100%",minWidth:0,height:280,minHeight:280},children:t.jsx(Ot,{children:t.jsxs(na,{data:n,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[t.jsx(os,{strokeDasharray:"3 3"}),t.jsx(ls,{type:"number",allowDecimals:!1}),t.jsx(cs,{dataKey:"label",type:"category",width:110}),t.jsx(Nt,{formatter:r=>[r.toLocaleString(),a("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})],labelFormatter:r=>a("settings.metricsDashboard.syncMismatchReasonLabel",{defaultValue:"Reason: {{label}}",label:r})}),t.jsx(_s,{dataKey:"count",fill:"var(--lotus-chart-danger)",radius:[0,6,6,0],name:a("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})})]})})})})},{Text:no}=ue,ro=({data:e,loading:s})=>{const{t:a}=ae();return s?t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.charts.tokenUsageOverTime"),children:t.jsx(gt,{active:!0,paragraph:{rows:5}})}):t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.charts.tokenUsageOverTime"),children:e.length===0?t.jsx(He,{image:He.PRESENTED_IMAGE_SIMPLE,description:a("settings.charts.noTokenUsage")}):t.jsxs(t.Fragment,{children:[t.jsx(no,{type:"secondary",children:a("settings.charts.tokenUsageDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(Ot,{children:t.jsxs(en,{data:e,children:[t.jsx(os,{strokeDasharray:"3 3"}),t.jsx(ls,{dataKey:"label",minTickGap:24}),t.jsx(cs,{allowDecimals:!1,tickFormatter:oa}),t.jsx(Nt,{formatter:n=>ln(n)}),t.jsx(ra,{}),t.jsx(At,{type:"monotone",dataKey:"totalTokens",name:a("settings.charts.total"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),t.jsx(At,{type:"monotone",dataKey:"promptTokens",name:a("settings.charts.prompt"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),t.jsx(At,{type:"monotone",dataKey:"completionTokens",name:a("settings.charts.completion"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{Text:io}=ue,Jt=({title:e,subtitle:s,emptyText:a,color:n="var(--lotus-chart-primary)",data:r,loading:o,countLabel:l})=>{const{t:u}=ae();return o?t.jsx(N,{size:"small",className:"lotus-metric-card",title:e,children:t.jsx(gt,{active:!0,paragraph:{rows:5}})}):t.jsx(N,{size:"small",className:"lotus-metric-card",title:e,children:r.length===0?t.jsx(He,{image:He.PRESENTED_IMAGE_SIMPLE,description:a}):t.jsxs(t.Fragment,{children:[s?t.jsx(io,{type:"secondary",children:s}):null,t.jsx("div",{style:{width:"100%",minWidth:0,height:280,marginTop:s?12:0},children:t.jsx(Ot,{children:t.jsxs(na,{data:r,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[t.jsx(os,{strokeDasharray:"3 3"}),t.jsx(ls,{type:"number",allowDecimals:!1}),t.jsx(cs,{dataKey:"label",type:"category",width:110}),t.jsx(Nt,{formatter:g=>[g.toLocaleString(),l??u("settings.metricsDashboard.calls",{defaultValue:"Calls"})],labelFormatter:(g,m)=>{var b,p;const c=(p=(b=m==null?void 0:m[0])==null?void 0:b.payload)==null?void 0:p.meta;return c?`${g} · ${c}`:String(g)}}),t.jsx(_s,{dataKey:"count",fill:n,radius:[0,6,6,0],name:l??u("settings.metricsDashboard.calls",{defaultValue:"Calls"})})]})})})]})})},{useToken:oo}=Te,za=({summary:e,loading:s})=>{const{t:a}=ae(),{token:n}=oo();if(s)return t.jsx(gt,{active:!0,paragraph:{rows:1}});const r=[{key:"skill-load-calls",title:a("settings.metricsDashboard.skillsAndMcp.cards.skillLoadCalls",{defaultValue:"Skill Loads"}),value:(e==null?void 0:e.skill_load_calls)??0,color:"var(--lotus-chart-primary)"},{key:"unique-skills",title:a("settings.metricsDashboard.skillsAndMcp.cards.uniqueSkills",{defaultValue:"Unique Skills"}),value:(e==null?void 0:e.unique_skills)??0,color:"var(--lotus-chart-purple)"},{key:"mcp-calls",title:a("settings.metricsDashboard.skillsAndMcp.cards.mcpCalls",{defaultValue:"MCP Calls"}),value:(e==null?void 0:e.mcp_calls)??0,color:"var(--lotus-chart-accent)"},{key:"unique-mcp-servers",title:a("settings.metricsDashboard.skillsAndMcp.cards.uniqueMcpServers",{defaultValue:"MCP Servers"}),value:(e==null?void 0:e.unique_mcp_servers)??0,color:"var(--lotus-chart-cyan)"},{key:"unique-mcp-tools",title:a("settings.metricsDashboard.skillsAndMcp.cards.uniqueMcpTools",{defaultValue:"MCP Tools"}),value:(e==null?void 0:e.unique_mcp_tools)??0,color:"var(--lotus-chart-secondary)"},{key:"core-tool-calls",title:a("settings.metricsDashboard.skillsAndMcp.cards.coreToolCalls",{defaultValue:"Core Tool Calls"}),value:(e==null?void 0:e.core_tool_calls)??0,color:"var(--lotus-metric-text-strong)"}].filter(o=>o.value>0);return r.length===0?null:t.jsx(Je,{gutter:[n.marginSM,n.marginSM],children:r.map(o=>t.jsx(me,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:o.title,value:o.value,precision:0,formatter:lt,valueStyle:{color:o.color}})})},o.key))})},{Text:wt}=ue,{useToken:lo}=Te,La=e=>"date"in e?e.date:e.label,co=(e,s)=>{if(s<=0||e<=0)return"var(--lotus-heat-0)";const a=e/s;return a>=.8?"var(--lotus-heat-4)":a>=.6?"var(--lotus-heat-3)":a>=.4?"var(--lotus-heat-2)":a>=.2?"var(--lotus-heat-1)":"var(--lotus-heat-0)"},hs=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),a=Math.floor(s/60),n=s%60;if(a>=60){const r=Math.floor(a/60),o=a%60;return`${r}h ${o}m`}return a>0?`${a}m ${n}s`:`${n}s`},Oa=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString()},qs=e=>{const s=Object.entries(e??{}).sort((a,n)=>n[1]-a[1]);return s.length===0?"-":s.slice(0,6).map(([a,n])=>`${a}: ${rn(n)}`).join(" • ")},Hs=(e,s=320)=>({width:"100%",display:"grid",gridTemplateColumns:`repeat(auto-fit, minmax(${s}px, 1fr))`,gap:e}),uo=()=>{const{t:e}=ae(),{token:s}=lo(),a=Sn(f=>f.themeMode)==="dark",[n,r]=i.useState(void 0),[o,l]=i.useState(void 0),[u,g]=i.useState(void 0),[m,c]=i.useState(30),[b,p]=i.useState("daily"),{summary:S,modelMetrics:v,sessions:x,timeline:R,memorySummary:P,memoryTimeline:C,sessionDetail:I,isLoading:h,isRefreshing:k,isSessionDetailLoading:V,error:F,refresh:U,loadSessionDetail:ee,clearSessionDetail:$}=Ei({filters:{startDate:n,endDate:o,model:u,days:m,granularity:b}}),{summary:j,endpointMetrics:T,requests:D,isLoading:A,isRefreshing:Q,error:O,refresh:Y}=Ci({filters:{startDate:n,endDate:o,days:m,model:u}}),{data:G,isLoading:ne,isRefreshing:ie,error:be,refresh:d}=Ii({filters:{startDate:n,endDate:o,days:m,model:u}}),E=i.useMemo(()=>R.map(f=>({label:La(f),promptTokens:f.total_token_usage.prompt_tokens,completionTokens:f.total_token_usage.completion_tokens,totalTokens:f.total_token_usage.total_tokens})),[R]),M=i.useMemo(()=>v.map(f=>({label:f.model,value:f.model})),[v]),K=i.useMemo(()=>{const f=R.map(ve=>({label:La(ve),sessions:ve.total_sessions,tokens:ve.total_token_usage.total_tokens})),ce=f.reduce((ve,Ne)=>Math.max(ve,Ne.sessions),0);return{points:f,maxSessions:ce}},[R]),se=i.useMemo(()=>{const f=D.map(ve=>ve.duration_ms).filter(ve=>typeof ve=="number"&&ve>0).sort((ve,Ne)=>ve-Ne);if(f.length===0)return null;const ce=Math.ceil(f.length*.95)-1;return f[Math.max(0,Math.min(ce,f.length-1))]},[D]),pe=i.useMemo(()=>[{title:e("settings.metricsDashboard.roundColumns.round"),dataIndex:"round_id",key:"round_id",render:f=>`${f.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:f=>hs(f)},{title:e("settings.metricsDashboard.roundColumns.tokens"),key:"tokens",render:(f,ce)=>rs(ce.token_usage.total_tokens)},{title:e("settings.metricsDashboard.roundColumns.toolCalls"),key:"tool_calls",render:(f,ce)=>ce.tool_calls.length}],[e]),ye=i.useMemo(()=>{const f=(S==null?void 0:S.total_sessions)??0,ce=(S==null?void 0:S.total_tokens.total_tokens)??0,ve=(S==null?void 0:S.total_tool_calls)??0,Ne=(S==null?void 0:S.active_sessions)??0,_e=x.reduce(($t,_)=>$t+_.total_rounds,0),Ve=(S==null?void 0:S.total_tokens_saved)??0,gs=(S==null?void 0:S.tool_context_tokens_saved)??0,Ms=(S==null?void 0:S.non_tool_compression_tokens_saved)??0,Es=(S==null?void 0:S.prompt_cached_tool_outputs)??0,Vt=(S==null?void 0:S.total_compression_events)??0,mt=(j==null?void 0:j.total_requests)??0,Ps=(j==null?void 0:j.total_tokens.total_tokens)??0,Ds=(j==null?void 0:j.failed_requests)??0,Is=D.filter($t=>$t.is_stream).length,ms=f>0?Ne/f*100:0,Fs=mt>0?Ds/mt*100:0,As=D.length>0?Is/D.length*100:0,bt=ce>0?Number((Ve/ce*100).toFixed(1)):0,Rs=Ve>0?Number((gs/Ve*100).toFixed(1)):0;return[{title:e("settings.metricsDashboard.compactStats.avgTokensPerSession"),value:f>0?Math.round(ce/f):0},{title:e("settings.metricsDashboard.compactStats.savedTokens",{defaultValue:"Saved Tokens"}),value:Ve},{title:e("settings.metricsDashboard.compactStats.toolContextSavedTokens",{defaultValue:"Tool Context Saved Tokens"}),value:gs},{title:e("settings.metricsDashboard.compactStats.nonToolCompressionSavedTokens",{defaultValue:"Non-Tool Compression Saved Tokens"}),value:Ms},{title:e("settings.metricsDashboard.compactStats.savedTokenRatio",{defaultValue:"Saved / Chat Tokens"}),value:bt,suffix:"%"},{title:e("settings.metricsDashboard.compactStats.toolSavedShare",{defaultValue:"Tool Share of Saved Tokens"}),value:Rs,suffix:"%"},{title:e("settings.metricsDashboard.compactStats.promptCachedToolOutputs",{defaultValue:"Prompt-Cached Tool Outputs"}),value:Es},{title:e("settings.metricsDashboard.compactStats.compressionEvents",{defaultValue:"Compression Events"}),value:Vt},{title:e("settings.metricsDashboard.compactStats.avgRoundsPerSession"),value:f>0?Number((_e/f).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.toolCallsPerSession"),value:f>0?Number((ve/f).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.activeSessionRate"),value:Number(ms.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.avgTokensPerForward"),value:mt>0?Math.round(Ps/mt):0},{title:e("settings.metricsDashboard.compactStats.forwardErrorRate"),value:Number(Fs.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.streamingRatio"),value:Number(As.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.p95ForwardLatency"),value:hs(se)},{title:e("settings.metricsDashboard.compactStats.modelCoverage"),value:v.length},{title:e("settings.metricsDashboard.compactStats.endpointCoverage"),value:T.length}]},[T.length,D,j,v.length,se,x,S,e]),je=i.useMemo(()=>{const f=(j==null?void 0:j.total_requests)??0,ce=(j==null?void 0:j.failed_requests)??0,ve=D.filter(Ve=>Ve.is_stream).length,Ne=D.length>0?ve/D.length*100:0,_e=f>0?ce/f*100:0;return[{title:e("settings.metricsDashboard.forward.performance.p95Latency",{defaultValue:"P95 Latency"}),value:hs(se)},{title:e("settings.metricsDashboard.forward.performance.errorRate",{defaultValue:"Error Rate"}),value:Number(_e.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.streamingRatio",{defaultValue:"Streaming Ratio"}),value:Number(Ne.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.endpointCoverage",{defaultValue:"Endpoint Coverage"}),value:T.length}]},[T.length,D,j,se,e]),B=i.useMemo(()=>G?[{label:e("settings.metricsDashboard.skillsAndMcp.mix.coreTools",{defaultValue:"Core Tools"}),count:G.core_tool_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.skillLoads",{defaultValue:"Skill Loads"}),count:G.skill_load_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.mcpCalls",{defaultValue:"MCP Calls"}),count:G.mcp_calls}].filter(f=>f.count>0):[],[e,G]),we=i.useMemo(()=>((G==null?void 0:G.top_skills)??[]).map(f=>({label:f.skill_id,count:f.count})),[G]),We=i.useMemo(()=>((G==null?void 0:G.top_mcp_servers)??[]).map(f=>({label:f.server_id,count:f.count,meta:e("settings.metricsDashboard.skillsAndMcp.meta.uniqueTools",{defaultValue:"{{count}} tools",count:f.unique_tools})})),[e,G]),Ie=i.useMemo(()=>((G==null?void 0:G.top_mcp_tools)??[]).map(f=>({label:f.tool_name,count:f.count,meta:f.server_id})),[G]),Oe=i.useMemo(()=>((G==null?void 0:G.top_core_tools)??[]).map(f=>({label:f.name,count:f.count})),[G]),Pe=I==null?void 0:I.session,Ge=k||Q||ie;return t.jsxs(L,{direction:"vertical",size:s.marginMD,style:{width:"100%"},children:[F?t.jsx(qe,{type:"error",showIcon:!0,message:F}):null,O?t.jsx(qe,{type:"error",showIcon:!0,message:O}):null,be?t.jsx(qe,{type:"error",showIcon:!0,message:be}):null,t.jsx(N,{size:"small",title:e("settings.metricsDashboard.filtersTitle"),extra:t.jsx(z,{icon:t.jsx(Lt,{}),loading:Ge,onClick:()=>{U(),Y(),d()},children:e("settings.metricsDashboard.refresh")}),children:t.jsxs(L,{wrap:!0,children:[t.jsx(xa,{placeholder:e("settings.metricsDashboard.startDate"),onChange:f=>{r(f?f.format("YYYY-MM-DD"):void 0)}}),t.jsx(xa,{placeholder:e("settings.metricsDashboard.endDate"),onChange:f=>{l(f?f.format("YYYY-MM-DD"):void 0)}}),t.jsx(te,{allowClear:!0,style:{minWidth:180},placeholder:e("settings.metricsDashboard.model"),value:u,options:M,onChange:f=>{g(f)}}),t.jsx(te,{style:{width:120},value:m,options:[7,14,30,90].map(f=>({label:e("settings.metricsDashboard.daysOption",{value:f}),value:f})),onChange:f=>{c(f)}}),t.jsx(te,{style:{width:140},value:b,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:f=>{p(f)}})]})}),t.jsx(N,{size:"small",title:e("settings.metricsDashboard.dashboardTitle"),children:t.jsx(Ts,{size:"small",destroyInactiveTabPane:!0,items:[{key:"overview",label:e("settings.metricsDashboard.tabs.overview"),children:t.jsxs(L,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(N,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.overviewSections.scaleTitle",{defaultValue:"Scale & Activity"}),extra:t.jsx(wt,{type:"secondary",children:e("settings.metricsDashboard.overviewSections.scaleSubtitle",{defaultValue:"Current usage volume across chat, forward, skills, and memory."})}),children:t.jsxs(L,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(Fa,{summary:S,sessions:x,loading:h}),t.jsx(Da,{summary:j,loading:A}),t.jsx(za,{summary:G,loading:ne}),t.jsx(Ia,{summary:P,loading:h})]})}),t.jsxs(N,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.overviewSections.efficiencyTitle",{defaultValue:"Compression & Efficiency Advantage"}),extra:t.jsx(wt,{type:"secondary",children:e("settings.metricsDashboard.overviewSections.efficiencySubtitle",{defaultValue:"Real savings from context compression, especially around tool-heavy workflows."})}),children:[t.jsx(Je,{gutter:[s.marginSM,s.marginSM],children:ye.map(f=>t.jsx(me,{xs:24,sm:12,md:8,xl:6,children:t.jsx("div",{style:{borderRadius:s.borderRadiusSM,padding:s.paddingXS,background:a?"rgba(255, 255, 255, 0.05)":"rgba(255, 255, 255, 0.82)",border:a?"1px solid rgba(255,255,255,0.08)":"1px solid rgba(148,163,184,0.18)"},children:t.jsx(Ee,{title:f.title,value:f.value,suffix:f.suffix,formatter:typeof f.value=="number"?lt:void 0,valueStyle:{fontSize:s.fontSizeHeading4}})})},f.title))}),t.jsx(wt,{type:"secondary",style:{display:"block",marginTop:s.marginXS},children:e("settings.metricsDashboard.efficiencyHint",{defaultValue:"这些指标优先使用真实运行统计:总节约 Tokens、工具上下文压缩节约、非工具压缩节约、压缩事件数,以及会话 / Forward 的平均负载与质量指标。"})})]})]})},{key:"chat",label:e("settings.metricsDashboard.tabs.chat",{defaultValue:"Chat"}),children:t.jsxs(L,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(Fa,{summary:S,sessions:x,loading:h}),t.jsxs("div",{style:Hs(s.marginSM,360),children:[t.jsx(ro,{data:E,loading:h}),t.jsx(Ji,{data:v,loading:h})]}),t.jsxs("div",{style:Hs(s.marginSM,360),children:[t.jsx(ao,{breakdown:S==null?void 0:S.sync_mismatch_breakdown,loading:h}),t.jsx(N,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.activityHeatmapTitle"),children:K.points.length===0?t.jsx(wt,{type:"secondary",children:e("settings.metricsDashboard.noActivity")}):t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(72px, 1fr))",gap:s.marginXS},children:K.points.map(f=>t.jsxs("div",{style:{borderRadius:s.borderRadiusSM,padding:s.paddingXS,background:co(f.sessions,K.maxSessions),minHeight:64,color:f.sessions>0?"var(--lotus-metric-text-strong)":s.colorTextSecondary},children:[t.jsx("div",{style:{fontSize:12,lineHeight:1.2},children:f.label}),t.jsx("div",{style:{fontWeight:600,marginTop:4},children:e("settings.metricsDashboard.sessionsCount",{count:f.sessions})}),t.jsx("div",{style:{fontSize:12},children:e("settings.metricsDashboard.tokensAmount",{value:oa(f.tokens)})})]},f.label))})})]})]})},{key:"skills-and-mcp",label:e("settings.metricsDashboard.tabs.skillsAndMcp",{defaultValue:"Skills & MCP"}),children:t.jsxs(L,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(za,{summary:G,loading:ne}),t.jsxs("div",{style:Hs(s.marginSM,360),children:[t.jsx(Jt,{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:ne,color:"var(--lotus-chart-primary)"}),t.jsx(Jt,{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:we,loading:ne,color:"var(--lotus-chart-purple)"}),t.jsx(Jt,{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:We,loading:ne,color:"var(--lotus-chart-cyan)"}),t.jsx(Jt,{title:e("settings.metricsDashboard.skillsAndMcp.topMcpToolsTitle",{defaultValue:"Top MCP Tools"}),subtitle:e("settings.metricsDashboard.skillsAndMcp.topMcpToolsSubtitle",{defaultValue:"Most frequently called MCP tool aliases."}),emptyText:e("settings.metricsDashboard.skillsAndMcp.noMcpTools",{defaultValue:"No MCP tools were called in this range."}),data:Ie,loading:ne,color:"var(--lotus-chart-accent)"}),t.jsx(Jt,{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:ne,color:"var(--lotus-chart-secondary)"})]})]})},{key:"forward",label:e("settings.metricsDashboard.tabs.forward",{defaultValue:"Forward"}),children:t.jsxs(L,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(Da,{summary:j,loading:A}),t.jsx(N,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.forward.performanceTitle",{defaultValue:"Forward Performance"}),children:t.jsx(Je,{gutter:[s.marginSM,s.marginSM],children:je.map(f=>t.jsx(me,{xs:24,sm:12,xl:6,children:t.jsx("div",{style:{borderRadius:s.borderRadiusSM,padding:s.paddingXS,background:a?"rgba(255, 255, 255, 0.05)":"rgba(255, 255, 255, 0.82)",border:a?"1px solid rgba(255,255,255,0.08)":"1px solid rgba(148,163,184,0.18)"},children:t.jsx(Ee,{title:f.title,value:f.value,suffix:f.suffix,valueStyle:{fontSize:s.fontSizeHeading4}})})},f.title))})}),t.jsx(Ai,{data:T,loading:A})]})},{key:"memory",label:e("settings.metricsDashboard.tabs.memory",{defaultValue:"Memory"}),children:t.jsxs(L,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(Ia,{summary:P,loading:h}),t.jsx(Hi,{data:C,loading:h}),t.jsx(N,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.memory.breakdownTitle",{defaultValue:"Memory Breakdown"}),children:t.jsxs(ze,{size:"small",bordered:!0,column:1,children:[t.jsx(ze.Item,{label:e("settings.metricsDashboard.memory.byType",{defaultValue:"By Type"}),children:qs(P==null?void 0:P.by_type)}),t.jsx(ze.Item,{label:e("settings.metricsDashboard.memory.byStatus",{defaultValue:"By Status"}),children:qs(P==null?void 0:P.by_status)}),t.jsx(ze.Item,{label:e("settings.metricsDashboard.memory.byScope",{defaultValue:"By Scope"}),children:qs(P==null?void 0:P.by_scope)}),t.jsx(ze.Item,{label:e("settings.metricsDashboard.memory.lastDream",{defaultValue:"Last Dream"}),children:Oa(P==null?void 0:P.last_dream_at)}),t.jsx(ze.Item,{label:e("settings.metricsDashboard.memory.lastReindex",{defaultValue:"Last Reindex"}),children:Oa(P==null?void 0:P.last_reindex_at)})]})})]})},{key:"records",label:e("settings.metricsDashboard.tabs.records"),children:t.jsx(Ts,{size:"small",destroyInactiveTabPane:!0,items:[{key:"sessions",label:e("settings.metricsDashboard.sessionsTabLabel",{count:x.length}),children:t.jsx(N,{size:"small",extra:t.jsx(wt,{type:"secondary",children:e("settings.metricsDashboard.sessionsHint")}),children:t.jsx(eo,{sessions:x,loading:h,onSelectSession:f=>{ee(f)}})})},{key:"forward-requests",label:e("settings.metricsDashboard.forwardTabLabel",{count:D.length}),children:t.jsx(N,{size:"small",children:t.jsx(Vi,{requests:D,loading:A})})}]})}]})}),t.jsx(Qe,{title:e("settings.metricsDashboard.sessionMetricsTitle"),open:!!I,onCancel:$,onOk:$,width:960,destroyOnClose:!0,children:V?t.jsx(wt,{children:e("settings.metricsDashboard.loadingSessionDetails")}):Pe?t.jsxs(L,{direction:"vertical",style:{width:"100%"},size:s.marginMD,children:[t.jsxs(ze,{size:"small",bordered:!0,column:2,children:[t.jsx(ze.Item,{label:e("settings.metricsDashboard.sessionDetail.sessionId"),span:2,children:Pe.session_id}),t.jsx(ze.Item,{label:e("settings.metricsDashboard.sessionDetail.model"),children:Pe.model}),t.jsx(ze.Item,{label:e("settings.metricsDashboard.sessionDetail.status"),children:Pe.status}),t.jsx(ze.Item,{label:e("settings.metricsDashboard.sessionDetail.duration"),children:hs(Pe.duration_ms)}),t.jsx(ze.Item,{label:e("settings.metricsDashboard.sessionDetail.messages"),children:Pe.message_count}),t.jsx(ze.Item,{label:e("settings.metricsDashboard.sessionDetail.totalTokens"),children:rs(Pe.total_token_usage.total_tokens)}),t.jsx(ze.Item,{label:e("settings.metricsDashboard.sessionDetail.toolCalls"),children:Pe.tool_call_count})]}),t.jsx(at,{rowKey:"round_id",size:"small",columns:pe,dataSource:I.rounds,pagination:{pageSize:6,showSizeChanger:!1}})]}):t.jsx(wt,{type:"secondary",children:e("settings.metricsDashboard.noDetail")})})]})},{Text:fs}=ue,{useToken:go}=Te,mo=e=>{const s=e==null?void 0:e.hooks,a=s==null?void 0:s.image_fallback,n=String((a==null?void 0:a.mode)||"placeholder").trim().toLowerCase();return n==="error"||n==="ocr"||n==="vision"?n:"placeholder"},po=e=>{const s=e==null?void 0:e.hooks,a=s==null?void 0:s.image_fallback,n=a==null?void 0:a.enabled;return typeof n=="boolean"?n:!1},ho=()=>{const{t:e}=ae(),{token:s}=go(),[a,n]=zt.useMessage(),[r,o]=i.useState(!1),[l,u]=i.useState(!0),[g,m]=i.useState("placeholder"),c=i.useMemo(()=>[{label:e("settings.hooksTab.mode.placeholder"),value:"placeholder"},{label:e("settings.hooksTab.mode.error"),value:"error"},{label:e("settings.hooksTab.mode.ocr"),value:"ocr"},{label:e("settings.hooksTab.mode.vision"),value:"vision"}],[e]),b=i.useCallback(async()=>{o(!0);try{const x=await Re.getBambooConfig();u(po(x)),m(mo(x))}catch(x){a.error(x instanceof Error?x.message:e("settings.hooksTab.loadFailed"))}finally{o(!1)}},[a,e]),p=i.useCallback(async(x,R)=>{await Re.setBambooConfig({hooks:{image_fallback:{enabled:x,mode:R}}})},[]),S=i.useCallback(async x=>{o(!0);try{await p(x,g),a.success(e(x?"settings.hooksTab.enabled":"settings.hooksTab.disabled")),await b()}catch(R){a.error(R instanceof Error?R.message:e("settings.hooksTab.updateFailed"))}finally{o(!1)}},[b,g,a,p,e]),v=i.useCallback(async x=>{var R;o(!0);try{await p(l,x),a.success(e("settings.hooksTab.modeUpdated",{mode:((R=c.find(P=>P.value===x))==null?void 0:R.label)??x})),await b()}catch(P){a.error(P instanceof Error?P.message:e("settings.hooksTab.modeUpdateFailed"))}finally{o(!1)}},[l,b,c,a,p,e]);return i.useEffect(()=>{b()},[b]),t.jsxs(X,{vertical:!0,gap:s.marginLG,children:[n,t.jsx(N,{size:"small",loading:r,children:t.jsxs(X,{vertical:!0,gap:s.marginXS,children:[t.jsx(fs,{strong:!0,children:e("settings.hooksTab.title")}),t.jsxs(X,{align:"center",justify:"space-between",children:[t.jsx(fs,{children:e("settings.hooksTab.enableImagePreflight")}),t.jsx(fe,{checked:l,onChange:S})]}),t.jsxs(X,{align:"center",justify:"space-between",children:[t.jsx(fs,{children:e("settings.hooksTab.modeLabel")}),t.jsx(te,{style:{width:180},value:g,options:c,onChange:v,disabled:!l})]}),t.jsx(fs,{type:"secondary",style:{fontSize:s.fontSizeSM},children:e("settings.hooksTab.description")})]})})]})};function De(e){return String(e??"").trim()||void 0}function cn(e){return{type:"interval",every_seconds:e}}function fo(e){const s=De(e);if(!s)return{days:[],invalid:!1};const n=s.split(/[\s,]+/).filter(Boolean).map(l=>Number(l)),r=n.some(l=>!Number.isInteger(l)||l<1||l>31);return{days:Array.from(new Set(n.filter(l=>Number.isInteger(l)&&l>=1&&l<=31))),invalid:r}}function Na(e){switch(e.trigger_type){case"interval":{const s=Number(e.interval_seconds||0);return s<=0?{errorKey:"settings.schedulesTab.validation.intervalRequired"}:{trigger:cn(s)}}case"daily":{const s=e.daily_hour,a=e.daily_minute;return s==null||a==null?{errorKey:"settings.schedulesTab.validation.triggerRequired"}:{trigger:{type:"daily",hour:s,minute:a,second:0}}}case"weekly":{const s=e.weekly_weekdays||[],a=e.weekly_hour,n=e.weekly_minute;return s.length===0?{errorKey:"settings.schedulesTab.validation.weekdaysRequired"}:a==null||n==null?{errorKey:"settings.schedulesTab.validation.triggerRequired"}:{trigger:{type:"weekly",weekdays:s,hour:a,minute:n,second:0}}}case"monthly":{const{days:s,invalid:a}=fo(e.monthly_days);if(a)return{errorKey:"settings.schedulesTab.validation.invalidMonthDays"};if(s.length===0)return{errorKey:"settings.schedulesTab.validation.monthDaysRequired"};const n=e.monthly_hour,r=e.monthly_minute;return n==null||r==null?{errorKey:"settings.schedulesTab.validation.triggerRequired"}:{trigger:{type:"monthly",days:s,hour:n,minute:r,second:0}}}case"cron":{const s=De(e.cron_expr);return s?{trigger:{type:"cron",expr:s}}:{errorKey:"settings.schedulesTab.validation.cronRequired"}}default:return{errorKey:"settings.schedulesTab.validation.triggerRequired"}}}function Va(e){switch(e.misfire_policy){case"skip":return{type:"skip"};case"catch_up_all":return{type:"catch_up_all"};case"catch_up_window":return{type:"catch_up_window",max_catch_up_runs:Number(e.catch_up_window_max_runs||1),max_lateness_seconds:Number(e.catch_up_window_max_lateness_seconds||60)};case"run_once":default:return{type:"run_once"}}}const{Text:Fe}=ue,rt=sa.getInstance();function yo(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 xo=[{label:oe.t("settings.schedulesTab.weekdays.mon"),value:"mon"},{label:oe.t("settings.schedulesTab.weekdays.tue"),value:"tue"},{label:oe.t("settings.schedulesTab.weekdays.wed"),value:"wed"},{label:oe.t("settings.schedulesTab.weekdays.thu"),value:"thu"},{label:oe.t("settings.schedulesTab.weekdays.fri"),value:"fri"},{label:oe.t("settings.schedulesTab.weekdays.sat"),value:"sat"},{label:oe.t("settings.schedulesTab.weekdays.sun"),value:"sun"}];function bo(e){return(e==null?void 0:e.type)==="interval"?e.every_seconds:null}function vo(e){switch(e.type){case"interval":return oe.t("settings.schedulesTab.triggerLabels.interval",{type:oe.t("settings.schedulesTab.triggerTypes.interval"),seconds:e.every_seconds});case"daily":return oe.t("settings.schedulesTab.triggerLabels.daily",{type:oe.t("settings.schedulesTab.triggerTypes.daily"),time:`${String(e.hour).padStart(2,"0")}:${String(e.minute).padStart(2,"0")}`});case"weekly":return oe.t("settings.schedulesTab.triggerLabels.weekly",{type:oe.t("settings.schedulesTab.triggerTypes.weekly"),weekdays:e.weekdays.join(", ")});case"monthly":return oe.t("settings.schedulesTab.triggerLabels.monthly",{type:oe.t("settings.schedulesTab.triggerTypes.monthly"),days:e.days.join(", ")});case"cron":return oe.t("settings.schedulesTab.triggerLabels.cron",{type:oe.t("settings.schedulesTab.triggerTypes.cron"),expr:e.expr})}}function jo(e){switch(e==null?void 0:e.type){case"skip":return oe.t("settings.schedulesTab.misfirePolicyOptions.skip");case"catch_up_all":return oe.t("settings.schedulesTab.misfirePolicyOptions.catchUpAll");case"catch_up_window":return oe.t("settings.schedulesTab.misfirePolicyOptions.catchUpWindow");case"run_once":default:return oe.t("settings.schedulesTab.misfirePolicyOptions.runOnce")}}function To(e){switch(e){case"allow":return oe.t("settings.schedulesTab.overlapPolicyOptions.allow");case"skip":return oe.t("settings.schedulesTab.overlapPolicyOptions.skip");case"queue_one":default:return oe.t("settings.schedulesTab.overlapPolicyOptions.queueOne")}}function _o(e){var s;return(s=e.state)!=null&&s.next_fire_at?String(e.state.next_fire_at):"-"}function So(e){var s,a;return(s=e.state)!=null&&s.last_success_at?String(e.state.last_success_at):(a=e.state)!=null&&a.last_finished_at?String(e.state.last_finished_at):"-"}function ko(e){var s,a,n,r;return((s=e.state)==null?void 0:s.running_run_count)>0?{color:"processing",label:oe.t("settings.schedulesTab.statusLabels.running"),detail:oe.t("settings.schedulesTab.statusDetails.active",{count:e.state.running_run_count})}:(((a=e.state)==null?void 0:a.queued_run_count)||0)>0?{color:"gold",label:oe.t("settings.schedulesTab.statusLabels.queued"),detail:oe.t("settings.schedulesTab.statusDetails.pending",{count:e.state.queued_run_count})}:(((n=e.state)==null?void 0:n.consecutive_failures)||0)>0?{color:"error",label:oe.t("settings.schedulesTab.statusLabels.failing"),detail:oe.t("settings.schedulesTab.statusDetails.consecutiveFailures",{count:e.state.consecutive_failures})}:e.enabled?(r=e.state)!=null&&r.last_success_at?{color:"success",label:oe.t("settings.schedulesTab.statusLabels.healthy"),detail:oe.t("settings.schedulesTab.statusDetails.lastRunSucceeded")}:{color:"default",label:oe.t("settings.schedulesTab.statusLabels.idle")}:{color:"default",label:oe.t("settings.schedulesTab.statusLabels.disabled")}}function wo(e){var a,n,r,o,l,u,g,m;const s={name:e.name,enabled:e.enabled,trigger_type:e.trigger.type,timezone:e.timezone||"",start_at:e.start_at||"",end_at:e.end_at||"",misfire_policy:((a=e.misfire_policy)==null?void 0:a.type)||"run_once",overlap_policy:e.overlap_policy||"queue_one",system_prompt:((n=e.run_config)==null?void 0:n.system_prompt)||"",task_message:((r=e.run_config)==null?void 0:r.task_message)||"",model:((o=e.run_config)==null?void 0:o.model)||"",workspace_path:((l=e.run_config)==null?void 0:l.workspace_path)||"",enhance_prompt:((u=e.run_config)==null?void 0:u.enhance_prompt)||"",auto_execute:!!((g=e.run_config)!=null&&g.auto_execute)};switch(((m=e.misfire_policy)==null?void 0:m.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 Us({hourName:e,minuteName:s}){const{t:a}=ae();return t.jsxs(X,{gap:12,wrap:"wrap",children:[t.jsx(y.Item,{label:a("settings.schedulesTab.form.dailyHour"),name:e,style:{width:180},children:t.jsx(Me,{min:0,max:23,style:{width:"100%"}})}),t.jsx(y.Item,{label:a("settings.schedulesTab.form.dailyMinute"),name:s,style:{width:180},children:t.jsx(Me,{min:0,max:59,style:{width:"100%"}})})]})}function Co(){const{t:e}=ae(),[s,a]=zt.useMessage(),[n,r]=i.useState(!1),[o,l]=i.useState([]),[u,g]=i.useState({open:!1,scheduleId:null,sessions:[],loading:!1}),[m,c]=i.useState({open:!1,scheduleId:null,runs:[],loading:!1}),[b,p]=i.useState({open:!1,schedule:null,saving:!1}),S=Ys(j=>j.close),[v]=y.useForm(),[x]=y.useForm(),R=y.useWatch("trigger_type",v),P=y.useWatch("misfire_policy",v),C=y.useWatch("trigger_type",x),I=y.useWatch("misfire_policy",x),h=i.useCallback(async()=>{r(!0);try{const j=await rt.listSchedules();l(j.schedules||[])}catch(j){console.error("[Schedules] Failed to load schedules:",j),s.error(e("settings.schedulesTab.loadFailed"))}finally{r(!1)}},[s,e]),k=i.useCallback(async(j,T,D)=>{try{await D()}catch(A){console.error(`[Schedules] ${j}:`,A),s.error(e(T))}},[s,e]);i.useEffect(()=>{h()},[h]);const V=[{value:"interval",label:e("settings.schedulesTab.triggerTypes.interval")},{value:"daily",label:e("settings.schedulesTab.triggerTypes.daily")},{value:"weekly",label:e("settings.schedulesTab.triggerTypes.weekly")},{value:"monthly",label:e("settings.schedulesTab.triggerTypes.monthly")},{value:"cron",label:e("settings.schedulesTab.triggerTypes.cron")}],F=[{value:"run_once",label:e("settings.schedulesTab.misfirePolicyOptions.runOnce")},{value:"skip",label:e("settings.schedulesTab.misfirePolicyOptions.skip")},{value:"catch_up_all",label:e("settings.schedulesTab.misfirePolicyOptions.catchUpAll")},{value:"catch_up_window",label:e("settings.schedulesTab.misfirePolicyOptions.catchUpWindow")}],U=[{value:"queue_one",label:e("settings.schedulesTab.overlapPolicyOptions.queueOne")},{value:"skip",label:e("settings.schedulesTab.overlapPolicyOptions.skip")},{value:"allow",label:e("settings.schedulesTab.overlapPolicyOptions.allow")}],ee=(j,T)=>t.jsxs(t.Fragment,{children:[t.jsxs(X,{gap:12,wrap:"wrap",children:[t.jsx(y.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(y.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:V})}),t.jsx(y.Item,{label:e("settings.schedulesTab.form.enabled"),name:"enabled",valuePropName:"checked",style:{width:120},children:t.jsx(fe,{})})]}),j==="interval"?t.jsx(y.Item,{label:e("settings.schedulesTab.form.intervalSeconds"),name:"interval_seconds",rules:[{required:!0,message:e("settings.schedulesTab.validation.intervalRequired")}],style:{width:220},children:t.jsx(Me,{min:1,style:{width:"100%"}})}):null,j==="daily"?t.jsx(Us,{hourName:"daily_hour",minuteName:"daily_minute"}):null,j==="weekly"?t.jsxs(t.Fragment,{children:[t.jsx(y.Item,{label:e("settings.schedulesTab.form.weeklyWeekdays"),name:"weekly_weekdays",style:{minWidth:320},children:t.jsx(te,{mode:"multiple",options:xo})}),t.jsx(Us,{hourName:"weekly_hour",minuteName:"weekly_minute"})]}):null,j==="monthly"?t.jsxs(t.Fragment,{children:[t.jsx(y.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(Us,{hourName:"monthly_hour",minuteName:"monthly_minute"})]}):null,j==="cron"?t.jsx(y.Item,{label:e("settings.schedulesTab.form.cronExpr"),name:"cron_expr",children:t.jsx(H,{placeholder:e("settings.schedulesTab.form.cronExprPlaceholder")})}):null,t.jsxs(X,{gap:12,wrap:"wrap",children:[t.jsx(y.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(y.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(y.Item,{label:e("settings.schedulesTab.form.endAt"),name:"end_at",style:{flex:"1 1 240px"},children:t.jsx(H,{placeholder:e("settings.schedulesTab.form.datetimePlaceholder")})})]}),t.jsxs(X,{gap:12,wrap:"wrap",children:[t.jsx(y.Item,{label:e("settings.schedulesTab.form.misfirePolicy"),name:"misfire_policy",style:{flex:"1 1 240px"},children:t.jsx(te,{options:F})}),t.jsx(y.Item,{label:e("settings.schedulesTab.form.overlapPolicy"),name:"overlap_policy",style:{flex:"1 1 240px"},children:t.jsx(te,{options:U})})]}),T==="catch_up_window"?t.jsxs(X,{gap:12,wrap:"wrap",children:[t.jsx(y.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxRuns"),name:"catch_up_window_max_runs",style:{width:220},children:t.jsx(Me,{min:1,style:{width:"100%"}})}),t.jsx(y.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxLatenessSeconds"),name:"catch_up_window_max_lateness_seconds",style:{width:260},children:t.jsx(Me,{min:1,style:{width:"100%"}})})]}):null,t.jsx(y.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(y.Item,{label:e("settings.schedulesTab.form.systemPrompt"),name:"system_prompt",children:t.jsx(H.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})}),t.jsxs(X,{gap:12,wrap:"wrap",children:[t.jsx(y.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(y.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(y.Item,{label:e("settings.schedulesTab.form.autoExecute"),name:"auto_execute",valuePropName:"checked",style:{width:160},children:t.jsx(fe,{})})]}),t.jsx(y.Item,{label:e("settings.schedulesTab.form.enhancePrompt"),name:"enhance_prompt",children:t.jsx(H.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})})]}),$=i.useMemo(()=>[{title:e("settings.schedulesTab.columns.name"),key:"name",render:(j,T)=>t.jsxs(X,{vertical:!0,gap:6,children:[t.jsx(Fe,{strong:!0,children:T.name}),t.jsxs(X,{gap:6,wrap:"wrap",children:[t.jsx(re,{children:vo(T.trigger)}),T.timezone?t.jsx(re,{color:"blue",children:T.timezone}):null,t.jsx(re,{children:jo(T.misfire_policy)}),t.jsx(re,{children:To(T.overlap_policy)})]})]})},{title:e("settings.schedulesTab.columns.status"),key:"status",render:(j,T)=>{const D=ko(T);return t.jsxs(X,{vertical:!0,gap:4,children:[t.jsx(re,{color:D.color,children:D.label}),D.detail?t.jsx(Fe,{type:"secondary",children:D.detail}):null]})}},{title:e("settings.schedulesTab.columns.activity"),key:"activity",render:(j,T)=>{var D,A,Q,O;return t.jsxs(X,{vertical:!0,gap:2,children:[t.jsx(Fe,{type:"secondary",children:e("settings.schedulesTab.activityLabels.queued",{count:((D=T.state)==null?void 0:D.queued_run_count)??0})}),t.jsx(Fe,{type:"secondary",children:e("settings.schedulesTab.activityLabels.running",{count:((A=T.state)==null?void 0:A.running_run_count)??0})}),t.jsx(Fe,{type:"secondary",children:e("settings.schedulesTab.activityLabels.ok",{count:((Q=T.state)==null?void 0:Q.total_success_count)??0})}),t.jsx(Fe,{type:"secondary",children:e("settings.schedulesTab.activityLabels.fail",{count:((O=T.state)==null?void 0:O.total_failure_count)??0})})]})}},{title:e("settings.schedulesTab.columns.nextRun"),key:"next_run_at",render:(j,T)=>t.jsx(Fe,{type:"secondary",children:_o(T)})},{title:e("settings.schedulesTab.columns.lastRun"),key:"last_run_at",render:(j,T)=>t.jsx(Fe,{type:"secondary",children:So(T)})},{title:e("settings.schedulesTab.columns.autoExecute"),key:"auto_execute",render:(j,T)=>{var D,A;return t.jsx(Fe,{type:(D=T.run_config)!=null&&D.auto_execute?void 0:"secondary",children:(A=T.run_config)!=null&&A.auto_execute?e("settings.schedulesTab.yes"):e("settings.schedulesTab.no")})}},{title:e("settings.schedulesTab.columns.model"),key:"model",render:(j,T)=>{var D;return t.jsx(Fe,{type:"secondary",children:(D=T.run_config)!=null&&D.model?String(T.run_config.model):"-"})}},{title:e("settings.schedulesTab.columns.enabled"),key:"enabled",render:(j,T)=>t.jsx(fe,{checked:T.enabled,onChange:async D=>{await k("Failed to toggle","settings.schedulesTab.updateFailed",async()=>{await rt.patchSchedule(T.id,{enabled:D}),await h()})}})},{title:e("settings.schedulesTab.columns.actions"),key:"actions",render:(j,T)=>{const D=t.jsx(Me,{min:1,value:bo(T.trigger)??void 0,disabled:T.trigger.type!=="interval",onChange:async A=>{const Q=typeof A=="number"?A:null;!Q||Q<=0||await k("Failed to patch interval","settings.schedulesTab.updateFailed",async()=>{await rt.patchSchedule(T.id,{trigger:cn(Q)}),await h()})}});return t.jsxs(X,{vertical:!0,gap:8,children:[t.jsxs(X,{gap:8,wrap:"wrap",children:[t.jsx(z,{size:"small",onClick:()=>{p({open:!0,schedule:T,saving:!1}),x.setFieldsValue(wo(T))},children:e("settings.schedulesTab.actions.edit")}),t.jsx(z,{size:"small",onClick:async()=>{await k("Failed to run now","settings.schedulesTab.runNowFailed",async()=>{await rt.runScheduleNow(T.id),s.success(e("settings.schedulesTab.enqueuedRun")),await h()})},children:e("settings.schedulesTab.actions.runNow")}),t.jsx(z,{size:"small",onClick:async()=>{g(A=>({...A,open:!0,scheduleId:T.id,loading:!0,sessions:[]}));try{const A=await rt.listScheduleSessions(T.id);g(Q=>({...Q,open:!0,scheduleId:T.id,loading:!1,sessions:(A.sessions||[]).map(O=>({id:O.id,title:O.title,updated_at:O.updated_at}))}))}catch(A){console.error("[Schedules] Failed to list sessions:",A),s.error(e("settings.schedulesTab.loadSessionsFailed")),g(Q=>({...Q,loading:!1}))}},children:e("settings.schedulesTab.actions.sessions")}),t.jsx(z,{size:"small",onClick:async()=>{c(A=>({...A,open:!0,scheduleId:T.id,loading:!0,runs:[]}));try{const A=await rt.listScheduleRuns(T.id);c(Q=>({...Q,open:!0,scheduleId:T.id,loading:!1,runs:A.runs||[]}))}catch(A){console.error("[Schedules] Failed to list runs:",A),s.error(e("settings.schedulesTab.loadRunsFailed")),c(Q=>({...Q,loading:!1}))}},children:e("settings.schedulesTab.actions.runs")}),t.jsx(z,{danger:!0,size:"small",onClick:async()=>{await k("Failed to delete","settings.schedulesTab.deleteFailed",async()=>{await rt.deleteSchedule(T.id),s.success(e("settings.schedulesTab.deleted")),await h()})},children:e("settings.schedulesTab.actions.delete")})]}),t.jsxs(X,{gap:8,align:"center",wrap:"wrap",children:[t.jsx(Fe,{type:"secondary",children:e("settings.schedulesTab.columns.intervalSeconds")}),T.trigger.type==="interval"?D:t.jsx(ke,{title:e("settings.schedulesTab.nonIntervalReadOnly"),children:t.jsx("span",{children:D})})]})]})}}],[x,s,h,k,e]);return t.jsxs(X,{vertical:!0,gap:16,children:[a,t.jsx(N,{title:e("settings.schedulesTab.createTitle"),className:"lotus-settings-card",children:t.jsxs(y,{form:v,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 j=>{try{const T=!!j.auto_execute,D=De(j.task_message),A=De(j.model);if(T&&!D){s.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:Q,errorKey:O}=Na(j);if(!Q){s.error(e(O||"settings.schedulesTab.validation.triggerRequired"));return}await rt.createSchedule({name:String(j.name||"").trim(),trigger:Q,timezone:De(j.timezone),start_at:De(j.start_at),end_at:De(j.end_at),misfire_policy:Va(j),overlap_policy:j.overlap_policy,enabled:!!j.enabled,run_config:{system_prompt:De(j.system_prompt),task_message:D,model:A,workspace_path:De(j.workspace_path),enhance_prompt:De(j.enhance_prompt),auto_execute:T}}),s.success(e("settings.schedulesTab.created")),v.resetFields(),await h()}catch(T){console.error("[Schedules] Failed to create schedule:",T),s.error(e("settings.schedulesTab.createFailed"))}},children:[ee(R,P),t.jsx(z,{type:"primary",htmlType:"submit",children:e("settings.schedulesTab.actions.create")})]})}),t.jsx(N,{title:e("settings.schedulesTab.listTitle"),className:"lotus-settings-card",extra:t.jsx(z,{onClick:()=>void h(),loading:n,children:e("settings.schedulesTab.actions.refresh")}),children:t.jsx(at,{rowKey:"id",columns:$,dataSource:o,loading:n,pagination:{pageSize:10},scroll:{x:1500}})}),t.jsx(Qe,{title:e("settings.schedulesTab.scheduleSessionsTitle"),open:u.open,onCancel:()=>g(j=>({...j,open:!1,scheduleId:null})),footer:null,children:u.loading?t.jsx(Fe,{type:"secondary",children:e("settings.schedulesTab.loading")}):t.jsx(X,{vertical:!0,gap:8,children:u.sessions.length===0?t.jsx(Fe,{type:"secondary",children:e("settings.schedulesTab.noSessionsYet")}):u.sessions.map(j=>t.jsxs(X,{justify:"space-between",align:"center",children:[t.jsxs(X,{vertical:!0,style:{minWidth:0},children:[t.jsx(Fe,{strong:!0,ellipsis:!0,children:j.title}),t.jsxs(Fe,{type:"secondary",ellipsis:!0,children:[j.id," • ",j.updated_at]})]}),t.jsx(z,{size:"small",onClick:()=>{kn(j.id,{forceRefreshIndex:!0,forceLoadHistory:!0,subscribeIfRunning:!0,forceSubscribe:!0}),S()},children:e("settings.schedulesTab.actions.open")})]},j.id))})}),t.jsx(Qe,{title:e("settings.schedulesTab.scheduleRunsTitle"),open:m.open,onCancel:()=>c(j=>({...j,open:!1,scheduleId:null})),footer:null,width:960,children:m.loading?t.jsx(Fe,{type:"secondary",children:e("settings.schedulesTab.loading")}):m.runs.length===0?t.jsx(Fe,{type:"secondary",children:e("settings.schedulesTab.noRunsYet")}):t.jsx(at,{rowKey:"run_id",pagination:{pageSize:8},dataSource:m.runs,columns:[{title:e("settings.schedulesTab.runHistory.columns.status"),key:"status",render:(j,T)=>t.jsx(re,{color:yo(T.status),children:T.status})},{title:e("settings.schedulesTab.runHistory.columns.scheduledFor"),dataIndex:"scheduled_for",key:"scheduled_for"},{title:e("settings.schedulesTab.runHistory.columns.startedAt"),key:"started_at",render:(j,T)=>T.started_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.completedAt"),key:"completed_at",render:(j,T)=>T.completed_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.session"),key:"session_id",render:(j,T)=>T.session_id||"-"},{title:e("settings.schedulesTab.runHistory.columns.duration"),key:"execution_duration_ms",render:(j,T)=>T.execution_duration_ms!=null?`${T.execution_duration_ms}ms`:"-"},{title:e("settings.schedulesTab.runHistory.columns.outcome"),key:"outcome_reason",render:(j,T)=>T.outcome_reason||(T.was_catch_up?"catch-up":"-")}]})}),t.jsx(Qe,{title:e("settings.schedulesTab.editTitle"),open:b.open,onCancel:()=>p({open:!1,schedule:null,saving:!1}),okText:e("settings.schedulesTab.actions.save"),confirmLoading:b.saving,onOk:()=>x.submit(),forceRender:!0,children:t.jsx(y,{form:x,layout:"vertical",onFinish:async j=>{const T=b.schedule;if(!T)return;const D=!!j.auto_execute,A=De(j.task_message),Q=De(j.model);if(D&&!A){s.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:O,errorKey:Y}=Na(j);if(!O){s.error(e(Y||"settings.schedulesTab.validation.triggerRequired"));return}p(G=>({...G,saving:!0}));try{await rt.patchSchedule(T.id,{name:String(j.name||"").trim()||void 0,enabled:!!j.enabled,trigger:O,timezone:De(j.timezone),start_at:De(j.start_at),end_at:De(j.end_at),misfire_policy:Va(j),overlap_policy:j.overlap_policy,run_config:{system_prompt:De(j.system_prompt),task_message:A,model:Q,workspace_path:De(j.workspace_path),enhance_prompt:De(j.enhance_prompt),auto_execute:D}}),s.success(e("settings.schedulesTab.updated")),p({open:!1,schedule:null,saving:!1}),await h()}catch(G){console.error("[Schedules] Failed to patch schedule:",G),s.error(e("settings.schedulesTab.updateFailed")),p(ne=>({...ne,saving:!1}))}},children:ee(C,I)})})]})}const{Text:Xt}=ue,Yt=sa.getInstance();function Mo(){const{t:e}=ae(),{modal:s,message:a}=ut.useApp(),n=Ke(v=>v.chats),r=Ke(v=>v.currentSessionId),o=Ke(v=>v.refreshChats),l=Ke(v=>v.loadChats),u=Ke(v=>v.loadChatHistory),[g,m]=i.useState(!0),[c,b]=i.useState(!1),p=i.useMemo(()=>r?n.find(v=>v.id===r)??null:null,[n,r]),S=async v=>{if(!c){b(!0);try{await v()}finally{b(!1)}}};return t.jsxs(X,{vertical:!0,gap:16,children:[t.jsx(N,{size:"small",title:e("settings.sessionsTab.currentSessionTitle"),children:p?t.jsxs(X,{vertical:!0,gap:4,children:[t.jsx(Xt,{strong:!0,ellipsis:!0,children:p.title}),t.jsxs(Xt,{type:"secondary",ellipsis:!0,children:[e("settings.sessionsTab.id"),": ",p.id," ","•"," ",e("settings.sessionsTab.kind"),": ",p.kind]}),t.jsx(X,{gap:8,wrap:"wrap",style:{marginTop:8},children:t.jsx(z,{danger:!0,loading:c,onClick:()=>{s.confirm({title:e("settings.sessionsTab.clearMessagesTitle"),content:e("settings.sessionsTab.clearMessagesContent"),okText:e("settings.sessionsTab.clear"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await S(async()=>{await Yt.clearSession(p.id),await u(p.id),await o(),a.success(e("settings.sessionsTab.sessionCleared"))})}})},children:e("settings.sessionsTab.clearMessages")})})]}):t.jsx(Xt,{type:"secondary",children:e("settings.sessionsTab.noActiveSession")})}),t.jsxs(N,{size:"small",title:e("settings.sessionsTab.bulkCleanupTitle"),children:[t.jsxs(X,{align:"center",gap:8,style:{marginBottom:12},children:[t.jsx(Xt,{children:e("settings.sessionsTab.keepPinned")}),t.jsx(fe,{checked:g,onChange:m})]}),t.jsxs(X,{gap:8,wrap:"wrap",children:[t.jsx(z,{danger:!0,loading:c,onClick:()=>{s.confirm({title:e("settings.sessionsTab.deleteAllTitle"),content:e(g?"settings.sessionsTab.deleteAllKeepPinned":"settings.sessionsTab.deleteAllIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await S(async()=>{await Yt.cleanupSessions("all",g),await l(),a.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteAll")}),t.jsx(z,{danger:!0,loading:c,onClick:()=>{s.confirm({title:e("settings.sessionsTab.deleteEmptyTitle"),content:e(g?"settings.sessionsTab.deleteEmptyKeepPinned":"settings.sessionsTab.deleteEmptyIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await S(async()=>{await Yt.cleanupSessions("empty",g),await l(),a.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteEmpty")}),t.jsx(z,{danger:!0,loading:c,onClick:()=>{s.confirm({title:e("settings.sessionsTab.deleteChildrenTitle"),content:e(g?"settings.sessionsTab.deleteChildrenKeepPinned":"settings.sessionsTab.deleteChildrenIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await S(async()=>{await Yt.cleanupSessions("children",g),await l(),a.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteChildren")})]})]}),t.jsxs(N,{size:"small",title:e("settings.sessionsTab.devResetTitle"),children:[t.jsx(Xt,{type:"secondary",children:e("settings.sessionsTab.devResetDescription")}),t.jsx(X,{style:{marginTop:12},children:t.jsx(z,{danger:!0,type:"primary",loading:c,onClick:()=>{s.confirm({title:e("settings.sessionsTab.devResetConfirmTitle"),content:e("settings.sessionsTab.devResetConfirmContent"),okText:e("settings.sessionsTab.reset"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await S(async()=>{await Yt.devResetSessions(),await l(),a.success(e("settings.sessionsTab.devResetDone"))})}})},children:e("settings.sessionsTab.devResetAction")})})]})]})}const dn="notifications/preferences";function un(e){return{enabled:e.enabled,onClarification:e.on_clarification,onToolApproval:e.on_tool_approval,onContextPressure:e.on_context_pressure,onSubAgentComplete:e.on_subagent_complete,onBackgroundTaskComplete:e.on_background_task_complete}}function Eo(e){return{enabled:e.enabled,on_clarification:e.onClarification,on_tool_approval:e.onToolApproval,on_context_pressure:e.onContextPressure,on_subagent_complete:e.onSubAgentComplete,on_background_task_complete:e.onBackgroundTaskComplete}}async function Po(){const e=await Ye.get(dn);return un(e)}async function Do(e){const s=await Ye.put(dn,Eo(e));return un(s)}const{Text:tt}=ue,{useToken:Io}=Te,Fo={enabled:!0,onClarification:!0,onToolApproval:!0,onContextPressure:!0,onSubAgentComplete:!0,onBackgroundTaskComplete:!0},Ao=()=>{const{t:e}=ae(),{token:s}=Io(),{message:a}=ut.useApp(),[n,r]=i.useState(Fo),[o,l]=i.useState(!0),u=wn();i.useEffect(()=>{let c=!1;return(async()=>{try{const b=await Po();c||r(b)}catch{c||a.error(e("settings.notificationsTab.loadError","Failed to load notification preferences"))}finally{c||l(!1)}})(),()=>{c=!0}},[a,e]);const g=(c,b)=>{const p=n,S={...n,[c]:b};r(S),Do(S).then(v=>{r(v)}).catch(()=>{r(p),a.error(e("settings.notificationsTab.saveError","Failed to save notification preferences"))})},m=!u||o;return t.jsx(N,{size:"small",className:"lotus-settings-card",children:t.jsxs(X,{vertical:!0,gap:s.marginMD,children:[!u&&t.jsx(qe,{type:"info",showIcon:!0,message:e("settings.notificationsTab.desktopOnly","Desktop notifications are only available in the Bodhi desktop app.")}),t.jsxs(X,{align:"center",gap:s.marginSM,children:[t.jsx(Wn,{}),t.jsx(tt,{strong:!0,children:e("settings.notificationsTab.title","Desktop Notifications")})]}),t.jsx(tt,{type:"secondary",style:{fontSize:s.fontSizeSM},children:e("settings.notificationsTab.description","Receive OS-level notifications when the app is in the background and user action is required.")}),t.jsx(Le,{style:{margin:`${s.marginXS}px 0`}}),t.jsxs(X,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(tt,{children:e("settings.notificationsTab.enabled","Enable desktop notifications")}),t.jsx(fe,{"data-testid":"notification-enabled-toggle",checked:n.enabled,onChange:c=>g("enabled",c),disabled:m})]}),t.jsx(Le,{style:{margin:`${s.marginXS}px 0`}}),t.jsx(tt,{strong:!0,style:{fontSize:s.fontSizeSM,opacity:n.enabled?1:.5},children:e("settings.notificationsTab.events","Notify when:")}),t.jsxs(X,{vertical:!0,gap:s.marginSM,style:{opacity:n.enabled?1:.5,pointerEvents:n.enabled?"auto":"none"},children:[t.jsxs(X,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(tt,{children:e("settings.notificationsTab.onClarification","Agent needs clarification")}),t.jsx(fe,{"data-testid":"notification-clarification-toggle",checked:n.onClarification,onChange:c=>g("onClarification",c),disabled:m})]}),t.jsxs(X,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(tt,{children:e("settings.notificationsTab.onToolApproval","Tool execution needs approval")}),t.jsx(fe,{"data-testid":"notification-tool-approval-toggle",checked:n.onToolApproval,onChange:c=>g("onToolApproval",c),disabled:m})]}),t.jsxs(X,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(tt,{children:e("settings.notificationsTab.onContextPressure","Context window is critically full")}),t.jsx(fe,{"data-testid":"notification-context-pressure-toggle",checked:n.onContextPressure,onChange:c=>g("onContextPressure",c),disabled:m})]}),t.jsxs(X,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(tt,{children:e("settings.notificationsTab.onSubAgentComplete","Background task completes")}),t.jsx(fe,{"data-testid":"notification-subagent-complete-toggle",checked:n.onSubAgentComplete,onChange:c=>g("onSubAgentComplete",c),disabled:m})]}),t.jsxs(X,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(tt,{children:e("settings.notificationsTab.onBackgroundTaskComplete","Background command finishes")}),t.jsx(fe,{"data-testid":"notification-background-task-complete-toggle",checked:n.onBackgroundTaskComplete,onChange:c=>g("onBackgroundTaskComplete",c),disabled:m})]})]}),t.jsx(Le,{style:{margin:`${s.marginXS}px 0`}}),t.jsxs(X,{align:"center",gap:s.marginSM,children:[t.jsx(Gn,{style:{color:s.colorPrimary}}),t.jsx(tt,{type:"secondary",style:{fontSize:s.fontSizeSM},children:e("settings.notificationsTab.osNote","OS notification permissions may also be required. You can manage them in your system settings.")})]})]})})},{Text:ys,Paragraph:Ro}=ue,gn=({open:e,onCancel:s,onComplete:a,onCopyCode:n,completingAuth:r,copiedUserCode:o,deviceCodeInfo:l,timeRemaining:u,token:g})=>{const{t:m}=ae();return t.jsx(Qe,{title:m("settings.providerTab.copilotAuthModalTitle"),open:e,onCancel:s,footer:[t.jsx(z,{onClick:s,children:m("settings.providerTab.cancel")},"cancel"),t.jsx(z,{type:"primary",onClick:a,loading:r,children:m("settings.providerTab.completedAuthorization")},"complete")],children:l&&t.jsxs(L,{direction:"vertical",size:"large",style:{width:"100%"},children:[t.jsx(qe,{message:m("settings.providerTab.browserOpened"),description:t.jsxs("ol",{children:[t.jsx("li",{children:m("settings.providerTab.authStep1")}),t.jsx("li",{children:m("settings.providerTab.authStep2")}),t.jsx("li",{children:m("settings.providerTab.authStep3")})]}),type:"info"}),t.jsx(N,{size:"small",className:"lotus-settings-card",children:t.jsxs(L,{direction:"vertical",style:{width:"100%"},children:[t.jsx(ys,{type:"secondary",children:m("settings.providerTab.visitUrl")}),t.jsx(L,{children:t.jsx(ys,{copyable:{text:l.verification_uri},children:l.verification_uri})})]})}),t.jsx(N,{style:{textAlign:"center",background:g.colorFillTertiary,borderColor:g.colorBorderSecondary},children:t.jsxs(L,{direction:"vertical",style:{width:"100%"},children:[t.jsx(ys,{type:"secondary",children:m("settings.providerTab.enterCode")}),t.jsxs(L,{children:[t.jsx(ys,{style:{color:g.colorText,fontSize:"32px",fontFamily:"monospace",fontWeight:"bold",letterSpacing:"4px"},children:l.user_code}),t.jsx(z,{icon:o?t.jsx(Zs,{}):t.jsx(Za,{}),onClick:n,type:o?"default":"primary",children:m(o?"settings.providerTab.copied":"settings.providerTab.copyCode")})]}),t.jsx("div",{style:{marginTop:8},children:t.jsxs(re,{color:u<60?"error":u<180?"warning":"success",children:[t.jsx(Jn,{style:{marginRight:4}}),"Expires in ",Math.floor(u/60),":",(u%60).toString().padStart(2,"0")]})})]})}),t.jsx(Ro,{type:"secondary",children:m("settings.providerTab.afterContinueHint")})]})})},zo=new Set(["id","type","provider_type","label","enabled","api_key_encrypted"]),$a=e=>e?Object.fromEntries(Object.entries(e).filter(([s])=>!zo.has(s))):{},{Password:Ba}=H,{Text:ht,Paragraph:Ks}=ue,Lo=["low","medium","high","xhigh","max"],Zt=(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:Lo.map(a=>t.jsx(te.Option,{value:a,children:e(`chat.input.reasoning.${a}`)},a))}),qa=e=>t.jsx(y.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})}),Oo=e=>Array.isArray(e)?e.map(s=>typeof s=="string"?s.trim():"").filter(s=>!!s):[],No=({type:e})=>{const{t:s}=ae();if(!e)return null;switch(e){case"openai":return t.jsxs(t.Fragment,{children:[t.jsx(y.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(xt,{})})}),t.jsx(y.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(y.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Zt(s)}),qa(s)]});case"anthropic":return t.jsxs(t.Fragment,{children:[t.jsx(y.Item,{name:"api_key",label:s("settings.providerTab.anthropicApiKey"),rules:[{required:!0,message:s("settings.providerTab.anthropicApiKeyRequired")}],children:t.jsx(Ba,{placeholder:s("settings.providerTab.anthropicApiKeyPlaceholder","sk-ant-..."),prefix:t.jsx(xt,{})})}),t.jsx(y.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(y.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(y.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Zt(s)})]});case"gemini":return t.jsxs(t.Fragment,{children:[t.jsx(y.Item,{name:"api_key",label:s("settings.providerTab.geminiApiKey"),rules:[{required:!0,message:s("settings.providerTab.geminiApiKeyRequired")}],children:t.jsx(Ba,{placeholder:s("settings.providerTab.geminiApiKeyPlaceholder","AIza..."),prefix:t.jsx(xt,{})})}),t.jsx(y.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(y.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Zt(s)})]});case"copilot":return t.jsxs(t.Fragment,{children:[t.jsx(y.Item,{name:"headless_auth",label:s("settings.providerTab.headlessAuth"),valuePropName:"checked",extra:s("settings.providerTab.headlessAuthHelp"),children:t.jsx(fe,{})}),t.jsx(y.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Zt(s)}),qa(s)]});case"bodhi":return t.jsxs(t.Fragment,{children:[t.jsx(y.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(xt,{})})}),t.jsx(y.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(y.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(y.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Zt(s)})]});default:return null}},Vo=({instances:e,defaultInstanceId:s,onInstancesChanged:a})=>{const{t:n}=ae(),{message:r}=ut.useApp(),{token:o}=Te.useToken(),[l]=y.useForm(),[u,g]=i.useState(!1),[m,c]=i.useState(null),[b,p]=i.useState(!1),[S,v]=i.useState(null),[x,R]=i.useState(void 0),[P,C]=i.useState(null),[I,h]=i.useState(!1),[k,V]=i.useState(!1),[F,U]=i.useState(0),[ee,$]=i.useState(!1),[j,T]=i.useState(!1),[D,A]=i.useState("unknown"),[Q,O]=i.useState(!1),Y=i.useCallback(B=>({type:B.type,label:B.label,enabled:B.enabled,...$a(B.config)}),[]),G=i.useCallback(()=>{c(null),R(void 0),g(!0)},[]),ne=async()=>{try{T(!0);const B=await de.startCopilotAuth();C(B),h(!0),U(B.expires_in)}catch(B){r.error(n("settings.providerTab.startCopilotAuthFailed","Failed to start Copilot authentication")),console.error("Failed to start Copilot authentication:",B)}finally{T(!1)}},ie=async()=>{if(P)try{V(!0),await de.completeCopilotAuth({device_code:P.device_code,interval:P.interval||5,expires_in:P.expires_in}),r.success(n("settings.providerTab.copilotAuthSuccess","Copilot authentication successful!")),h(!1),C(null),await d()}catch(B){r.error(n("settings.providerTab.completeAuthFailed","Authentication completion failed")),console.error("Authentication completion failed:",B)}finally{V(!1)}},be=async()=>{if(P)try{await aa(P.user_code),$(!0),r.success(n("settings.providerTab.userCodeCopied","User code copied!")),setTimeout(()=>$(!1),2e3)}catch{r.error(n("settings.providerTab.copyCodeFailed","Failed to copy code"))}},d=i.useCallback(async()=>{try{O(!0);const B=await de.getCopilotAuthStatus();A(B.authenticated?"authenticated":"not_authenticated")}catch(B){console.error("Failed to check Copilot auth status:",B),A("unknown")}finally{O(!1)}},[]);i.useEffect(()=>{u&&x==="copilot"&&d()},[d,u,x]);const E=i.useCallback(B=>{if(!B){l.resetFields();return}if(m){l.setFieldsValue(Y(m)),R(m.type);return}l.setFieldsValue({enabled:!0})},[Y,m,l]),M=(B="small")=>t.jsx(N,{size:"small",title:n("settings.providerTab.copilotAuth","GitHub Copilot Authentication"),style:{marginTop:8},children:t.jsxs(L,{direction:"vertical",style:{width:"100%"},children:[t.jsxs(L,{children:[t.jsx(ht,{strong:!0,children:n("settings.providerTab.authStatus","Status:")}),D==="authenticated"?t.jsx(re,{color:"success",children:n("settings.providerTab.authenticated","Authenticated")}):D==="not_authenticated"?t.jsx(re,{color:"warning",children:n("settings.providerTab.notAuthenticated","Not Authenticated")}):t.jsx(re,{children:n("settings.providerTab.unknown","Unknown")}),t.jsx(z,{type:"text",size:"small",onClick:()=>void d(),loading:Q,children:n("settings.providerTab.refreshStatus","Refresh")})]}),t.jsx(Ks,{type:"secondary",style:{marginBottom:8},children:n("settings.providerTab.copilotAuthHelp","Copilot requires OAuth authentication. Click the button below to start the Device Code Flow.")}),t.jsx(z,{type:"primary",icon:t.jsx(Qa,{}),onClick:()=>void ne(),loading:j,size:B,children:n("settings.providerTab.authenticateCopilot","Authenticate Copilot")})]})}),K=i.useCallback(B=>{c(B),R(B.type),g(!0)},[]),se=i.useCallback(async()=>{try{const B=await l.validateFields();p(!0);const{type:we,label:We,enabled:Ie,request_overrides_json:Oe,...Pe}=B,Ge=$a(Pe);if("responses_only_models"in Ge&&(Ge.responses_only_models=Oo(Ge.responses_only_models)),typeof Oe=="string"&&Oe.trim()&&(Ge.request_overrides=JSON.parse(Oe)),m){const f={label:We,enabled:Ie,config:Ge};await de.updateProviderInstance(m.id,f),r.success(n("settings.providerTab.instanceUpdated","Provider instance updated"))}else{const f={type:we,label:We||yt[we]||we,enabled:Ie??!0,config:Ge};await de.createProviderInstance(f),r.success(n("settings.providerTab.instanceCreated","Provider instance created"))}g(!1),await a(),await st.getState().loadProviderInstances()}catch(B){(vs(B)||B instanceof Error&&!tn(B))&&r.error(B.message)}finally{p(!1)}},[m,l,r,a,n]),pe=i.useCallback(async B=>{try{v(B),await de.deleteProviderInstance(B),r.success(n("settings.providerTab.instanceDeleted","Provider instance deleted")),await a(),await st.getState().loadProviderInstances()}catch(we){r.error(vs(we)?we.message:n("settings.providerTab.instanceDeleteFailed","Failed to delete instance"))}finally{v(null)}},[a,r,n]),ye=i.useCallback(async B=>{try{await de.setDefaultProviderInstance(B),r.success(n("settings.providerTab.defaultInstanceSet","Default provider updated")),await a(),await st.getState().loadProviderInstances()}catch(we){r.error(vs(we)?we.message:n("settings.providerTab.defaultInstanceFailed","Failed to set default"))}},[a,r,n]),je=i.useCallback(async()=>{await a()},[a]);return i.useEffect(()=>{je()},[]),t.jsxs("div",{style:{marginBottom:16},children:[t.jsxs("div",{style:{marginBottom:12,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[t.jsx(ht,{strong:!0,children:n("settings.providerTab.providerInstances","Provider Instances")}),t.jsx(z,{type:"dashed",icon:t.jsx(dt,{}),onClick:G,"data-testid":"add-provider-instance",children:n("settings.providerTab.addInstance","Add Provider")})]}),e.length===0&&t.jsx(Ks,{type:"secondary",children:n("settings.providerTab.noInstances",'No provider instances configured. Click "Add Provider" to create one.')}),t.jsx(ks,{ghost:!0,items:e.map(B=>{const we=B.id===s,We=yt[B.type]||B.type;return{key:B.id,label:t.jsxs(L,{size:"small",children:[t.jsx("span",{style:{fontWeight:500},children:B.label||We}),t.jsx(re,{color:"processing",style:{fontSize:11},children:We}),we&&t.jsxs(re,{color:"gold",style:{fontSize:11},children:[t.jsx(Yn,{})," ",n("settings.providerTab.default","Default")]}),!B.enabled&&t.jsx(re,{color:"default",style:{fontSize:11},children:n("settings.providerTab.disabled","Disabled")})]}),extra:t.jsxs(L,{size:4,onClick:Ie=>Ie.stopPropagation(),children:[!we&&t.jsx(ke,{title:n("settings.providerTab.setDefault","Set as default"),children:t.jsx(z,{type:"text",size:"small",icon:t.jsx(Xn,{}),onClick:()=>void ye(B.id)})}),t.jsx(z,{type:"text",size:"small",icon:t.jsx(is,{}),onClick:()=>K(B)}),t.jsx(Rt,{title:n("settings.providerTab.confirmDeleteInstance","Delete this provider instance?"),onConfirm:()=>void pe(B.id),okText:n("settings.providerTab.delete","Delete"),cancelText:n("settings.providerTab.cancel","Cancel"),children:t.jsx(z,{type:"text",size:"small",danger:!0,icon:t.jsx(Et,{}),loading:S===B.id})})]}),children:t.jsxs("div",{children:[t.jsxs(Ks,{type:"secondary",style:{marginBottom:8},children:["ID: ",t.jsx(ht,{code:!0,children:B.id})," · Type: ",t.jsx(ht,{code:!0,children:B.type})]}),B.config&&Object.keys(B.config).length>0&&t.jsx(N,{size:"small",style:{marginBottom:8},children:Object.entries(B.config).map(([Ie,Oe])=>Ie==="api_key"?t.jsxs("div",{style:{marginBottom:4},children:[t.jsxs(ht,{type:"secondary",children:[Ie,": "]}),t.jsx(ht,{children:"••••••••"})]},Ie):t.jsxs("div",{style:{marginBottom:4},children:[t.jsxs(ht,{type:"secondary",children:[Ie,": "]}),t.jsx(ht,{children:typeof Oe=="object"?JSON.stringify(Oe):String(Oe)})]},Ie))}),B.type==="copilot"&&M("small")]})}})}),t.jsx(Qe,{open:u,title:m?n("settings.providerTab.editInstance","Edit Provider Instance"):n("settings.providerTab.createInstance","Create Provider Instance"),onCancel:()=>g(!1),onOk:()=>void se(),afterOpenChange:E,confirmLoading:b,width:560,forceRender:!0,destroyOnClose:!0,children:t.jsxs(y,{form:l,layout:"vertical",preserve:!1,children:[t.jsx(y.Item,{name:"type",label:n("settings.providerTab.providerType","Provider Type"),rules:[{required:!0,message:n("settings.providerTab.typeRequired","Please select a provider type")}],children:t.jsx(te,{disabled:!!m,placeholder:n("settings.providerTab.selectType","Select provider type"),onChange:B=>R(B),children:Object.entries(yt).map(([B,we])=>t.jsx(te.Option,{value:B,children:we},B))})}),t.jsx(y.Item,{name:"label",label:n("settings.providerTab.instanceLabel","Label"),extra:n("settings.providerTab.labelHelp","A display name for this provider instance"),children:t.jsx(H,{placeholder:n("settings.providerTab.labelPlaceholder","My OpenAI Instance")})}),t.jsx(y.Item,{name:"enabled",label:n("settings.providerTab.enabled","Enabled"),valuePropName:"checked",initialValue:!0,children:t.jsx(fe,{})}),t.jsx(Le,{children:n("settings.providerTab.instanceConfig","Configuration")}),t.jsx(y.Item,{noStyle:!0,shouldUpdate:!0,children:()=>t.jsx(No,{form:l,type:x})}),x==="copilot"&&M("middle")]})}),t.jsx(gn,{open:I,onCancel:()=>h(!1),onComplete:()=>void ie(),onCopyCode:()=>void be(),completingAuth:k,copiedUserCode:ee,deviceCodeInfo:P,timeRemaining:F,token:o})]})},{Password:Ha}=H,{Text:Ze,Paragraph:Ws}=ue,xs=["openai","anthropic","gemini","copilot","bodhi"],Dt=()=>null,Gs=e=>{var a,n;if(!e||typeof e!="object")return!1;const s=e;return!!((a=s.provider)!=null&&a.trim()&&((n=s.model)!=null&&n.trim()))},$o=(e,s,a)=>{const n=e;n[s]={...n[s]??{},model:a}},Ua=e=>{var a,n;const s=(n=(a=e.memory)==null?void 0:a.background_model)==null?void 0:n.trim();return s||void 0},Ka=(e,s)=>{var a,n,r;return s||((a=e==null?void 0:e.chat)==null?void 0:a.provider)||((n=e==null?void 0:e.fast)==null?void 0:n.provider)||((r=e==null?void 0:e.memory_background)==null?void 0:r.provider)||void 0},Wa=e=>t.jsxs(L,{direction:"vertical",size:4,children:[t.jsxs(Ze,{type:"secondary",children:[e("settings.providerTab.responsesOnlyHelp1")," ",t.jsx(Ze,{code:!0,children:"/responses"}),"."]}),t.jsx(Ze,{type:"secondary",children:e("settings.providerTab.responsesOnlyHelp2")})]}),Bo=["low","medium","high","xhigh","max"],It=(e,s)=>t.jsx(te,{placeholder:e("settings.providerTab.reasoningEffortDefault"),allowClear:!0,value:s==null?void 0:s.value,onChange:s!=null&&s.onChange?a=>{var n;return(n=s.onChange)==null?void 0:n.call(s,a??void 0)}:void 0,disabled:s==null?void 0:s.disabled,size:s==null?void 0:s.size,style:s==null?void 0:s.style,"data-testid":s==null?void 0:s["data-testid"],children:Bo.map(a=>t.jsx(te.Option,{value:a,children:e(`chat.input.reasoning.${a}`)},a))}),qo=()=>{const{t:e}=ae(),{token:s}=Te.useToken(),{message:a}=ut.useApp(),[n]=y.useForm(),[r,o]=i.useState(!1),[l,u]=i.useState(!1),[g,m]=i.useState("copilot"),[c,b]=i.useState(!1),[p,S]=i.useState(null),[v,x]=i.useState(!1),[R,P]=i.useState(!1),[C,I]=i.useState(null),[h,k]=i.useState(!1),[V,F]=i.useState(!1),[U,ee]=i.useState(0),[$,j]=i.useState(!1),[T,D]=i.useState([]),[A,Q]=i.useState(!1),[O,Y]=i.useState([]),[G,ne]=i.useState(null),[ie,be]=i.useState(!1),[d,E]=i.useState([]),[M,K]=i.useState("idle"),[se,pe]=i.useState(null),ye=i.useCallback((_,w)=>{const Z=_.instances??[],q=Z.reduce((ge,le)=>{const $e={...le.config};return $e.request_overrides&&typeof $e.request_overrides=="object"&&($e.request_overrides_json=JSON.stringify($e.request_overrides,null,2)),ge[le.id]=$e,ge},{});let J=_.defaults?{..._.defaults}:void 0;const xe=_.default_provider_instance_id??null,he=xe?Z.find(ge=>ge.id===xe):void 0,Se=typeof(he==null?void 0:he.config.model)=="string"?he.config.model.trim():void 0;!Gs(J==null?void 0:J.chat)&&xe&&Se&&(J={...J||{},chat:{provider:xe,model:Se}});const Ae=w?Ua(w):void 0,Ce=Ka(J,xe);return Ae&&!(J!=null&&J.memory_background)&&Ce&&(J={...J||{},memory_background:{provider:Ce,model:Ae}}),{defaults:J,features:_.features,providers:q}},[]),je=i.useCallback((_,w)=>{Y(_.instances??[]),ne(_.default_provider_instance_id??null),be(!0),n.setFieldsValue(ye(_,w)),b(!0)},[ye,n]),B=i.useCallback(_=>{if(!(_!=null&&_.trim()))return;const w=O.find(Z=>Z.id===_);return w?w.label||yt[w.type]:yt[_]||_},[O]),we=i.useCallback((_,w)=>{const Z=new Set;_!=null&&_.trim()&&Z.add(_);for(const q of xs){const J=w==null?void 0:w[q];J&&Object.keys(J).length>0&&Z.add(q)}return Array.from(Z)},[]);i.useEffect(()=>{if(M!=="success")return;const _=setTimeout(()=>{K("idle"),pe(null)},2e3);return()=>clearTimeout(_)},[M]),i.useEffect(()=>{if(!h||!C){ee(0);return}ee(C.expires_in);const _=setInterval(()=>{ee(w=>w<=1?(clearInterval(_),0):w-1)},1e3);return()=>clearInterval(_)},[h,C]);const We=i.useCallback(async()=>{var _;try{o(!0);const[w,Z]=await Promise.all([de.getProviderConfig(),it.getInstance().getBambooConfig().catch(()=>({}))]);let q=w.defaults?{...w.defaults}:void 0;if(!((_=q==null?void 0:q.chat)!=null&&_.model)&&w.provider&&w.providers){const Ce=w.provider,ge=w.providers[Ce],le=ge==null?void 0:ge.model;le&&(q={...q||{},chat:{provider:Ce,model:le}})}const J=Ua(Z),xe=Ka(q,w.provider||null);J&&!(q!=null&&q.memory_background)&&xe&&(q={...q||{},memory_background:{provider:xe,model:J}});const he=Gs(q==null?void 0:q.chat)?q:void 0,Se={provider:w.provider,defaults:he,providers:w.providers||{},features:w.features};ct("[Provider]","Loaded provider config:",Se);const Ae={...Se.providers||{}};xs.forEach(Ce=>{const ge=Ae[Ce];ge&&ge.request_overrides&&typeof ge.request_overrides=="object"&&(ge.request_overrides_json=JSON.stringify(ge.request_overrides,null,2))}),m(Se.provider),be(!1),E(we(Se.provider,Ae)),n.setFieldsValue({...Se,providers:Ae,defaults:Se.defaults}),b(!0)}catch(w){a.error(e("settings.providerTab.loadConfigFailed")),console.error("Failed to load provider config:",w)}finally{o(!1)}},[n,we,a,e]),Ie=i.useCallback(async()=>{try{const _=await de.getEnvVars();D(_.entries||[])}catch(_){console.warn("Failed to load env vars for provider overrides:",_)}},[]),Oe=i.useCallback(async()=>{try{const[_,w]=await Promise.all([de.getProviderInstances(),it.getInstance().getBambooConfig().catch(()=>({}))]);if(!Array.isArray(_.instances))throw new Error("Provider instances API returned an invalid payload");je(_,w)}catch{}},[je]),Pe=i.useCallback(async()=>{try{x(!0);const _=await de.getCopilotAuthStatus();S(_)}catch(_){console.error("Failed to check Copilot auth status:",_),S({authenticated:!1,message:e("settings.providerTab.checkStatusFailed")})}finally{x(!1)}},[e]);i.useEffect(()=>{Ie(),st.getState().loadCatalog(),Pe(),(async()=>{try{const[_,w]=await Promise.all([de.getProviderInstances(),it.getInstance().getBambooConfig().catch(()=>({}))]);if(!Array.isArray(_.instances))throw new Error("Provider instances API returned an invalid payload");je(_,w)}catch{await We()}})()},[We,Ie,Pe,je]);const Ge=async()=>{try{P(!0);const _=await de.startCopilotAuth();I(_),k(!0)}catch(_){a.error(e("settings.providerTab.startCopilotAuthFailed")),console.error("Failed to start Copilot authentication:",_)}finally{P(!1)}},f=async()=>{if(C)try{F(!0),await de.completeCopilotAuth({device_code:C.device_code,interval:C.interval||5,expires_in:C.expires_in}),a.success(e("settings.providerTab.copilotAuthSuccess")),k(!1),I(null),await Pe()}catch(_){a.error(e("settings.providerTab.completeAuthFailed")),console.error("Authentication completion failed:",_)}finally{F(!1)}},ce=async()=>{if(C)try{await aa(C.user_code),j(!0),a.success(e("settings.providerTab.userCodeCopied")),setTimeout(()=>j(!1),2e3)}catch{a.error(`${e("settings.providerTab.copyCodeFailedPrefix")} ${C.user_code}`)}},ve=async()=>{try{P(!0),await de.logoutCopilot(),a.success(e("settings.providerTab.logoutSuccess")),await Pe()}catch(_){a.error(e("settings.providerTab.logoutFailed")),console.error("Failed to logout:",_)}finally{P(!1)}},Ne=i.useCallback(async()=>{Q(!0);try{const _=await de.fetchCatalogModels();await st.getState().loadCatalog();const w=_.fetched.filter(q=>q.models&&q.models.length>0).length;_.fetched.filter(q=>q.error).length>0?a.warning(e("settings.providerTab.fetchModelsPartialSuccess",{success:w,total:_.fetched.length})):a.success(e("settings.providerTab.fetchModelsSuccess",{count:w}))}catch{a.error(e("settings.providerTab.fetchModelsFailed"))}finally{Q(!1)}},[a,e]),_e=_=>vs(_)||_ instanceof Error?_.message:e("settings.providerTab.unknownError"),Ve=_=>{n.setFields([{name:["provider"],errors:[]},{name:["providers",_,"api_key"],errors:[]},{name:["defaults","chat"],errors:[]}])},gs=_=>{const w=_.trim();return w?w.includes(".")?w.split(".").filter(Boolean):w==="provider"?["provider"]:w==="provider/providers"?["provider"]:null:null},Ms=(_,w)=>{if(!_.length)return;const Z=_.map(q=>{const J=gs(q.path);return J?{name:J,errors:[q.message]}:q.message.toLowerCase().includes("api key")?{name:["providers",w,"api_key"],errors:[q.message]}:{name:["provider"],errors:[q.message]}}).filter((q,J,xe)=>xe.findIndex(he=>JSON.stringify(he.name)===JSON.stringify(q.name))===J);Z.length&&n.setFields(Z)},Es=async _=>{var Z;const w=_.provider||g;Ve(w);try{const J=await it.getInstance().validateBambooConfigPatch({provider:_.provider,providers:_.providers||{},defaults:_.defaults,features:{..._.features||{},provider_model_ref:!0}});if(J.valid)return{valid:!0};const xe=((Z=J.errors)==null?void 0:Z.provider)||[];Ms(xe,w);const he=xe[0];return{valid:!1,message:(he==null?void 0:he.message)||e("settings.providerTab.invalidConfig")}}catch(q){return console.warn("Config validation failed, falling back to save:",q),{valid:!0}}},Vt=async(_,w)=>{var Z,q;try{o(!0);const J={provider:_.provider,defaults:_.defaults,providers:{..._.providers||{}},features:{..._.features||{},provider_model_ref:!0}},xe=(Z=J.defaults)==null?void 0:Z.chat;if(!Gs(xe)){const ge=e("settings.providerTab.selectModelRequired");if(n.setFields([{name:["defaults","chat"],errors:[ge]}]),(w==null?void 0:w.showMessage)!==!1&&a.error(ge),w!=null&&w.throwOnError)throw new Error(ge);return}const he=J.providers;for(const ge of xs){const le=he[ge];if(!le)continue;const $e=le.request_overrides_json;if(typeof $e!="string")continue;const vt=$e.trim();if(!vt)delete le.request_overrides;else try{le.request_overrides=JSON.parse(vt)}catch(Bt){const qt=e("settings.providerTab.invalidRequestOverridesJson",{provider:ge,error:Bt.message});if(n.setFields([{name:["providers",ge,"request_overrides_json"],errors:[qt]}]),(w==null?void 0:w.showMessage)!==!1&&a.error(qt),w!=null&&w.throwOnError)throw Bt;return}delete le.request_overrides_json}const Se={...J.providers||{}},Ae=J.provider,Ce=(q=J.defaults)==null?void 0:q.chat;if(Ce!=null&&Ce.model&&Ae&&$o(Se,Ae,Ce.model),ie){const ge=it.getInstance(),le={defaults:J.defaults,features:{...J.features||{},provider_model_ref:!0}};ct("[Provider]","Saving instance-mode config:",le),await ge.setBambooConfig(le)}else{const le={provider:J.provider||g,defaults:J.defaults,providers:Se,features:J.features},$e=await Es(J);if(!$e.valid){const vt=$e.message||e("settings.providerTab.invalidConfig");if((w==null?void 0:w.showMessage)!==!1&&a.error(`${e("settings.providerTab.invalidConfigPrefix")}: ${vt}`),w!=null&&w.throwOnError)throw new Error(vt);return}ct("[Provider]","Saving provider config:",le),await de.saveProviderConfig(le)}(w==null?void 0:w.showMessage)!==!1&&a.success(e("settings.providerTab.saveConfigSuccess"))}catch(J){const xe=_e(J);if((w==null?void 0:w.showMessage)!==!1&&a.error(xe?`${e("settings.providerTab.saveConfigErrorPrefix")}: ${xe}`:e("settings.providerTab.saveConfigFailed")),console.error("Failed to save configuration:",J),w!=null&&w.throwOnError)throw J}finally{o(!1)}},mt=async _=>{var w,Z,q,J,xe;try{u(!0);const{useProviderStore:he}=await Qs(async()=>{const{useProviderStore:Ht}=await import("./App-CH_iNVyb.js").then(zs=>zs.ak);return{useProviderStore:Ht}},__vite__mapDeps([4,1,2,3,5,6,7,8]),import.meta.url),{useAppStore:Se}=await Qs(async()=>{const{useAppStore:Ht}=await import("./App-CH_iNVyb.js").then(zs=>zs.al);return{useAppStore:Ht}},__vite__mapDeps([4,1,2,3,5,6,7,8]),import.meta.url),Ae=(w=he.getState().providerConfig.defaults)==null?void 0:w.chat;ie?await he.getState().loadProviderInstances():await he.getState().loadProviderConfig();const Ce=(Z=he.getState().providerConfig.defaults)==null?void 0:Z.chat;he.getState().setSelectedModelRef(null);const ge=Se.getState().currentSessionId,le=ge&&Se.getState().chats.find(Ht=>Ht.id===ge)||null,$e=Ae?`${Ae.provider}/${Ae.model}`:null,vt=Ce?`${Ce.provider}/${Ce.model}`:null,Bt=(q=le==null?void 0:le.config)!=null&&q.model_ref?`${le.config.model_ref.provider}/${le.config.model_ref.model}`:null,qt=((xe=(J=le==null?void 0:le.config)==null?void 0:J.model)==null?void 0:xe.trim())||null;!!(ge&&(le!=null&&le.config)&&Ce&&vt!==$e&&(!Bt||Bt===$e)&&(!qt||qt===(Ae==null?void 0:Ae.model)))&&ge&&(le!=null&&le.config)&&Ce&&Se.getState().updateSession(ge,{config:{...le.config,model:Ce.model,model_ref:Ce}}),(_==null?void 0:_.showMessage)!==!1&&a.success(e("settings.providerTab.applyConfigSuccess"))}catch(he){const Se=_e(he);if((_==null?void 0:_.showMessage)!==!1&&a.error(Se?`${e("settings.providerTab.applyConfigErrorPrefix")}: ${Se}`:e("settings.providerTab.applyConfigFailed")),console.error("Failed to apply configuration:",he),_!=null&&_.throwOnError)throw he}finally{u(!1)}},Ps=async _=>{try{const w=n.getFieldsValue(!0);await Vt(w,{throwOnError:!0}),await mt({throwOnError:!0})}catch{}},Ds=async(_,w)=>{if(!(_==="chat"&&!w)&&M!=="saving"){K("saving"),pe(null);try{const Z=n.getFieldsValue(!0),q=Z.defaults;if(!(q!=null&&q.chat))throw new Error(e("settings.providerTab.selectModelRequired"));Z.defaults={...q,[_]:w},await Vt(Z,{showMessage:!1,throwOnError:!0}),await mt({showMessage:!1,throwOnError:!0}),K("success"),a.success(e("settings.providerTab.modelUpdated"))}catch(Z){const q=_e(Z);K("error"),pe(q),a.error(q?`${e("settings.providerTab.updateModelErrorPrefix")}: ${q}`:e("settings.providerTab.updateModelFailed"))}}},Is=async(_,w)=>{if(M!=="saving"){K("saving"),pe(null);try{if(ie){const Z=O.find(q=>q.id===_);if(!Z)throw new Error(e("settings.providerTab.providerNotConfigured"));await de.updateProviderInstance(Z.id,{config:{reasoning_effort:w??null}}),await Oe(),await st.getState().loadProviderInstances()}else{const Z=n.getFieldsValue(!0);await Vt(Z,{showMessage:!1,throwOnError:!0}),await mt({showMessage:!1,throwOnError:!0})}K("success"),a.success(e("settings.providerTab.reasoningEffortUpdated"))}catch(Z){const q=_e(Z);K("error"),pe(q),a.error(q?`${e("settings.providerTab.updateReasoningEffortErrorPrefix")}: ${q}`:e("settings.providerTab.updateReasoningEffortFailed"))}}},ms=(_,w)=>{if(!_)return null;const Z=B(_)||_,q=n.getFieldValue(["providers",_,"reasoning_effort"]),J=(w==null?void 0:w.emphasis)==="subtle",xe=(w==null?void 0:w.label)||e("settings.providerTab.reasoningEffortOptional"),he=(w==null?void 0:w.helperText)||e("settings.providerTab.reasoningEffortHelp");return t.jsx("div",{style:{marginTop:(w==null?void 0:w.marginTop)??8,width:"100%"},children:t.jsxs(L,{direction:"vertical",size:J?6:4,style:{width:"100%"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,flexWrap:"wrap"},children:[t.jsx(Ze,{strong:!J,type:J?"secondary":void 0,style:J?{fontSize:s.fontSizeSM,lineHeight:1.4}:void 0,children:xe}),w!=null&&w.showProviderLabel?t.jsx(Ze,{type:"secondary",style:{fontSize:s.fontSizeSM,lineHeight:1.4},children:Z}):null]}),It(e,{value:q,disabled:M==="saving",size:(w==null?void 0:w.size)??(J?"small":void 0),style:{width:"100%"},"data-testid":w==null?void 0:w.dataTestId,onChange:Se=>{n.setFieldValue(["providers",_,"reasoning_effort"],Se),w!=null&&w.autoSave&&Is(_,Se)}}),t.jsx(Ze,{type:"secondary",style:J?{fontSize:s.fontSizeSM,lineHeight:1.5}:void 0,children:he})]})})},Fs=i.useCallback(_=>{const w=n.getFieldValue(["providers",_]);return w?_==="copilot"?(p==null?void 0:p.authenticated)??!1:!!w.api_key:!1},[n,p]),As=()=>{const _=Z=>{const q=n.getFieldValue(["defaults",Z]);return t.jsx(Cn,{value:q,dataTestId:`model-preference-${Z}-picker`,appearance:"contrast",disabled:M==="saving",onChange:J=>{n.setFieldValue(["defaults",Z],J),Ds(Z,J)}})},w=(Z,q,J)=>t.jsxs("div",{style:{width:"100%",display:"flex",alignItems:"flex-start",gap:s.marginLG,flexWrap:"wrap"},children:[t.jsx("div",{style:{flex:"1 1 420px",minWidth:0},children:t.jsxs(L,{direction:"vertical",size:8,style:{width:"100%"},children:[t.jsx(Ze,{strong:!0,children:q}),_(Z),J?t.jsx(Ze,{type:"secondary",children:J}):null]})}),t.jsx("div",{style:{flex:"0 1 320px",minWidth:280},children:t.jsx(y.Item,{noStyle:!0,shouldUpdate:!0,children:()=>{const xe=n.getFieldValue(["defaults",Z]),he=xe==null?void 0:xe.provider;return ms(he,{autoSave:!0,dataTestId:`model-preference-${Z}-reasoning-effort`,label:e("settings.providerTab.reasoningEffortOptional"),helperText:e("settings.providerTab.reasoningEffortHelp"),marginTop:0,size:"small",emphasis:"subtle",showProviderLabel:!!he})}})})]});return t.jsxs(N,{size:"small",title:e("settings.providerTab.modelPreferences"),style:{marginBottom:16},children:[t.jsx(y.Item,{name:["defaults","chat"],noStyle:!0,preserve:!0,children:t.jsx(Dt,{})}),t.jsx(y.Item,{name:["defaults","fast"],noStyle:!0,preserve:!0,children:t.jsx(Dt,{})}),t.jsx(y.Item,{name:["defaults","task_summary"],noStyle:!0,preserve:!0,children:t.jsx(Dt,{})}),t.jsx(y.Item,{name:["defaults","memory_background"],noStyle:!0,preserve:!0,children:t.jsx(Dt,{})}),t.jsx(y.Item,{name:["defaults","sub_agent"],noStyle:!0,preserve:!0,children:t.jsx(Dt,{})}),t.jsx(y.Item,{name:["defaults","vision"],noStyle:!0,preserve:!0,children:t.jsx(Dt,{})}),t.jsxs(L,{direction:"vertical",size:16,style:{width:"100%"},children:[w("chat",e("settings.providerTab.defaultModel")),w("fast",e("settings.providerTab.fastModel"),e("settings.providerTab.fastModelHelp")),w("task_summary",e("settings.providerTab.taskSummaryModel"),e("settings.providerTab.taskSummaryModelHelp")),w("memory_background",e("settings.providerTab.memoryBackgroundModel"),e("settings.providerTab.memoryBackgroundModelHelp")),w("sub_agent",e("settings.providerTab.subAgentModel"),e("settings.providerTab.subAgentModelHelp")),w("vision",e("settings.providerTab.visionModel"),e("settings.providerTab.visionModelHelp"))]})]})},bt=_=>{const w=T.map(q=>q.name);return t.jsx(y.Item,{name:["providers",_,"request_overrides_json"],label:e("settings.providerTab.advancedRequestOverrides"),extra:t.jsxs(L,{direction:"vertical",size:4,children:[t.jsx(Ze,{type:"secondary",children:e("settings.providerTab.advancedRequestOverridesHelp")}),t.jsxs(Ze,{type:"secondary",children:[e("settings.providerTab.envVarInjection")," ",t.jsx(Ze,{code:!0,children:'{ "type": "env_ref", "name": "YOUR_ENV_NAME" }'})]}),w.length>0&&t.jsx(L,{wrap:!0,size:[6,6],children:w.map(q=>t.jsx(re,{children:q},q))})]}),children:t.jsx(H.TextArea,{autoSize:{minRows:8,maxRows:20},placeholder:`{
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-BCJ3Fg76.js","./vendor-markdown-CARODNj-.js","./vendor-i18n-Dm-c3D_C.js","./vendor-antd-C-pjKgeW.js","./App-DlBGZjWK.js","./vendor-mermaid-1Fp-_2HG.js","./main-CMR1cQYD.js","./main-B6snAd4S.css","./App-xovo7L2Z.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
var mn=Object.defineProperty;var pn=(e,s,a)=>s in e?mn(e,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[s]=a;var la=(e,s,a)=>pn(e,typeof s!="symbol"?s+"":s,a);import{j as t}from"./vendor-markdown-CARODNj-.js";import{a as i,u as ae,R as ca,i as oe}from"./vendor-i18n-Dm-c3D_C.js";import{J as hn,u as Ke,b as fn,T as yn,g as xn,U as sa,d as st,B as ct,V as bn,W as ft,X as Re,Y as vn,Z as jn,_ as Tn,$ as _n,a0 as Xa,a1 as it,a2 as de,H as da,a as Ye,a3 as Ya,G as aa,m as Sn,l as Ys,q as kn,a4 as wn,a5 as yt,k as vs,a6 as Cn,a7 as Mn,a8 as ua,a9 as En,aa as ga,ab as ma,ac as pa,ad as ha,o as Pn,ae as Dn,A as In,af as Fn,ag as An,ah as Rn,ai as zn,aj as Ln}from"./App-DlBGZjWK.js";import{U as N,o as L,I as qe,j as ue,a9 as H,B as z,t as Te,a4 as y,a3 as as,aI as Ts,aJ as te,aK as fe,aL as Me,J as Xe,aM as Je,aN as me,D as ke,aO as Ue,aP as On,aG as Le,Q as X,aQ as ks,aR as Nn,a6 as Rt,a7 as Et,ao as Vn,aS as $n,A as ut,aT as ws,p as is,a5 as dt,x as re,aU as fa,aV as at,a8 as Qe,Z as Bn,aw as zt,a2 as Lt,n as Ft,aW as qn,an as Hn,aX as ya,aY as ze,a0 as He,av as Za,aZ as Un,a_ as gt,a$ as Ee,y as Kn,b0 as xa,b1 as Wn,X as Gn,z as Zs,W as Jn,b2 as Xn,b3 as Yn,b4 as Qa,b5 as xt,b6 as ba,b7 as Zn,ah as Qn,aC as er,b8 as tr}from"./vendor-antd-C-pjKgeW.js";import{_ as Qs}from"./vendor-mermaid-1Fp-_2HG.js";import{r as sr}from"./onboardingStorage-BVcEpmTy.js";import"./main-CMR1cQYD.js";import{m as ts}from"./MetricsService-BGNLv7xq.js";import{R as Ot,B as na,C as os,X as ls,Y as cs,T as Nt,L as ra,a as _s,b as en,c as At,P as ar,d as nr,e as rr}from"./vendor-charts-BoAlA5Ii.js";function ir(e){return e instanceof hn}function or(){const{chats:e,currentSessionId:s,currentChat:a,addMessage:n,selectSession:r,deleteSession:o,deleteSessions:l,deleteMessage:u,updateSession:g,persistSessionTitle:m,pinSession:c,unpinSession:b,loadChats:p}=Ke(fn(C=>({chats:C.chats,currentSessionId:C.currentSessionId,currentChat:yn(C),addMessage:C.addMessage,selectSession:C.selectSession,deleteSession:C.deleteSession,deleteSessions:C.deleteSessions,deleteMessage:C.deleteMessage,updateSession:C.updateSession,persistSessionTitle:C.persistSessionTitle,pinSession:C.pinSession,unpinSession:C.unpinSession,loadChats:C.loadChats}))),S=Ke(xn(s)),v=i.useMemo(()=>(a==null?void 0:a.messages)||[],[a]),x=i.useMemo(()=>e.filter(C=>C.pinned),[e]),R=i.useMemo(()=>e.filter(C=>!C.pinned),[e]),P=e.length;return{chats:e,currentSessionId:s,currentChat:a,isProcessing:S,baseMessages:v,pinnedChats:x,unpinnedChats:R,chatCount:P,addMessage:n,deleteMessage:u,selectSession:r,deleteSession:o,deleteSessions:l,pinSession:c,unpinSession:b,updateSession:g,persistSessionTitle:m,loadChats:p}}function lr(e){const s=Ke(p=>p.addChat),a=Ke(p=>p.lastSelectedPromptId),n=Ke(p=>p.systemPrompts),r=sa.getInstance(),o=i.useCallback(async(p,S)=>{var P,C;const v=n.find(I=>I.id===a),x=(v==null?void 0:v.id)||(n.length>0?((P=n.find(I=>I.id==="general_assistant"))==null?void 0:P.id)||n[0].id:""),R={title:p||"New Session",createdAt:Date.now(),messages:[],config:{systemPromptId:x,baseSystemPrompt:(v==null?void 0:v.content)||(n.length>0?((C=n.find(I=>I.id==="general_assistant"))==null?void 0:C.content)||n[0].content:""),lastUsedEnhancedPrompt:null,...st.getState().isProviderModelRefEnabled()?{model_ref:st.getState().selectedModelRef}:{}},...S};await s(R)},[s,a,n]),l=i.useCallback(async p=>{ct("[ChatOps]","[useChatOperations] createChatWithSystemPrompt started with prompt:",p);const S={title:`New Session - ${p.name}`,createdAt:Date.now(),messages:[],config:{systemPromptId:p.id,baseSystemPrompt:p.content,lastUsedEnhancedPrompt:null}};ct("[ChatOps]","[useChatOperations] Calling addChat with newChatData.config:",S.config),await s(S)},[s]),u=i.useCallback(p=>{const S=e.chats.find(v=>v.id===p);S&&(S.pinned?e.unpinSession(p):e.pinSession(p))},[e]),g=i.useCallback((p,S)=>{e.updateSession(p,{title:S})},[e]),m=i.useCallback(async()=>{await r.cleanupSessions("empty",!0),await Ke.getState().loadChats()},[r]),c=i.useCallback(async()=>{await r.cleanupSessions("all",!0),await Ke.getState().loadChats()},[r]),b=i.useCallback(async()=>{await r.cleanupSessions("all",!1),await Ke.getState().loadChats()},[r]);return{createNewChat:o,createChatWithSystemPrompt:l,toggleChatPin:u,updateChatTitle:g,deleteEmptyChats:m,deleteAllUnpinnedChats:c,deleteAllChats:b}}function cr(e,s){const a=i.useMemo(()=>e.baseMessages,[e.baseMessages]),n=i.useCallback(async()=>{var m;if(!e.currentSessionId||!e.currentChat)return;const r=[...e.baseMessages];if(r.length===0)return;const o=r[r.length-1];let l=r;if((o==null?void 0:o.role)==="assistant"){if(!(await e.deleteMessage(e.currentSessionId,o.id)).success)return;l=r.slice(0,-1)}const u=[...l].reverse().find(c=>c.role==="user");if(!u)return;const g="content"in u?u.content:u.displayText;typeof g=="string"&&await((m=s==null?void 0:s.onRetry)==null?void 0:m.call(s,g))},[e,s]);return{currentMessages:a,retryLastMessage:n}}const dr=()=>{const e=or(),s=lr(e),a=bn({sessionId:e.currentSessionId,addMessage:e.addMessage,updateSession:e.updateSession}),n=cr(e,{onRetry:a.sendMessage});return{chats:e.chats,currentSessionId:e.currentSessionId,currentChat:e.currentChat,pinnedChats:e.pinnedChats,unpinnedChats:e.unpinnedChats,chatCount:e.chatCount,currentMessages:n.currentMessages,agentAvailable:a.agentAvailable,addMessage:e.addMessage,deleteMessage:e.deleteMessage,selectSession:e.selectSession,deleteSession:e.deleteSession,deleteSessions:e.deleteSessions,pinSession:e.pinSession,unpinSession:e.unpinSession,updateSession:e.updateSession,loadChats:e.loadChats,createNewChat:s.createNewChat,createChatWithSystemPrompt:s.createChatWithSystemPrompt,toggleChatPin:s.toggleChatPin,updateChatTitle:s.updateChatTitle,deleteEmptyChats:s.deleteEmptyChats,deleteAllUnpinnedChats:s.deleteAllUnpinnedChats,deleteAllChats:s.deleteAllChats,retryLastMessage:n.retryLastMessage,sendMessage:a.sendMessage,cancelMessage:a.cancel}},{Text:ps}=ue,{useToken:ur}=Te,gr=({httpProxy:e,httpsProxy:s,onHttpProxyChange:a,onHttpsProxyChange:n,onReload:r,onSave:o,isLoading:l})=>{const{t:u}=ae(),{token:g}=ur(),m=ft(h=>h.proxyAuthStatus),c=ft(h=>h.isLoadingProxyAuthStatus),b=ft(h=>h.loadProxyAuthStatus),p=ft(h=>h.applyProxyAuth),S=ft(h=>h.clearProxyAuth),[v,x]=i.useState({username:"",password:""}),[R,P]=i.useState(!1);i.useEffect(()=>{b()},[b]);const C=async()=>{const h=v.username.trim();if(h){P(!0);try{await p({username:h,password:v.password}),x({username:"",password:""})}catch(k){console.error("Failed to apply proxy auth:",k)}finally{P(!1)}}},I=async()=>{P(!0);try{await S()}catch(h){console.error("Failed to clear proxy auth:",h)}finally{P(!1)}};return t.jsx(N,{size:"small",title:t.jsx(ps,{strong:!0,children:u("settings.networkCard.title")}),className:"lotus-settings-card",children:t.jsxs(L,{direction:"vertical",size:g.marginSM,style:{width:"100%"},children:[t.jsx(qe,{message:u("settings.networkCard.guideTip"),type:"info",showIcon:!0}),t.jsxs(L,{direction:"vertical",size:g.marginXXS,style:{width:"100%"},children:[t.jsx(ps,{type:"secondary",children:u("settings.networkCard.httpProxy")}),t.jsx(H,{"data-testid":"proxy-url",style:{width:"100%"},value:e,onChange:h=>a(h.target.value),placeholder:u("settings.networkCard.proxyPlaceholder"),disabled:l})]}),t.jsxs(L,{direction:"vertical",size:g.marginXXS,style:{width:"100%"},children:[t.jsx(ps,{type:"secondary",children:u("settings.networkCard.httpsProxy")}),t.jsx(H,{style:{width:"100%"},value:s,onChange:h=>n(h.target.value),placeholder:u("settings.networkCard.proxyPlaceholder"),disabled:l})]}),t.jsx(N,{size:"small",title:u("settings.networkCard.proxyAuthTitle"),className:"lotus-settings-card",style:{marginTop:g.marginSM},children:m!=null&&m.configured?t.jsxs(L,{direction:"vertical",style:{width:"100%"},children:[t.jsx(qe,{type:"success",message:u("settings.networkCard.proxyConfiguredForUser",{username:m.username??""}),showIcon:!0}),t.jsx(z,{onClick:I,loading:R||c,danger:!0,children:u("settings.networkCard.clearCredentials")})]}):t.jsxs(L,{direction:"vertical",size:g.marginXS,style:{width:"100%"},children:[t.jsx(H,{placeholder:u("settings.networkCard.username"),value:v.username,onChange:h=>x(k=>({...k,username:h.target.value}))}),t.jsx(H.Password,{placeholder:u("settings.networkCard.password"),value:v.password,onChange:h=>x(k=>({...k,password:h.target.value}))}),t.jsx(z,{type:"primary",onClick:C,loading:R||c,disabled:!v.username.trim(),children:u("settings.networkCard.apply")})]})}),t.jsx(ps,{type:"secondary",style:{fontSize:g.fontSizeSM},children:u("settings.networkCard.credentialsStorageNote")}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:g.marginSM},children:[t.jsx(z,{onClick:()=>Promise.resolve(r()).finally(()=>b({force:!0})),disabled:l,children:u("settings.networkCard.reload")}),t.jsx(z,{"data-testid":"save-proxy-settings",type:"primary",onClick:()=>Promise.resolve(o()).finally(()=>b({force:!0})),disabled:l,children:u("settings.networkCard.save")})]})]})})};function tn(e){return typeof e=="object"&&e!==null&&"errorFields"in e}const{Text:mr}=ue,{useToken:pr}=Te,hr=({msgApi:e})=>{const{t:s}=ae(),{token:a}=pr(),[n]=y.useForm(),[r,o]=i.useState(!1),[l,u]=i.useState(!1),[g,m]=i.useState(!1),[c,b]=i.useState(!1),[p,S]=i.useState(null),v=g&&!c,x=i.useMemo(()=>s(g?c?"settings.configTab.accessPassword.helperLocalBypass":"settings.configTab.accessPassword.helperRemote":"settings.configTab.accessPassword.helperNotEnabled"),[c,g,s]),R=i.useCallback(async()=>{o(!0),S(null);try{const C=await Re.getAccessStatus();m(C.password_enabled),b(C.local_bypass)}catch(C){const I=C instanceof Error?C.message:s("settings.configTab.accessPassword.loadStatusFailed","Failed to load access status");S(I)}finally{o(!1)}},[s]);i.useEffect(()=>{R()},[R]);const P=async()=>{var C;try{const I=await n.validateFields();u(!0),await Re.updateAccessPassword({current_password:((C=I.currentPassword)==null?void 0:C.trim())||void 0,new_password:I.newPassword.trim()}),e.success(s(g?"settings.configTab.accessPassword.updated":"settings.configTab.accessPassword.enabled")),n.resetFields(),await R()}catch(I){if(tn(I))return;const h=I instanceof Error?I.message:s("settings.configTab.accessPassword.updateFailed","Failed to update access password");e.error(h)}finally{u(!1)}};return t.jsx(N,{size:"small",className:"lotus-settings-card",title:t.jsx(mr,{strong:!0,children:s("settings.configTab.accessPasswordTitle")}),children:t.jsxs(L,{direction:"vertical",size:a.marginMD,style:{width:"100%"},children:[t.jsx(qe,{type:g?"info":"warning",showIcon:!0,message:s(g?"settings.configTab.accessPassword.statusEnabled":"settings.configTab.accessPassword.statusDisabled"),description:x}),p?t.jsx(qe,{type:"error",showIcon:!0,message:p}):null,t.jsxs(y,{form:n,layout:"vertical",disabled:r||l,children:[v?t.jsx(y.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(y.Item,{label:s(g?"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(y.Item,{label:s("settings.configTab.accessPassword.confirmPasswordLabel"),name:"confirmPassword",dependencies:["newPassword"],rules:[{required:!0,message:s("settings.configTab.accessPassword.validation.confirmPasswordRequired")},({getFieldValue:C})=>({validator(I,h){return!h||C("newPassword")===h?Promise.resolve():Promise.reject(new Error(s("settings.configTab.accessPassword.validation.passwordMismatch")))}})],children:t.jsx(H.Password,{autoComplete:"new-password"})}),t.jsx(z,{type:"primary",loading:l,onClick:()=>void P(),children:s(g?"settings.configTab.accessPassword.updateAction":"settings.configTab.accessPassword.enableAction")})]})]})})},{Text:Be}=ue,{useToken:fr}=Te,va="http://127.0.0.1:9562/v1",Qt=e=>[...new Set(e.map(s=>s.trim()).filter(s=>s.length>0))].sort(),yr=e=>{var a;const s=(a=e.tools)==null?void 0:a.disabled;return Array.isArray(s)?Qt(s.filter(n=>typeof n=="string")):[]},xr=({msgApi:e,locale:s,onLocaleChange:a})=>{const{t:n}=ae(),{token:r}=fr(),[o,l]=i.useState({http_proxy:"",https_proxy:"",memory:{auto_dream_enabled:!1},subagents:{}}),[u,g]=i.useState(va),[m,c]=i.useState([]),[b,p]=i.useState([]),[S,v]=i.useState([]),[x,R]=i.useState(!1),[P,C]=i.useState(!1),I=i.useCallback(async()=>{var O,Y;R(!0);try{const[G,ne]=await Promise.all([Re.getBambooConfig(),Re.getBambooTools()]);l({http_proxy:G.http_proxy||"",https_proxy:G.https_proxy||"",memory:{auto_dream_enabled:((O=G.memory)==null?void 0:O.auto_dream_enabled)??!1},subagents:{max_concurrent:(Y=G.subagents)==null?void 0:Y.max_concurrent}});const ie=yr(G);p(ie),v(ie),c(Qt(ne.tools||[]))}catch(G){console.error("Failed to load config:",G),e.error(n("settings.configTab.loadConfigFailed"))}finally{R(!1)}},[e,n]);i.useEffect(()=>{I()},[I]);const h=O=>{l(Y=>({...Y,http_proxy:O}))},k=O=>{l(Y=>({...Y,https_proxy:O}))},V=O=>{l(Y=>({...Y,memory:{...Y.memory,auto_dream_enabled:O}}))},F=O=>{l(Y=>({...Y,subagents:{...Y.subagents,max_concurrent:O!==null&&Number.isFinite(O)&&O>0?O:void 0}}))},U=async O=>{var Y,G;R(!0);try{let ne;O==="network"?ne={http_proxy:o.http_proxy,https_proxy:o.https_proxy}:O==="memory"?ne={memory:{auto_dream_enabled:o.memory.auto_dream_enabled}}:ne={subagents:{max_concurrent:o.subagents.max_concurrent}};const ie=await Re.validateBambooConfigPatch(ne);if(!ie.valid){const d=((G=(Y=ie.errors)==null?void 0:Y.proxy)==null?void 0:G[0])??Object.values(ie.errors||{}).flat().filter(Boolean)[0];e.error((d==null?void 0:d.message)||n("settings.configTab.invalidConfig"));return}await Re.setBambooConfig(ne),e.success(n("settings.configTab.saveConfigSuccess"))}catch(ne){console.error("Failed to save config:",ne);const ie=ne instanceof Error&&ne.message.trim()?ne.message:n("settings.configTab.saveConfigFailed");e.error(ie)}finally{R(!1)}},ee=async()=>{e.success(n("settings.configTab.backendSaved"))},$=()=>{g(va),e.success(n("settings.configTab.backendResetDefault"))},j=(O,Y)=>{p(G=>{const ne=new Set(G);return Y?ne.delete(O):ne.add(O),Qt([...ne])})},T=async()=>{C(!0);try{const O=await Re.getBambooTools();c(Qt(O.tools||[])),e.success(n("settings.configTab.toolsReloadSuccess"))}catch(O){console.error("Failed to reload tools:",O),e.error(n("settings.configTab.toolsLoadFailed"))}finally{C(!1)}},D=async()=>{C(!0);try{const O=Qt(b);await Re.setBambooConfig({tools:{disabled:O}}),p(O),v(O),e.success(n("settings.configTab.toolsSaveSuccess"))}catch(O){console.error("Failed to save tool settings:",O),e.error(n("settings.configTab.toolsSaveFailed"))}finally{C(!1)}},A=JSON.stringify(b)!==JSON.stringify(S),Q=new Set(b);return t.jsx(as,{spinning:x,tip:n("settings.common.loading"),children:t.jsx(Ts,{items:[{key:"general",label:n("settings.configTab.tabs.general"),children:t.jsxs(L,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[t.jsx(gr,{httpProxy:o.http_proxy,httpsProxy:o.https_proxy,onHttpProxyChange:h,onHttpsProxyChange:k,onReload:I,onSave:()=>U("network"),isLoading:x}),t.jsx(N,{size:"small",className:"lotus-settings-card",title:t.jsx(Be,{strong:!0,children:n("settings.configTab.language")}),children:t.jsx(te,{value:s,style:{width:260},options:[{label:n("settings.configTab.languageEnglish"),value:"en-US"},{label:n("settings.configTab.languageChinese"),value:"zh-CN"},{label:n("settings.configTab.languageTraditionalChinese"),value:"zh-TW"},{label:n("settings.configTab.languageFrench"),value:"fr-FR"},{label:n("settings.configTab.languageJapanese"),value:"ja-JP"},{label:n("settings.configTab.languageHindi"),value:"hi-IN"}],onChange:O=>a(O)})}),t.jsx(N,{size:"small",className:"lotus-settings-card",title:t.jsx(Be,{strong:!0,children:n("settings.configTab.memoryTitle")}),children:t.jsxs(L,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[t.jsx(Be,{type:"secondary",children:n("settings.configTab.memoryDescription")}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:r.marginMD,flexWrap:"wrap"},children:[t.jsxs("div",{children:[t.jsx(Be,{strong:!0,children:n("settings.configTab.autoDreamEnabled")}),t.jsx("div",{children:t.jsx(Be,{type:"secondary",style:{fontSize:r.fontSizeSM},children:n("settings.configTab.autoDreamEnabledHint")})})]}),t.jsx(fe,{"data-testid":"auto-dream-toggle",checked:o.memory.auto_dream_enabled,onChange:V})]}),t.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:t.jsx(z,{"data-testid":"save-memory-settings",type:"primary",onClick:()=>U("memory"),loading:x,children:n("settings.configTab.save")})})]})}),t.jsx(N,{size:"small",className:"lotus-settings-card",title:t.jsx(Be,{strong:!0,children:n("settings.configTab.subagentsTitle")}),children:t.jsxs(L,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[t.jsx(Be,{type:"secondary",children:n("settings.configTab.subagentsDescription")}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:r.marginMD,flexWrap:"wrap"},children:[t.jsxs("div",{children:[t.jsx(Be,{strong:!0,children:n("settings.configTab.subagentMaxConcurrent")}),t.jsx("div",{children:t.jsx(Be,{type:"secondary",style:{fontSize:r.fontSizeSM},children:n("settings.configTab.subagentMaxConcurrentHint")})})]}),t.jsx(Me,{"data-testid":"subagent-max-concurrent",style:{width:120},min:1,step:1,precision:0,placeholder:"8",value:o.subagents.max_concurrent??null,onChange:O=>F(typeof O=="number"?O:null)})]}),t.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:t.jsx(z,{"data-testid":"save-subagent-settings",type:"primary",onClick:()=>U("subagents"),loading:x,children:n("settings.configTab.save")})})]})}),t.jsx(N,{size:"small",title:t.jsx(Be,{strong:!0,children:n("settings.configTab.backendApiBaseUrlTitle")}),children:t.jsxs(L,{direction:"vertical",size:r.marginSM,style:{width:"100%"},children:[t.jsx(L,{direction:"vertical",size:r.marginXXS,style:{width:"100%"},children:t.jsx(H,{style:{width:"100%"},value:u,onChange:O=>g(O.target.value),placeholder:n("settings.configTab.backendApiPlaceholder")})}),t.jsx(Be,{type:"secondary",style:{fontSize:r.fontSizeSM},children:n("settings.configTab.backendApiHint")}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:r.marginSM},children:[t.jsx(z,{"data-testid":"reset-to-defaults",onClick:$,children:n("settings.configTab.resetToDefault")}),t.jsx(z,{"data-testid":"save-api-settings",type:"primary",onClick:ee,children:n("settings.configTab.save")})]})]})}),t.jsx(hr,{msgApi:e})]})},{key:"tools",label:n("settings.configTab.tabs.tools"),children:t.jsx(N,{size:"small",title:t.jsx(Be,{strong:!0,children:n("settings.configTab.toolsTitle")}),children:t.jsxs(L,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[t.jsx(Be,{type:"secondary",children:n("settings.configTab.toolsDescription")}),m.length===0?t.jsx(qe,{type:"info",showIcon:!0,message:n("settings.configTab.toolsEmpty")}):t.jsx(Xe,{bordered:!0,dataSource:m,renderItem:O=>t.jsx(Xe.Item,{actions:[t.jsx(fe,{checked:!Q.has(O),onChange:Y=>j(O,Y)},`${O}-switch`)],children:t.jsx(Be,{code:!0,children:O})})}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:r.marginSM},children:[t.jsx(z,{onClick:T,loading:P,children:n("settings.configTab.reloadTools")}),t.jsx(z,{type:"primary",onClick:D,loading:P,disabled:!A,children:n("settings.configTab.save")})]})]})})}]})})},{Title:br,Text:Ls}=ue,{useToken:vr}=Te,jr=()=>{const{t:e}=ae(),{token:s}=vr(),a=vn(),n=jn(),r=Tn(),[o]=y.useForm(),l=ca.useRef(a);ca.useEffect(()=>{l.current!==a&&(o.setFieldsValue(a),l.current=a)},[a,o]);const u=m=>{l.current={...l.current,...m},n(m)},g=()=>{r(),o.resetFields()};return t.jsxs("div",{style:{padding:"24px",maxWidth:"1200px",margin:"0 auto"},children:[t.jsx(br,{level:3,style:{marginBottom:"8px"},children:e("settings.mermaidTab.title")}),t.jsx(Ls,{type:"secondary",style:{display:"block",marginBottom:"24px"},children:e("settings.mermaidTab.description")}),t.jsxs(y,{form:o,layout:"vertical",initialValues:a,onValuesChange:u,children:[t.jsxs(N,{title:e("settings.mermaidTab.themeCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:[t.jsx(Je,{gutter:16,children:t.jsx(me,{span:24,children:t.jsx(y.Item,{name:"theme",label:t.jsxs(L,{children:[e("settings.mermaidTab.themeLabel"),t.jsx(ke,{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(Ls,{type:"secondary",style:{display:"block",marginTop:"8px"},children:[t.jsx("strong",{children:e("settings.mermaidTab.themeDescriptionsTitle")}),t.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.default"),t.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.neutral"),t.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.dark"),t.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.forest"),t.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.base")]})]}),t.jsxs(N,{title:e("settings.mermaidTab.globalCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:[t.jsxs(Je,{gutter:16,children:[t.jsx(me,{span:12,children:t.jsx(y.Item,{name:"fontSize",label:t.jsxs(L,{children:[e("settings.mermaidTab.fontSizeLabel"),t.jsx(ke,{title:e("settings.mermaidTab.fontSizeTooltip"),children:t.jsx(Ue,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:10,max:32,step:1,style:{width:"100%"},addonAfter:"px"})})}),t.jsx(me,{span:12,children:t.jsx(y.Item,{name:"defaultScale",label:t.jsxs(L,{children:[e("settings.mermaidTab.defaultZoomLabel"),t.jsx(ke,{title:e("settings.mermaidTab.defaultZoomTooltip"),children:t.jsx(Ue,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:.1,max:3,step:.1,style:{width:"100%"}})})})]}),t.jsx(y.Item,{name:"useMaxWidth",label:t.jsxs(L,{children:[e("settings.mermaidTab.responsiveWidthLabel"),t.jsx(ke,{title:e("settings.mermaidTab.responsiveWidthTooltip"),children:t.jsx(Ue,{style:{color:s.colorTextSecondary}})})]}),valuePropName:"checked",children:t.jsx(fe,{})})]}),t.jsx(N,{title:e("settings.mermaidTab.flowchartCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsxs(Je,{gutter:16,children:[t.jsx(me,{span:8,children:t.jsx(y.Item,{name:"flowchartNodeSpacing",label:t.jsxs(L,{children:[e("settings.mermaidTab.flowchartNodeSpacingLabel"),t.jsx(ke,{title:e("settings.mermaidTab.flowchartNodeSpacingTooltip"),children:t.jsx(Ue,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:20,max:200,step:10,style:{width:"100%"}})})}),t.jsx(me,{span:8,children:t.jsx(y.Item,{name:"flowchartRankSpacing",label:t.jsxs(L,{children:[e("settings.mermaidTab.flowchartRankSpacingLabel"),t.jsx(ke,{title:e("settings.mermaidTab.flowchartRankSpacingTooltip"),children:t.jsx(Ue,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:20,max:200,step:10,style:{width:"100%"}})})}),t.jsx(me,{span:8,children:t.jsx(y.Item,{name:"flowchartCurve",label:t.jsxs(L,{children:[e("settings.mermaidTab.flowchartCurveTypeLabel"),t.jsx(ke,{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(N,{title:e("settings.mermaidTab.sequenceCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsxs(Je,{gutter:16,children:[t.jsx(me,{span:6,children:t.jsx(y.Item,{name:"sequenceActorMargin",label:t.jsxs(L,{children:[e("settings.mermaidTab.sequenceActorMarginLabel"),t.jsx(ke,{title:e("settings.mermaidTab.sequenceActorMarginTooltip"),children:t.jsx(Ue,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:20,max:200,step:10,style:{width:"100%"}})})}),t.jsx(me,{span:6,children:t.jsx(y.Item,{name:"sequenceMessageMargin",label:t.jsxs(L,{children:[e("settings.mermaidTab.sequenceMessageMarginLabel"),t.jsx(ke,{title:e("settings.mermaidTab.sequenceMessageMarginTooltip"),children:t.jsx(Ue,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:10,max:100,step:5,style:{width:"100%"}})})}),t.jsx(me,{span:6,children:t.jsx(y.Item,{name:"sequenceWidth",label:t.jsxs(L,{children:[e("settings.mermaidTab.sequenceActorWidthLabel"),t.jsx(ke,{title:e("settings.mermaidTab.sequenceActorWidthTooltip"),children:t.jsx(Ue,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:100,max:300,step:10,style:{width:"100%"}})})}),t.jsx(me,{span:6,children:t.jsx(y.Item,{name:"sequenceHeight",label:t.jsxs(L,{children:[e("settings.mermaidTab.sequenceActorHeightLabel"),t.jsx(ke,{title:e("settings.mermaidTab.sequenceActorHeightTooltip"),children:t.jsx(Ue,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:40,max:150,step:5,style:{width:"100%"}})})})]})}),t.jsx(N,{title:e("settings.mermaidTab.ganttCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsxs(Je,{gutter:16,children:[t.jsx(me,{span:12,children:t.jsx(y.Item,{name:"ganttBarHeight",label:t.jsxs(L,{children:[e("settings.mermaidTab.ganttBarHeightLabel"),t.jsx(ke,{title:e("settings.mermaidTab.ganttBarHeightTooltip"),children:t.jsx(Ue,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:10,max:50,step:5,style:{width:"100%"},addonAfter:"px"})})}),t.jsx(me,{span:12,children:t.jsx(y.Item,{name:"ganttTopPadding",label:t.jsxs(L,{children:[e("settings.mermaidTab.ganttTopPaddingLabel"),t.jsx(ke,{title:e("settings.mermaidTab.ganttTopPaddingTooltip"),children:t.jsx(Ue,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:20,max:100,step:10,style:{width:"100%"}})})})]})}),t.jsx(L,{children:t.jsx(z,{icon:t.jsx(On,{}),onClick:g,children:e("settings.mermaidTab.resetToDefaults")})}),t.jsx(Le,{}),t.jsx(N,{title:e("settings.mermaidTab.previewTitle"),styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsx(Ls,{type:"secondary",children:e("settings.mermaidTab.previewDescription")})})]})]})},Tr=i.lazy(()=>Qs(()=>import("./index-BCJ3Fg76.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8]),import.meta.url)),{Text:jt}=ue,{useToken:_r}=Te,Sr=({promptEnhancement:e,onPromptEnhancementChange:s,mermaidEnhancementEnabled:a,taskEnhancementEnabled:n,showCopilotConclusionWithOptionsEnhancement:r,copilotConclusionWithOptionsEnhancementEnabled:o,onMermaidToggle:l,onTaskToggle:u,onCopilotConclusionWithOptionsToggle:g,onSaveEnhancement:m})=>{const{t:c}=ae(),{token:b}=_r(),p=b.marginLG;return t.jsxs(X,{vertical:!0,gap:p,children:[t.jsx(N,{size:"small",className:"lotus-settings-card",children:t.jsx(i.Suspense,{fallback:t.jsx(as,{size:"small"}),children:t.jsx(Tr,{})})}),t.jsx(N,{size:"small",className:"lotus-settings-card",children:t.jsxs(L,{direction:"vertical",size:b.marginXS,style:{width:"100%"},children:[t.jsx(jt,{strong:!0,children:c("settings.promptsTab.title")}),t.jsxs(X,{align:"center",gap:b.marginSM,children:[t.jsx(jt,{strong:!0,children:c("settings.promptsTab.mermaidEnhancement")}),t.jsx(fe,{checked:a,onChange:l})]}),t.jsxs(X,{align:"center",gap:b.marginSM,children:[t.jsx(jt,{strong:!0,children:c("settings.promptsTab.taskListRules")}),t.jsx(fe,{checked:n,onChange:u})]}),r&&t.jsxs(L,{direction:"vertical",size:b.marginXXS,style:{width:"100%"},children:[t.jsxs(X,{align:"center",gap:b.marginSM,children:[t.jsx(jt,{strong:!0,children:c("settings.promptsTab.copilotConclusionWithOptionsBeforeFinish")}),t.jsx(fe,{checked:o,onChange:g})]}),t.jsx(jt,{type:"secondary",style:{fontSize:b.fontSizeSM},children:c("settings.promptsTab.copilotConclusionWithOptionsBeforeFinishDescription",{defaultValue:_n()})})]}),t.jsx(H.TextArea,{rows:6,placeholder:c("settings.promptsTab.enhancementPlaceholder"),value:e,onChange:S=>s(S.target.value)}),t.jsx(X,{justify:"flex-end",children:t.jsx(z,{type:"primary",onClick:m,children:c("settings.promptsTab.saveEnhancement")})}),t.jsx(jt,{type:"secondary",style:{fontSize:b.fontSizeSM},children:c("settings.promptsTab.description")})]})}),a&&t.jsx(ks,{size:"small",items:[{key:"mermaid",label:t.jsx(jt,{strong:!0,children:c("settings.mermaidTab.title")}),children:t.jsx(jr,{})}]})]})},{Text:pt}=ue,{useToken:kr}=Te,wr=({themeMode:e,onThemeModeChange:s,vdiSafeMode:a,onVdiSafeModeToggle:n,onClearLocalStorage:r,onResetApp:o,isResetting:l,darkModeKey:u})=>{const{t:g}=ae(),{token:m}=kr();return t.jsx(N,{size:"small",className:"lotus-settings-card",children:t.jsxs(L,{direction:"vertical",size:m.marginSM,style:{width:"100%"},children:[t.jsxs(X,{align:"center",justify:"space-between",gap:m.marginSM,children:[t.jsx(pt,{strong:!0,children:g("settings.appTab.runningVersion","Running version")}),t.jsxs(pt,{code:!0,"data-testid":"settings-app-version",children:["v",Xa]})]}),t.jsx(pt,{type:"secondary",style:{fontSize:m.fontSizeSM},children:g("settings.appTab.runningVersionDesc","This is the currently running Lotus frontend version.")}),t.jsxs(X,{align:"center",gap:m.marginSM,children:[t.jsx(pt,{strong:!0,children:g("settings.appTab.darkMode")}),t.jsx(fe,{"data-testid":"dark-mode-toggle",checked:e==="dark",onChange:c=>{const b=c?"dark":"light";s(b),localStorage.setItem(u,b)}})]}),t.jsxs(X,{align:"center",gap:m.marginSM,children:[t.jsx(pt,{strong:!0,children:g("settings.appTab.vdiSafeMode","Graphics compatibility mode")}),t.jsx(fe,{"data-testid":"vdi-safe-mode-toggle",checked:a,onChange:n})]}),t.jsx(pt,{type:"secondary",style:{fontSize:m.fontSizeSM},children:g("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(Nn,{}),onClick:()=>{sr(),window.location.reload()},children:g("settings.appTab.resetStepReplayGuide")}),t.jsx(Rt,{title:g("settings.appTab.clearLocalStorageTitle"),description:g("settings.appTab.clearLocalStorageDescription"),onConfirm:r,okText:g("settings.appTab.confirmClear"),cancelText:g("settings.appTab.cancel"),placement:"top",children:t.jsx(z,{danger:!0,block:!0,icon:t.jsx(Et,{}),children:g("settings.appTab.clearLocalStorageButton")})}),t.jsx(Le,{style:{margin:`${m.marginSM}px 0`}}),t.jsxs(X,{align:"center",gap:m.marginSM,children:[t.jsx(Vn,{style:{color:m.colorError}}),t.jsx(pt,{strong:!0,style:{color:m.colorError},children:g("settings.appTab.dangerZone")})]}),t.jsx(pt,{type:"secondary",style:{fontSize:m.fontSizeSM},children:g("settings.appTab.dangerDescription")}),t.jsx(Rt,{title:g("settings.appTab.resetApplicationTitle"),description:t.jsxs("div",{children:[t.jsx("p",{children:g("settings.appTab.resetApplicationIntro")}),t.jsxs("ul",{style:{margin:0,paddingLeft:16},children:[t.jsx("li",{children:g("settings.appTab.resetStepDeleteAllSessions")}),t.jsx("li",{children:g("settings.appTab.resetStepClearStorage")}),t.jsx("li",{children:g("settings.appTab.resetStepResetConfig")}),t.jsx("li",{children:g("settings.appTab.resetStepSetupFlow")}),t.jsx("li",{children:g("settings.appTab.resetStepReload")})]})]}),onConfirm:o,okText:g("settings.appTab.resetConfirm"),cancelText:g("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($n,{}),loading:l,children:g("settings.appTab.resetButton")})})]})})},{Text:Tt}=ue,{useToken:Cr}=Te,ja=[{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,}"}],Mr=(e,s,a)=>{if(!s)return{masked:e};if(a==="exact")return{masked:e.split(s).join("[MASKED]")};try{const n=new RegExp(s,"g");return{masked:e.replace(n,"[MASKED]")}}catch(n){return{masked:e,error:n instanceof Error?n.message:oe.t("settings.keywordMaskingTab.invalidRegexPattern")}}},Er=()=>{const{t:e}=ae(),{message:s}=ut.useApp(),{token:a}=Cr(),[n,r]=i.useState([]),[o,l]=i.useState(!1),[u,g]=i.useState(null),[m,c]=i.useState(""),[b,p]=i.useState("exact"),[S,v]=i.useState(!0),[x,R]=i.useState(),[P,C]=i.useState("My token is sk-123"),I=i.useCallback(async()=>{try{l(!0);const D=await it.getInstance().getKeywordMaskingConfig();r(D.entries)}catch(T){s.error(e("settings.keywordMaskingTab.loadFailed")),console.error(T)}finally{l(!1)}},[s,e]);i.useEffect(()=>{I()},[I]);const h=async T=>{try{const D=it.getInstance(),A=await D.validateKeywordEntries(T);if(!A.valid&&A.errors){const O=A.errors.map(Y=>`Entry ${Y.index+1}: ${Y.message}`).join("; ");return s.error(`${e("settings.keywordMaskingTab.validationFailedPrefix")}: ${O}`),!1}const Q=await D.updateKeywordMaskingConfig(T);return r(Q.entries),s.success(e("settings.keywordMaskingTab.saveSuccess")),!0}catch(D){return s.error(D instanceof Error?D.message:e("settings.keywordMaskingTab.saveFailed")),!1}},k=async()=>{const T={pattern:"",match_type:"exact",enabled:!0},D=[...n,T];r(D),g(D.length-1),c(""),p("exact"),v(!0),R(void 0)},V=T=>{const D=n[T];g(T),c(D.pattern),p(D.match_type),v(D.enabled),R(void 0)},F=async()=>{if(u===null)return;if(!m.trim()){s.error(e("settings.keywordMaskingTab.patternRequired"));return}const T=[...n];T[u]={pattern:m.trim(),match_type:b,enabled:S},await h(T)&&g(null)},U=()=>{var T;u!==null&&!((T=n[u])!=null&&T.pattern)&&r(n.filter((D,A)=>A!==u)),g(null)},ee=async T=>{const D=n.filter((A,Q)=>Q!==T);await h(D)},$=async(T,D)=>{const A=[...n];A[T]={...A[T],enabled:D},await h(A)},j=Mr(P,m,b);return t.jsx(N,{className:"lotus-settings-card",title:e("settings.keywordMaskingTab.title"),extra:t.jsx(z,{"data-testid":"add-keyword",type:"primary",icon:t.jsx(dt,{}),onClick:k,loading:o,children:e("settings.keywordMaskingTab.addKeyword")}),children:t.jsxs(L,{direction:"vertical",style:{width:"100%"},size:"large",children:[t.jsx(Tt,{type:"secondary",children:e("settings.keywordMaskingTab.description")}),t.jsx(Xe,{loading:o,dataSource:n,locale:{emptyText:e("settings.keywordMaskingTab.empty")},renderItem:(T,D)=>t.jsx(Xe.Item,{style:{backgroundColor:a.colorFillAlter,marginBottom:8,borderRadius:a.borderRadius,padding:12},actions:u===D?[t.jsx(z,{"data-testid":"save-keyword",type:"primary",icon:t.jsx(ws,{}),onClick:F,"aria-label":e("settings.keywordMaskingTab.save")},"save"),t.jsx(z,{onClick:U,children:e("settings.keywordMaskingTab.cancel")},"cancel")]:[t.jsx(z,{icon:t.jsx(is,{}),onClick:()=>V(D),"aria-label":e("settings.keywordMaskingTab.edit")},"edit"),t.jsx(z,{"data-testid":`delete-keyword-${D}`,danger:!0,icon:t.jsx(Et,{}),onClick:()=>ee(D),"aria-label":e("settings.keywordMaskingTab.delete")},"delete")],children:t.jsx(X,{vertical:!0,style:{width:"100%"},gap:8,children:u===D?t.jsxs(t.Fragment,{children:[t.jsx(H,{"data-testid":"keyword-pattern-input",placeholder:e("settings.keywordMaskingTab.patternPlaceholder"),value:m,onChange:A=>c(A.target.value),autoFocus:!0}),t.jsxs(X,{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:x,onChange:A=>{R(A);const Q=ja.find(O=>O.value===A);Q&&(c(Q.pattern),p(Q.match_type))},options:ja.map(A=>({value:A.value,label:e(A.labelKey)})),style:{minWidth:220}}),t.jsx(te,{value:b,onChange:p,options:[{value:"exact",label:e("settings.keywordMaskingTab.exactMatch")},{value:"regex",label:e("settings.keywordMaskingTab.regexPattern")}],style:{width:150}}),t.jsx(fe,{checked:S,onChange:v})]}),t.jsxs(X,{vertical:!0,gap:6,children:[t.jsx(Tt,{type:"secondary",children:e("settings.keywordMaskingTab.sampleText")}),t.jsx(H,{placeholder:e("settings.keywordMaskingTab.sampleTextPlaceholder"),value:P,onChange:A=>C(A.target.value)}),t.jsx(Tt,{type:"secondary",children:e("settings.keywordMaskingTab.maskedPreview")}),t.jsx(H,{readOnly:!0,value:j.masked,status:j.error?"error":void 0}),j.error&&t.jsx(Tt,{type:"danger",children:j.error})]})]}):t.jsxs(X,{justify:"space-between",align:"center",children:[t.jsxs(X,{vertical:!0,gap:4,children:[t.jsx(Tt,{strong:!0,children:T.pattern||e("settings.keywordMaskingTab.emptyPattern")}),t.jsxs(X,{gap:8,children:[t.jsx(Tt,{type:"secondary",style:{fontSize:12},children:T.match_type==="regex"?e("settings.keywordMaskingTab.regexPattern"):e("settings.keywordMaskingTab.exactMatch")}),!T.enabled&&t.jsx(Tt,{type:"warning",style:{fontSize:12},children:e("settings.keywordMaskingTab.disabled")})]})]}),t.jsx(fe,{checked:T.enabled,onChange:A=>$(D,A),size:"small"})]})})})})]})})},{Text:Ta,Paragraph:Pr}=ue,Dr=["Bash(rm -rf *)","Bash(git push *)","Bash(sudo *)","Write(/etc/**)"],Ir=()=>{const{t:e}=ae(),{message:s}=ut.useApp(),[a,n]=i.useState([]),[r,o]=i.useState(""),[l,u]=i.useState(!1),[g,m]=i.useState(!1),c=i.useCallback(async()=>{try{u(!0),n(await de.getPermissionAskRules())}catch(v){s.error(e("settings.permissionsTab.loadFailed")),console.error(v)}finally{u(!1)}},[s,e]);i.useEffect(()=>{c()},[c]);const b=i.useCallback(async v=>{try{m(!0);const x=await de.updatePermissionAskRules(v);return n(x),s.success(e("settings.permissionsTab.saveSuccess")),!0}catch(x){return s.error(x instanceof Error?x.message:e("settings.permissionsTab.saveFailed")),!1}finally{m(!1)}},[s,e]),p=i.useCallback(async v=>{const x=v.trim();if(!x)return;if(a.includes(x)){s.info(e("settings.permissionsTab.duplicate"));return}await b([...a,x])&&o("")},[a,b,s,e]),S=i.useCallback(v=>b(a.filter(x=>x!==v)),[a,b]);return t.jsx(N,{className:"lotus-settings-card",title:e("settings.permissionsTab.title"),extra:t.jsx(z,{type:"primary",icon:t.jsx(dt,{}),loading:g,disabled:!r.trim(),onClick:()=>void p(r),children:e("settings.permissionsTab.add")}),children:t.jsxs(L,{direction:"vertical",style:{width:"100%"},size:"large",children:[t.jsx(Pr,{type:"secondary",style:{marginBottom:0},children:e("settings.permissionsTab.description")}),t.jsx(H,{value:r,onChange:v=>o(v.target.value),onPressEnter:()=>void p(r),placeholder:e("settings.permissionsTab.placeholder"),allowClear:!0}),t.jsxs(X,{gap:8,wrap:"wrap",align:"center",children:[t.jsx(Ta,{type:"secondary",style:{fontSize:12},children:e("settings.permissionsTab.examples")}),Dr.map(v=>t.jsx(re.CheckableTag,{checked:a.includes(v),onChange:()=>{a.includes(v)||p(v)},children:v},v))]}),t.jsx(Xe,{loading:l,dataSource:a,locale:{emptyText:e("settings.permissionsTab.empty")},renderItem:v=>t.jsx(Xe.Item,{actions:[t.jsx(z,{danger:!0,size:"small",icon:t.jsx(Et,{}),loading:g,onClick:()=>void S(v),"aria-label":e("settings.permissionsTab.remove")},"delete")],children:t.jsx(Ta,{code:!0,children:v})})})]})})},{Text:Pt,Paragraph:Fr}=ue,Ar=/^[A-Za-z_][A-Za-z0-9_]*$/,Rr=()=>{const{t:e}=ae(),{message:s}=ut.useApp(),[a,n]=i.useState([]),[r,o]=i.useState(!1),[l,u]=i.useState(!1),[g,m]=i.useState(null),[c]=y.useForm(),b=i.useCallback(async()=>{o(!0);try{const C=await de.getEnvVars();n(C.entries)}catch{s.error(e("settings.envVars.fetchError","Failed to load environment variables"))}finally{o(!1)}},[s,e]);i.useEffect(()=>{b()},[b]);const p=async C=>{var h;const I={name:C.name.trim(),value:C.value,secret:C.secret??!1,description:((h=C.description)==null?void 0:h.trim())||void 0};try{const k=await de.upsertEnvVar(I);n(k.entries),s.success(g?e("settings.envVars.updated","Variable updated"):e("settings.envVars.created","Variable created")),R()}catch(k){s.error((k instanceof Error?k.message:void 0)||e("settings.envVars.saveError","Failed to save variable"))}},S=async C=>{try{const I=await de.deleteEnvVar(C);n(I.entries),s.success(e("settings.envVars.deleted","Variable deleted"))}catch(I){s.error((I instanceof Error?I.message:void 0)||e("settings.envVars.deleteError","Failed to delete variable"))}},v=()=>{m(null),c.resetFields(),c.setFieldsValue({secret:!1}),u(!0)},x=C=>{m(C.name),c.setFieldsValue({name:C.name,value:"",secret:C.secret,description:C.description??""}),u(!0)},R=()=>{u(!1),m(null),c.resetFields()},P=[{title:e("settings.envVars.name","Name"),dataIndex:"name",key:"name",render:C=>t.jsx(Pt,{code:!0,children:C})},{title:e("settings.envVars.value","Value"),dataIndex:"value",key:"value",render:(C,I)=>I.secret?t.jsxs(Pt,{type:"secondary",children:[t.jsx(fa,{style:{marginRight:4}}),I.has_value?"••••••••":e("settings.envVars.notSet","(not set)")]}):t.jsx(Pt,{children:C||t.jsx(Pt,{type:"secondary",children:e("settings.envVars.empty","(empty)")})})},{title:e("settings.envVars.type","Type"),key:"secret",width:100,render:(C,I)=>I.secret?t.jsx(re,{color:"warning",icon:t.jsx(fa,{}),children:e("settings.envVars.secret","Secret")}):t.jsx(re,{color:"processing",children:e("settings.envVars.plain","Plain")})},{title:e("settings.envVars.descriptionCol","Description"),dataIndex:"description",key:"description",ellipsis:!0,render:C=>C?t.jsx(Pt,{type:"secondary",children:C}):t.jsx(Pt,{type:"secondary",italic:!0,children:"—"})},{title:e("settings.envVars.actions","Actions"),key:"actions",width:120,render:(C,I)=>t.jsxs(L,{size:"small",children:[t.jsx(z,{type:"text",size:"small",icon:t.jsx(is,{}),onClick:()=>x(I),"aria-label":e("settings.envVars.edit","Edit")}),t.jsx(Rt,{title:e("settings.envVars.deleteConfirm","Delete this variable?"),onConfirm:()=>S(I.name),okText:e("settings.envVars.yes","Yes"),cancelText:e("settings.envVars.no","No"),children:t.jsx(z,{type:"text",size:"small",danger:!0,icon:t.jsx(Et,{}),"aria-label":e("settings.envVars.delete","Delete")})})]})}];return t.jsxs("div",{style:{maxWidth:900},children:[t.jsxs(N,{className:"lotus-settings-card",title:e("settings.envVars.title","Environment Variables"),extra:t.jsx(z,{type:"primary",icon:t.jsx(dt,{}),onClick:v,children:e("settings.envVars.addButton","Add Variable")}),children:[t.jsx(Fr,{type:"secondary",style:{marginBottom:16},children:e("settings.envVars.description","Variables are injected into Bash tool processes. Secret variables are encrypted at rest.")}),t.jsx(at,{dataSource:a,columns:P,rowKey:"name",size:"small",pagination:!1,loading:r,locale:{emptyText:e("settings.envVars.noVars","No environment variables configured")}})]}),t.jsx(Qe,{title:g?e("settings.envVars.editTitle","Edit Variable"):e("settings.envVars.addTitle","Add Environment Variable"),open:l,onCancel:R,onOk:()=>c.submit(),okText:e("settings.envVars.save","Save"),cancelText:e("settings.envVars.cancel","Cancel"),destroyOnClose:!0,children:t.jsxs(y,{form:c,layout:"vertical",onFinish:p,initialValues:{secret:!1},children:[t.jsx(y.Item,{name:"name",label:e("settings.envVars.name","Name"),rules:[{required:!0,message:e("settings.envVars.nameRequired","Variable name is required")},{pattern:Ar,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:g!==null,autoFocus:g===null})}),t.jsx(y.Item,{name:"value",label:e("settings.envVars.value","Value"),rules:[{required:g===null,message:e("settings.envVars.valueRequired","Value is required for new variables")}],extra:g?e("settings.envVars.valueEditHint","Leave empty to keep the existing value"):void 0,children:t.jsx(H.Password,{placeholder:g?e("settings.envVars.valuePlaceholderEdit","Enter new value or leave empty"):e("settings.envVars.valuePlaceholder","Enter value"),visibilityToggle:!0})}),t.jsx(y.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(fe,{})}),t.jsx(y.Item,{name:"description",label:e("settings.envVars.descriptionField","Description"),children:t.jsx(H,{placeholder:e("settings.envVars.descriptionPlaceholder","Optional description")})})]})})]})},{Text:Ut,Paragraph:zr}=ue,Os="****...****",Lr={not_deployed:"default",deploying:"processing",running:"success",unreachable:"warning",stopped:"default",failed:"error"},Or=e=>{if(!e)return"";const s=new Date(e).getTime();if(Number.isNaN(s))return"";const a=Math.max(0,Math.floor((Date.now()-s)/1e3));if(a<60)return`${a}s ago`;const n=Math.floor(a/60);if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`},Nr=3e4,Vr=()=>{const{t:e}=ae(),{message:s}=ut.useApp(),[a,n]=i.useState([]),[r,o]=i.useState([]),[l,u]=i.useState(!1),[g,m]=i.useState(!1),[c,b]=i.useState(null),[p]=y.useForm(),[S,v]=i.useState(!1),[x,R]=i.useState(null),[P,C]=i.useState(""),[I,h]=i.useState(!1),k=y.useWatch("placement_type",p),V=y.useWatch("auth_method",p),F=i.useRef(0),U=i.useCallback(async(d=!1)=>{const E=++F.current;d||u(!0);try{const M=await de.listNodes();if(E!==F.current)return;n(M.nodes),o(M.clusters)}catch{d||s.error(e("settings.clusters.fetchError","Failed to load clusters"))}finally{d||u(!1)}},[s,e]);i.useEffect(()=>{U()},[U]),i.useEffect(()=>{const d=()=>{document.visibilityState==="visible"&&!g&&!S&&U(!0)},E=window.setInterval(d,Nr);return document.addEventListener("visibilitychange",d),()=>{window.clearInterval(E),document.removeEventListener("visibilitychange",d)}},[U,g,S]);const ee=i.useMemo(()=>{const d=new Map;for(const E of r)for(const M of E.node_ids)d.has(M)||d.set(M,E.name);return d},[r]),$=()=>{b(null),p.resetFields(),p.setFieldsValue({placement_type:"ssh",port:22,auth_method:"password",enabled:!0}),m(!0)},j=d=>{var K,se,pe;b(d.id);const M=d.placement.type==="ssh"?d.placement:void 0;p.setFieldsValue({label:d.label,placement_type:d.placement.type,host:M==null?void 0:M.host,port:(M==null?void 0:M.port)??22,username:M==null?void 0:M.username,auth_method:(M==null?void 0:M.auth.method)??"password",password:"",private_key:"",private_key_path:(M==null?void 0:M.auth.method)==="private_key"?M.auth.private_key_path:void 0,passphrase:"",artifact_path:(K=d.deploy)==null?void 0:K.artifact_path,default_role:(se=d.deploy)==null?void 0:se.default_role,auto_recover:((pe=d.deploy)==null?void 0:pe.auto_recover)??!1,cluster_name:(()=>{const ye=ee.get(d.id);return ye?[ye]:[]})(),enabled:d.enabled}),m(!0)},T=()=>{m(!1),b(null),p.resetFields()},D=d=>{var pe,ye;if(d.placement_type==="local")return{type:"local"};const E=c?a.find(je=>je.id===c):void 0,M=(E==null?void 0:E.placement.type)==="ssh"?E.placement.auth:void 0,K=(je,B)=>!!je&&!B;let se;if(d.auth_method==="system_ssh_config")se={method:"system_ssh_config"};else if(d.auth_method==="private_key"){const je=(M==null?void 0:M.method)==="private_key"?M.private_key:void 0,B=(M==null?void 0:M.method)==="private_key"?M.passphrase:void 0;se={method:"private_key",private_key:K(je,d.private_key)?Os:d.private_key||void 0,private_key_path:d.private_key_path||void 0,passphrase:K(B,d.passphrase)?Os:d.passphrase||void 0}}else{const je=(M==null?void 0:M.method)==="password"?M.password:void 0;se={method:"password",password:K(je,d.password)?Os:d.password}}return{type:"ssh",host:((pe=d.host)==null?void 0:pe.trim())??"",port:d.port??22,username:((ye=d.username)==null?void 0:ye.trim())??"",auth:se}},A=async d=>{var M,K;const E={label:d.label.trim(),placement:D(d),enabled:d.enabled??!0,deploy:{artifact_path:((M=d.artifact_path)==null?void 0:M.trim())||void 0,default_role:((K=d.default_role)==null?void 0:K.trim())||void 0,auto_recover:d.auto_recover??!1}};try{const se=c?await de.updateNode(c,E):await de.createNode(E),pe=Array.isArray(d.cluster_name)?d.cluster_name[0]:d.cluster_name;try{await Q(se.id,pe)}catch(ye){s.warning((ye instanceof Error?ye.message:void 0)||e("settings.clusters.membershipError","Node saved, but updating cluster membership failed")),T(),U();return}s.success(c?e("settings.clusters.updated","Node updated"):e("settings.clusters.created","Node created")),T(),U()}catch(se){s.error((se instanceof Error?se.message:void 0)||e("settings.clusters.saveError","Failed to save node"))}},Q=async(d,E)=>{const M=E==null?void 0:E.trim();for(const se of r){const pe=se.name===M,ye=se.node_ids.includes(d);!pe&&ye&&await de.updateCluster(se.name,{name:se.name,description:se.description,node_ids:se.node_ids.filter(je=>je!==d)})}if(!M)return;const K=r.find(se=>se.name===M);K?K.node_ids.includes(d)||await de.updateCluster(M,{name:M,description:K.description,node_ids:[...K.node_ids,d]}):await de.createCluster({name:M,node_ids:[d]})},O=async d=>{try{await de.deleteNode(d),s.success(e("settings.clusters.deleted","Node deleted")),U()}catch(E){s.error((E instanceof Error?E.message:void 0)||e("settings.clusters.deleteError","Failed to delete node"))}},Y=async(d,E)=>{try{const M=await de.nodeAction(d,E),K=E==="test"&&M&&typeof M=="object"&&"preflight"in M?String(M.preflight??""):"";s.success(K?e("settings.clusters.testOk","Reachable: {{info}}",{info:K}):e("settings.clusters.actionOk","Action triggered")),U()}catch(M){s.error((M instanceof Error?M.message:void 0)||e("settings.clusters.actionFailed","Action failed"))}},G=async d=>{R(d),v(!0),h(!0),C("");try{const E=await de.nodeLogs(d.id,200);C(E.logs||e("settings.clusters.logsEmpty","(no log output yet)"))}catch(E){C((E instanceof Error?E.message:void 0)||e("settings.clusters.logsError","Failed to read logs"))}finally{h(!1)}},ne=[{title:e("settings.clusters.label","Label"),dataIndex:"label",key:"label",render:(d,E)=>t.jsxs(L,{children:[t.jsx(Bn,{}),t.jsx(Ut,{strong:!0,children:d}),!E.enabled&&t.jsx(re,{children:e("settings.clusters.disabled","disabled")})]})},{title:e("settings.clusters.target","Target"),key:"target",render:(d,E)=>E.placement.type==="ssh"?t.jsxs(Ut,{code:!0,children:[E.placement.username,"@",E.placement.host,":",E.placement.port]}):t.jsx(re,{color:"blue",children:e("settings.clusters.local","local")})},{title:e("settings.clusters.cluster","Cluster"),key:"cluster",render:(d,E)=>{const M=ee.get(E.id);return M?t.jsx(re,{children:M}):t.jsx(Ut,{type:"secondary",children:"—"})}},{title:e("settings.clusters.status","Status"),key:"status",render:(d,E)=>{var ye,je,B;const M=((ye=E.state)==null?void 0:ye.status)??"not_deployed",K=(je=E.state)==null?void 0:je.last_error,se=Or((B=E.state)==null?void 0:B.last_health),pe=t.jsx(re,{color:Lr[M],children:M.replace(/_/g," ")});return t.jsxs(L,{direction:"vertical",size:0,children:[K&&(M==="unreachable"||M==="failed")?t.jsx(ke,{title:K,children:pe}):pe,se&&t.jsx(Ut,{type:"secondary",style:{fontSize:11},children:e("settings.clusters.lastSeen","seen {{ago}}",{ago:se})})]})}},{title:e("settings.clusters.actions","Actions"),key:"actions",width:320,render:(d,E)=>t.jsxs(L,{size:"small",wrap:!0,children:[t.jsx(z,{size:"small",onClick:()=>Y(E.id,"test"),children:e("settings.clusters.test","Test")}),t.jsx(z,{size:"small",type:"primary",ghost:!0,onClick:()=>Y(E.id,"deploy"),children:e("settings.clusters.deploy","Deploy")}),t.jsx(z,{size:"small",onClick:()=>Y(E.id,"stop"),children:e("settings.clusters.stop","Stop")}),t.jsx(z,{size:"small",onClick:()=>G(E),children:e("settings.clusters.logs","Logs")}),t.jsx(z,{type:"text",size:"small",icon:t.jsx(is,{}),onClick:()=>j(E),"aria-label":e("settings.clusters.edit","Edit")}),t.jsx(Rt,{title:e("settings.clusters.deleteConfirm","Delete this node?"),onConfirm:()=>O(E.id),okText:e("settings.clusters.yes","Yes"),cancelText:e("settings.clusters.no","No"),children:t.jsx(z,{type:"text",size:"small",danger:!0,icon:t.jsx(Et,{}),"aria-label":e("settings.clusters.delete","Delete")})})]})}],ie=k!=="local",be=c?a.find(d=>d.id===c):void 0;return t.jsxs("div",{style:{maxWidth:1e3},children:[t.jsxs(N,{className:"lotus-settings-card",title:e("settings.clusters.title","Remote Clusters"),extra:t.jsx(z,{type:"primary",icon:t.jsx(dt,{}),onClick:$,children:e("settings.clusters.addButton","Add Node")}),children:[t.jsx(zr,{type:"secondary",style:{marginBottom:16},children:e("settings.clusters.description","Register machines (local or over SSH) to deploy worker agents onto. SSH credentials are encrypted at rest and never sent to the agent. Deploy/Test/Stop are wired but the deploy engine ships in a later phase.")}),t.jsx(at,{dataSource:a,columns:ne,rowKey:"id",size:"small",pagination:!1,loading:l,locale:{emptyText:e("settings.clusters.noNodes","No nodes registered")}})]}),t.jsx(Qe,{title:c?e("settings.clusters.editTitle","Edit Node"):e("settings.clusters.addTitle","Add Node"),open:g,onCancel:T,onOk:()=>p.submit(),okText:e("settings.clusters.save","Save"),cancelText:e("settings.clusters.cancel","Cancel"),width:560,destroyOnClose:!0,children:t.jsxs(y,{form:p,layout:"vertical",onFinish:A,children:[t.jsx(y.Item,{name:"label",label:e("settings.clusters.label","Label"),rules:[{required:!0,message:e("settings.clusters.labelRequired","Label is required")}],children:t.jsx(H,{placeholder:"gpu-1",autoFocus:!0})}),t.jsx(y.Item,{name:"placement_type",label:e("settings.clusters.placement","Placement"),children:t.jsx(te,{options:[{value:"ssh",label:e("settings.clusters.ssh","SSH (remote)")},{value:"local",label:e("settings.clusters.localhost","Local (this host)")}]})}),ie&&t.jsxs(t.Fragment,{children:[t.jsxs(L.Compact,{block:!0,children:[t.jsx(y.Item,{name:"host",label:e("settings.clusters.host","Host"),style:{width:"70%"},rules:[{required:!0,message:e("settings.clusters.hostRequired","Host is required")}],children:t.jsx(H,{placeholder:"10.0.0.5"})}),t.jsx(y.Item,{name:"port",label:e("settings.clusters.port","Port"),style:{width:"30%"},children:t.jsx(Me,{min:1,max:65535,style:{width:"100%"}})})]}),t.jsx(y.Item,{name:"username",label:e("settings.clusters.username","Username"),rules:[{required:!0,message:e("settings.clusters.usernameRequired","Username is required")}],children:t.jsx(H,{placeholder:"deploy"})}),t.jsx(y.Item,{name:"auth_method",label:e("settings.clusters.authMethod","Auth method"),children:t.jsx(te,{options:[{value:"password",label:e("settings.clusters.password","Password")},{value:"private_key",label:e("settings.clusters.privateKey","Private key")},{value:"system_ssh_config",label:e("settings.clusters.systemSsh","Use host's SSH config")}]})}),V==="password"&&t.jsx(y.Item,{name:"password",label:e("settings.clusters.password","Password"),extra:be?e("settings.clusters.secretEditHint","Leave empty to keep the existing secret"):void 0,rules:[{required:!be,message:e("settings.clusters.passwordRequired","Password is required")}],children:t.jsx(H.Password,{visibilityToggle:!0,placeholder:be?e("settings.clusters.keepSecret","Enter new password or leave empty"):void 0})}),V==="private_key"&&t.jsxs(t.Fragment,{children:[t.jsx(y.Item,{name:"private_key_path",label:e("settings.clusters.privateKeyPath","Private key file path (on this host)"),children:t.jsx(H,{placeholder:"~/.ssh/id_ed25519"})}),t.jsx(y.Item,{name:"private_key",label:e("settings.clusters.privateKeyInline","…or paste key (PEM)"),dependencies:["private_key_path"],extra:be?e("settings.clusters.secretEditHint","Leave empty to keep the existing secret"):void 0,rules:[{validator:async()=>{var K,se;const d=(K=p.getFieldValue("private_key_path"))==null?void 0:K.trim(),E=(se=p.getFieldValue("private_key"))==null?void 0:se.trim();if(d||E)return;const M=(be==null?void 0:be.placement.type)==="ssh"?be.placement.auth:void 0;if(!((M==null?void 0:M.method)==="private_key"&&(M.private_key||M.private_key_path)))throw new Error(e("settings.clusters.privateKeyRequired","Provide a key file path or paste a private key"))}}],children:t.jsx(H.TextArea,{rows:3,placeholder:"-----BEGIN OPENSSH PRIVATE KEY-----"})}),t.jsx(y.Item,{name:"passphrase",label:e("settings.clusters.passphrase","Passphrase"),children:t.jsx(H.Password,{visibilityToggle:!0})})]})]}),t.jsx(y.Item,{name:"artifact_path",label:e("settings.clusters.artifactPath","Artifact path (binary to upload)"),extra:e("settings.clusters.artifactHint","Path on this host to the correct-arch bamboo binary; used at deploy time (P2)."),children:t.jsx(H,{placeholder:"/path/to/bamboo-linux-x64"})}),t.jsx(y.Item,{name:"default_role",label:e("settings.clusters.role","Default role"),children:t.jsx(H,{placeholder:"worker"})}),t.jsx(y.Item,{name:"auto_recover",label:e("settings.clusters.autoRecover","Auto-recover"),valuePropName:"checked",extra:e("settings.clusters.autoRecoverHint","Redeploy this node automatically if the health monitor finds its worker gone."),children:t.jsx(fe,{})}),t.jsx(y.Item,{name:"cluster_name",label:e("settings.clusters.cluster","Cluster"),children:t.jsx(te,{allowClear:!0,showSearch:!0,mode:"tags",maxCount:1,placeholder:e("settings.clusters.clusterPlaceholder","Pick or type a cluster name"),options:r.map(d=>({value:d.name,label:d.name}))})}),t.jsx(y.Item,{name:"enabled",label:e("settings.clusters.enabled","Enabled"),valuePropName:"checked",children:t.jsx(fe,{})})]})}),t.jsx(Qe,{title:e("settings.clusters.logsTitle","Logs — {{label}}",{label:(x==null?void 0:x.label)??""}),open:S,onCancel:()=>v(!1),onOk:()=>x&&G(x),okText:e("settings.clusters.refresh","Refresh"),cancelText:e("settings.clusters.close","Close"),width:760,destroyOnClose:!0,children:I?t.jsx(Ut,{type:"secondary",children:e("settings.clusters.loading","Loading…")}):t.jsx("pre",{style:{maxHeight:420,overflow:"auto",fontSize:12,whiteSpace:"pre-wrap",wordBreak:"break-all",margin:0},children:P})})]})},Ct=class Ct{constructor(){}static getInstance(){return Ct.instance||(Ct.instance=new Ct),Ct.instance}async listWorkflows(){try{ct("[WorkflowManager]","[WorkflowManagerService] Listing workflows");const s=await da.get("bamboo/workflows"),a=Array.isArray(s)?s:[];return ct("[WorkflowManager]","[WorkflowManagerService] Listed workflows:",a),a.map(n=>({name:String(n.name||""),filename:String(n.filename||(n.name||"workflow")+".md"),size:Number(n.size||0),modified_at:typeof n.modified_at=="string"?n.modified_at:void 0,source:"global"}))}catch(s){throw console.error("[WorkflowManagerService] Failed to list workflows:",s),s}}async getWorkflow(s){try{ct("[WorkflowManager]","[WorkflowManagerService] Getting workflow: "+s);const a=await da.get("bamboo/workflows/"+encodeURIComponent(s)),n=a!=null&&a.name?String(a.name):s,r={name:n,filename:String((a==null?void 0:a.filename)||n+".md"),size:Number((a==null?void 0:a.size)||0),modified_at:a==null?void 0:a.modified_at,source:"global"};return ct("[WorkflowManager]","[WorkflowManagerService] Got workflow:",a),{name:n,content:String((a==null?void 0:a.content)||""),metadata:r}}catch(a){throw console.error("[WorkflowManagerService] Failed to get workflow "+s+":",a),ir(a)&&a.status===404?new Error("Workflow '"+s+"' not found"):a instanceof Error&&a.message.includes("404")?new Error("Workflow '"+s+"' not found"):a}}};la(Ct,"instance");let ea=Ct;const{Text:Ns}=ue,{TextArea:$r}=H,{useToken:Br}=Te,qr=e=>!(!e||e.includes("/")||e.includes("\\")||e.includes("..")),Hr=()=>{const{t:e}=ae(),{token:s}=Br(),[a,n]=zt.useMessage(),[r,o]=i.useState([]),[l,u]=i.useState(!1),[g,m]=i.useState(!1),[c,b]=i.useState(!1),[p,S]=i.useState(null),[v,x]=i.useState(""),[R,P]=i.useState(""),[C,I]=i.useState(!1),h=i.useMemo(()=>ea.getInstance(),[]),k=i.useCallback(async()=>{u(!0);try{const $=await h.listWorkflows();return o($),$}catch{return a.error(e("settings.workflowsTab.loadFailed")),[]}finally{u(!1)}},[a,e,h]);i.useEffect(()=>{k()},[k]);const V=i.useCallback(async $=>{S($),x($.name),I(!1),m(!0);try{const j=await h.getWorkflow($.name);P(j.content??"")}catch{a.error(e("settings.workflowsTab.loadContentFailed")),P("")}finally{m(!1)}},[a,e,h]),F=()=>{S(null),x(""),P(""),I(!1)},U=i.useCallback(async()=>{if(!qr(v)){a.error(e("settings.workflowsTab.invalidName"));return}const $=r.some(j=>j.name===v);if(!p&&$){a.error(e("settings.workflowsTab.nameAlreadyExists"));return}b(!0);try{await it.getInstance().saveWorkflow(v,R),a.success(e("settings.workflowsTab.saved")),I(!1);const D=(await k()).find(A=>A.name===v);D&&S(D)}catch(j){a.error(j instanceof Error?j.message:e("settings.workflowsTab.saveFailed"))}finally{b(!1)}},[R,v,k,a,p,e,r]),ee=i.useCallback(async $=>{try{await it.getInstance().deleteWorkflow($.name),a.success(e("settings.workflowsTab.deleted")),(p==null?void 0:p.name)===$.name&&F(),await k()}catch(j){a.error(j instanceof Error?j.message:e("settings.workflowsTab.deleteFailed"))}},[k,a,p,e]);return t.jsxs("div",{style:{padding:"24px"},children:[n,t.jsxs(N,{title:e("settings.workflowsTab.title"),extra:t.jsxs(L,{children:[t.jsx(z,{icon:t.jsx(Lt,{}),onClick:k,loading:l,children:e("settings.workflowsTab.refresh")}),t.jsx(z,{"data-testid":"create-workflow",icon:t.jsx(dt,{}),onClick:F,children:e("settings.workflowsTab.newWorkflow")}),t.jsx(z,{"data-testid":"save-workflow",type:"primary",icon:t.jsx(ws,{}),onClick:U,loading:c,disabled:!C,children:e("settings.workflowsTab.save")})]}),children:[t.jsx(Ns,{type:"secondary",children:e("settings.workflowsTab.description")}),t.jsxs(X,{gap:s.marginLG,style:{marginTop:s.marginLG},children:[t.jsx("div",{style:{width:320,flexShrink:0},children:t.jsx(Xe,{loading:l,dataSource:r,locale:{emptyText:e("settings.workflowsTab.empty")},renderItem:$=>t.jsx(Xe.Item,{style:{cursor:"pointer",backgroundColor:(p==null?void 0:p.name)===$.name?s.colorFillSecondary:"transparent",borderRadius:s.borderRadius,padding:s.paddingSM},onClick:()=>V($),actions:[t.jsx(z,{"data-testid":`delete-workflow-${$.name}`,type:"text",danger:!0,size:"small",icon:t.jsx(Et,{}),onClick:j=>{j.stopPropagation(),ee($)},"aria-label":e("settings.workflowsTab.delete")},"delete")],children:t.jsxs(L,{direction:"vertical",size:0,children:[t.jsxs(Ns,{strong:!0,children:["/",$.name]}),t.jsx(Ns,{type:"secondary",style:{fontSize:12},children:$.filename})]})})})}),t.jsx("div",{style:{flex:1},children:t.jsxs(L,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(H,{"data-testid":"workflow-name",placeholder:e("settings.workflowsTab.namePlaceholder"),value:v,onChange:$=>{x($.target.value),I(!0)},disabled:!!p,prefix:t.jsx(is,{})}),t.jsx($r,{"data-testid":"workflow-content",placeholder:e("settings.workflowsTab.contentPlaceholder"),value:R,onChange:$=>{P($.target.value),I(!0)},autoSize:{minRows:12},disabled:g})]})})]})]})]})};var W=(e=>(e.Connecting="connecting",e.Ready="ready",e.Degraded="degraded",e.Stopped="stopped",e.Error="error",e))(W||{});const ds=6e4,us=3e4,ns=2e4,Ss=1e4,Cs=e=>({id:e,enabled:!0,transport:{type:"stdio",command:"",args:[],env:{},startup_timeout_ms:ns},request_timeout_ms:ds,healthcheck_interval_ms:us,allowed_tools:[],denied_tools:[]}),Ur=()=>({status:"stopped",tool_count:0,restart_count:0}),Kr=e=>{switch(typeof e=="string"?e.trim().toLowerCase():""){case W.Connecting:return W.Connecting;case W.Ready:return W.Ready;case W.Degraded:return W.Degraded;case W.Error:return W.Error;case W.Stopped:default:return W.Stopped}},ot=(e,s)=>{if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const a=Number(e);if(Number.isFinite(a))return a}return s},Wr=(e,s)=>{if(!e||typeof e!="object")return s;const a=e;if(a.type==="sse"){const o=Array.isArray(a.headers)?a.headers.map(l=>{if(!l||typeof l!="object")return null;const u=l;return typeof u.name!="string"||typeof u.value!="string"?null:{name:u.name,value:u.value}}).filter(l=>!!l):[];return{type:"sse",url:typeof a.url=="string"?a.url:"",headers:o,connect_timeout_ms:ot(a.connect_timeout_ms,Ss)}}const n=Array.isArray(a.args)?a.args.filter(o=>typeof o=="string"):[],r=a.env&&typeof a.env=="object"?Object.entries(a.env):[];return{type:"stdio",command:typeof a.command=="string"?a.command:"",args:n,cwd:typeof a.cwd=="string"?a.cwd:void 0,env:r.reduce((o,[l,u])=>(typeof u=="string"&&(o[l]=u),o),{}),startup_timeout_ms:ot(a.startup_timeout_ms,ns)}},Gr=(e,s)=>{const a=Cs(e.id),n=s??{};return{...a,...n,id:e.id,name:typeof n.name=="string"?n.name:typeof e.name=="string"?e.name:void 0,enabled:typeof e.enabled=="boolean"?e.enabled:typeof n.enabled=="boolean"?n.enabled:!0,request_timeout_ms:ot(n.request_timeout_ms,ds),healthcheck_interval_ms:ot(n.healthcheck_interval_ms,us),allowed_tools:Array.isArray(n.allowed_tools)?n.allowed_tools.filter(o=>typeof o=="string"):[],denied_tools:Array.isArray(n.denied_tools)?n.denied_tools.filter(o=>typeof o=="string"):[],reconnect:n.reconnect&&typeof n.reconnect=="object"?{enabled:typeof n.reconnect.enabled=="boolean"?n.reconnect.enabled:!0,initial_backoff_ms:ot(n.reconnect.initial_backoff_ms,1e3),max_backoff_ms:ot(n.reconnect.max_backoff_ms,3e4),max_attempts:ot(n.reconnect.max_attempts,0)}:void 0,transport:Wr(n.transport,a.transport)}},Jr=e=>{const s=Ur(),n=e.runtime??{},r=n.status??e.status;return{status:Kr(r),last_error:typeof n.last_error=="string"?n.last_error:typeof e.last_error=="string"?e.last_error:void 0,connected_at:typeof n.connected_at=="string"?n.connected_at:void 0,disconnected_at:typeof n.disconnected_at=="string"?n.disconnected_at:void 0,tool_count:ot(n.tool_count??e.tool_count,s.tool_count),restart_count:ot(n.restart_count??e.restart_count,s.restart_count),last_ping_at:typeof n.last_ping_at=="string"?n.last_ping_at:void 0}},Xr=e=>{const s=Gr(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:Jr(e)}},Yr=(e,s)=>`mcp__${e}__${s}`,Zr=e=>{if(!e.startsWith("mcp__"))return null;const s=e.slice(5),a=s.indexOf("__");if(a<=0)return null;const n=s.slice(0,a),r=s.slice(a+2);return!n||!r?null:{server_id:n,original_name:r}},Qr=(e,s,a=0)=>{if(!e||typeof e!="object")return null;const n=e,r=typeof n.alias=="string"?n.alias:typeof n.name=="string"&&n.name.startsWith("mcp__")?n.name:void 0,o=r&&typeof r=="string"?Zr(r):null,l=(typeof n.server_id=="string"?n.server_id:void 0)??(typeof n.serverId=="string"?n.serverId:void 0)??(o==null?void 0:o.server_id)??s??"",u=(typeof n.original_name=="string"?n.original_name:void 0)??(typeof n.originalName=="string"?n.originalName:void 0)??(o==null?void 0:o.original_name)??(typeof n.name=="string"?n.name:void 0)??"",g=r??(l&&u?Yr(l,u):""),m=typeof n.description=="string"?n.description:"",c=n,b="parameters"in c?c.parameters:"inputSchema"in c?c.inputSchema:"input_schema"in c?c.input_schema:void 0,p=g||u||`mcp_tool_${a}`;return{alias:p,server_id:l||"unknown",original_name:u||p,description:m,parameters:b}};class ei{async getServers(){const s=await Ye.get("mcp/servers");return Array.isArray(s.servers)?s.servers.map(Xr):[]}async addServer(s){return Ye.post("mcp/servers",s)}async updateServer(s,a){const n={...a,id:s};return Ye.put(`mcp/servers/${s}`,n)}async deleteServer(s){return Ye.delete(`mcp/servers/${s}`)}async connectServer(s){return Ye.post(`mcp/servers/${s}/connect`)}async disconnectServer(s){return Ye.post(`mcp/servers/${s}/disconnect`)}async refreshTools(s){return Ye.post(`mcp/servers/${s}/refresh`)}async getTools(s){const a=s?`mcp/servers/${s}/tools`:"mcp/tools",n=await Ye.get(a);return(Array.isArray(n.tools)?n.tools:[]).map((o,l)=>Qr(o,s,l)).filter(o=>!!o)}async importServers(s){return Ye.post("mcp/servers/import",s)}}const sn=new ei,ti=5e3,nt=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,_a=(e,s)=>`${e}:${s}`,si=(e={})=>{const{service:s=sn,autoRefreshMs:a=ti,autoRefreshEnabled:n=!0}=e,[r,o]=i.useState([]),[l,u]=i.useState(null),[g,m]=i.useState({}),[c,b]=i.useState({}),[p,S]=i.useState({}),[v,x]=i.useState(!1),[R,P]=i.useState(!1),[C,I]=i.useState(!1),[h,k]=i.useState(null),V=i.useRef({}),F=i.useCallback(d=>{const E=new Set(d.map(K=>K.id)),M=d.map(K=>{const pe=V.current[K.id]??K.config,ye={...pe,id:K.id,name:pe.name??K.name};return V.current[K.id]=ye,{...K,name:K.name||ye.name||K.id,enabled:K.enabled??ye.enabled,config:ye}});return Object.keys(V.current).forEach(K=>{E.has(K)||delete V.current[K]}),M},[]),U=i.useCallback(async({silent:d=!1}={})=>{d||x(!0);try{const E=await s.getServers(),M=F(E);o(M),u(K=>{var se;return K&&M.some(pe=>pe.id===K)?K:((se=M[0])==null?void 0:se.id)??null}),k(null)}catch(E){throw k(nt(E,"Failed to load MCP servers")),E}finally{d||x(!1)}},[F,s]),ee=i.useCallback(async(d,E=!1)=>{if(!d)return[];if(!E&&g[d])return g[d];b(M=>({...M,[d]:!0}));try{const M=await s.getTools(d);return m(K=>({...K,[d]:M})),k(null),M}catch(M){throw k(nt(M,"Failed to load MCP tools")),M}finally{b(M=>({...M,[d]:!1}))}},[s,g]),$=i.useCallback((d,E,M)=>{const K=_a(d,E);S(se=>({...se,[K]:M}))},[]),j=i.useCallback(async d=>{P(!0);try{await s.addServer(d),V.current[d.id]=d,await U()}catch(E){throw k(nt(E,"Failed to add MCP server")),E}finally{P(!1)}},[U,s]),T=i.useCallback(async(d,E)=>{P(!0);try{const M={...E,id:d};await s.updateServer(d,M),V.current[d]=M,await U()}catch(M){throw k(nt(M,"Failed to update MCP server")),M}finally{P(!1)}},[U,s]),D=i.useCallback(async d=>{$(d,"delete",!0);try{await s.deleteServer(d),m(E=>{const M={...E};return delete M[d],M}),delete V.current[d],await U()}catch(E){throw k(nt(E,"Failed to delete MCP server")),E}finally{$(d,"delete",!1)}},[U,s,$]),A=i.useCallback(async d=>{$(d,"connect",!0);try{await s.connectServer(d),await U({silent:!0})}catch(E){throw k(nt(E,"Failed to connect MCP server")),E}finally{$(d,"connect",!1)}},[U,s,$]),Q=i.useCallback(async d=>{$(d,"disconnect",!0);try{await s.disconnectServer(d),await U({silent:!0})}catch(E){throw k(nt(E,"Failed to disconnect MCP server")),E}finally{$(d,"disconnect",!1)}},[U,s,$]),O=i.useCallback(async d=>{$(d,"refresh",!0);try{await s.refreshTools(d),await ee(d,!0),await U({silent:!0})}catch(E){throw k(nt(E,"Failed to refresh MCP tools")),E}finally{$(d,"refresh",!1)}},[ee,U,s,$]),Y=i.useCallback(async()=>{I(!0);try{const d=r.map(E=>E.id);await Promise.all(d.map(async E=>{try{await s.refreshTools(E)}catch{}})),await U(),l&&await ee(l,!0)}catch(d){throw k(nt(d,"Failed to refresh MCP status")),d}finally{I(!1)}},[ee,U,l,r,s]),G=i.useCallback(d=>{u(d)},[]),ne=i.useCallback((d,E)=>!!p[_a(d,E)],[p]),ie=i.useMemo(()=>l?g[l]??[]:[],[l,g]),be=i.useMemo(()=>l?!!c[l]:!1,[l,c]);return i.useEffect(()=>{U().catch(()=>{})},[U]),i.useEffect(()=>{if(!n||a<=0)return;const d=window.setInterval(()=>{U({silent:!0}).catch(()=>{})},a);return()=>{window.clearInterval(d)}},[n,a,U]),i.useEffect(()=>{l&&ee(l).catch(()=>{})},[ee,l]),{servers:r,selectedServerId:l,selectedServerTools:ie,isLoadingServers:v,isMutatingConfig:R,isRefreshingAll:C,isSelectedServerToolsLoading:be,error:h,setSelectedServerId:G,refreshServers:U,addServer:j,updateServer:T,deleteServer:D,connectServer:A,disconnectServer:Q,refreshServerTools:O,refreshAll:Y,isServerActionLoading:ne}},ai={[W.Connecting]:"blue",[W.Ready]:"green",[W.Degraded]:"orange",[W.Stopped]:"default",[W.Error]:"red"},ni=e=>e===W.Connecting||e===W.Ready||e===W.Degraded,ri=e=>{if(!e)return;const s=e.replace(/\s+/g," ").trim();if(s)return s.length>180?`${s.slice(0,180)}...`:s},ii=({servers:e,loading:s=!1,selectedServerId:a,onSelectServer:n,onEditServer:r,onDeleteServer:o,onConnectServer:l,onDisconnectServer:u,onRefreshTools:g,isServerActionLoading:m})=>{const{t:c}=ae(),{token:b}=Te.useToken(),p=i.useMemo(()=>({[W.Connecting]:c("settings.mcpTab.statusHelp.connecting"),[W.Ready]:c("settings.mcpTab.statusHelp.ready"),[W.Degraded]:c("settings.mcpTab.statusHelp.degraded"),[W.Stopped]:c("settings.mcpTab.statusHelp.stopped"),[W.Error]:c("settings.mcpTab.statusHelp.error")}),[c]),S=i.useMemo(()=>[{key:"name",title:c("settings.mcpServerTable.columns.name"),render:(v,x)=>x.name||x.id},{key:"transport",title:c("settings.mcpServerTable.columns.transportType"),render:(v,x)=>x.config.transport.type==="sse"?c("settings.mcpServerTable.transportOptions.sse"):c("settings.mcpServerTable.transportOptions.stdio"),width:140},{key:"status",title:c("settings.mcpServerTable.columns.status"),render:(v,x)=>{var h,k;const R=((h=x.runtime)==null?void 0:h.status)??W.Stopped,P=ri((k=x.runtime)==null?void 0:k.last_error),C=p[R],I={[W.Connecting]:c("settings.mcpTab.status.connecting"),[W.Ready]:c("settings.mcpTab.status.ready"),[W.Degraded]:c("settings.mcpTab.status.degraded"),[W.Stopped]:c("settings.mcpTab.status.stopped"),[W.Error]:c("settings.mcpTab.status.error")};return t.jsx(ke,{title:P?`${C} ${c("settings.mcpTab.statusLastError",{error:P})}`:C,children:t.jsx(re,{color:R===W.Stopped?void 0:ai[R],style:{marginInlineEnd:0,cursor:"help",...R===W.Stopped?{background:b.colorFillSecondary,borderColor:b.colorBorderSecondary,color:b.colorTextSecondary}:void 0},children:I[R]})})},width:120},{key:"toolCount",title:c("settings.mcpServerTable.columns.toolCount"),render:(v,x)=>{var R;return((R=x.runtime)==null?void 0:R.tool_count)??0},width:100},{key:"actions",title:c("settings.mcpServerTable.columns.actions"),width:360,render:(v,x)=>{var C;const R=((C=x.runtime)==null?void 0:C.status)??W.Stopped,P=ni(R);return t.jsxs(L,{size:b.marginXS,children:[t.jsx(z,{size:"small",onClick:I=>{I.stopPropagation(),r==null||r(x)},children:c("settings.mcpServerTable.actions.edit")}),t.jsx(Rt,{title:c("settings.mcpServerTable.deleteTitle"),description:c("settings.mcpServerTable.deleteDescription",{name:x.name||x.id}),onConfirm:()=>o==null?void 0:o(x),okText:c("settings.mcpServerTable.actions.delete"),okButtonProps:{danger:!0,loading:m==null?void 0:m(x.id,"delete")},children:t.jsx(z,{size:"small",danger:!0,loading:m==null?void 0:m(x.id,"delete"),onClick:I=>I.stopPropagation(),children:c("settings.mcpServerTable.actions.delete")})}),P?t.jsx(z,{size:"small",onClick:I=>{I.stopPropagation(),u==null||u(x)},loading:m==null?void 0:m(x.id,"disconnect"),children:c("settings.mcpServerTable.actions.disconnect")}):t.jsx(z,{size:"small",type:"primary",ghost:!0,onClick:I=>{I.stopPropagation(),l==null||l(x)},loading:m==null?void 0:m(x.id,"connect"),children:c("settings.mcpServerTable.actions.connect")}),t.jsx(z,{size:"small",onClick:I=>{I.stopPropagation(),g==null||g(x)},loading:m==null?void 0:m(x.id,"refresh"),children:c("settings.mcpServerTable.actions.refreshTools")})]})}}],[m,l,o,u,r,g,p,c,b.colorBorderSecondary,b.colorFillSecondary,b.colorTextSecondary,b.marginXS]);return t.jsx(at,{rowKey:"id",columns:S,dataSource:e,loading:s,pagination:!1,locale:{emptyText:c("settings.mcpServerTable.empty")},onRow:v=>({onClick:()=>n==null?void 0:n(v.id),style:{cursor:n?"pointer":"default",backgroundColor:a===v.id?b.colorFillSecondary:void 0}})})},{Text:Sa}=ue,{TextArea:oi}=H,ka=e=>{const s=e??Cs(""),a=s.transport,n=a.type==="stdio"?Object.entries(a.env??{}).map(([o,l])=>({key:o,value:l})):[],r=a.type==="sse"?a.headers.map(o=>({name:o.name,value:o.value})):[];return{id:s.id,name:s.name,enabled:s.enabled,transportType:a.type,command:a.type==="stdio"?a.command:void 0,args:a.type==="stdio"?a.args:[],envEntries:n,url:a.type==="sse"?a.url:void 0,headerEntries:r,requestTimeoutMs:s.request_timeout_ms||ds,healthcheckIntervalMs:s.healthcheck_interval_ms||us,allowedTools:s.allowed_tools||[],deniedTools:s.denied_tools||[]}},li=e=>e.reduce((s,a)=>{var r;const n=(r=a.key)==null?void 0:r.trim();return n&&(s[n]=a.value??""),s},{}),ci=e=>e.filter(s=>{var a;return(a=s.name)==null?void 0:a.trim()}).map(s=>{var a;return{name:((a=s.name)==null?void 0:a.trim())||"",value:s.value??""}}),wa=(e,s,a)=>{var c,b,p;const n=s==="edit"&&(a==null?void 0:a.id)||e.id,r=(c=e.name)==null?void 0:c.trim(),o=typeof e.requestTimeoutMs=="number"?e.requestTimeoutMs:(a==null?void 0:a.request_timeout_ms)??ds,l=typeof e.healthcheckIntervalMs=="number"?e.healthcheckIntervalMs:(a==null?void 0:a.healthcheck_interval_ms)??us,u=Array.isArray(e.allowedTools)?e.allowedTools:(a==null?void 0:a.allowed_tools)??[],g=Array.isArray(e.deniedTools)?e.deniedTools:(a==null?void 0:a.denied_tools)??[],m=e.transportType==="sse"?{type:"sse",url:((b=e.url)==null?void 0:b.trim())||"",headers:ci(e.headerEntries||[]),connect_timeout_ms:(a==null?void 0:a.transport.type)==="sse"?a.transport.connect_timeout_ms??Ss:Ss}:{type:"stdio",command:((p=e.command)==null?void 0:p.trim())||"",args:e.args||[],env:li(e.envEntries||[]),cwd:(a==null?void 0:a.transport.type)==="stdio"?a.transport.cwd:void 0,startup_timeout_ms:(a==null?void 0:a.transport.type)==="stdio"?a.transport.startup_timeout_ms??ns:ns};return{id:n,name:r||void 0,enabled:e.enabled,transport:m,request_timeout_ms:o,healthcheck_interval_ms:l,allowed_tools:u,denied_tools:g,reconnect:a==null?void 0:a.reconnect}},Ca=e=>JSON.stringify(e||Cs(""),null,2),Vs=(e,s)=>{try{const a=JSON.parse(e);if(!a||typeof a!="object")return{valid:!1,error:s("settings.mcpServerForm.jsonMustBeObject")};const n=a;if(n.mcpServers&&typeof n.mcpServers=="object")return{valid:!1,error:s("settings.mcpServerForm.detectedBulkConfig")};const r=typeof n.id=="string"?n.id:"";if(!r.trim())return{valid:!1,error:s("settings.mcpServerForm.missingIdField")};if(n.transport&&typeof n.transport=="object"){const b=n;return!b.transport||typeof b.transport!="object"?{valid:!1,error:s("settings.mcpServerForm.missingTransportField")}:{valid:!0,config:b}}const o=typeof n.enabled=="boolean"?n.enabled:typeof n.disabled=="boolean"?!n.disabled:!0,l=typeof n.request_timeout_ms=="number"?n.request_timeout_ms:ds,u=typeof n.healthcheck_interval_ms=="number"?n.healthcheck_interval_ms:us,g=Array.isArray(n.allowed_tools)?n.allowed_tools.filter(b=>typeof b=="string"):[],m=Array.isArray(n.denied_tools)?n.denied_tools.filter(b=>typeof b=="string"):[],c=typeof n.name=="string"?n.name:void 0;if(typeof n.url=="string"){const b=n.headers,p=Array.isArray(b)?b.map(v=>{if(!v||typeof v!="object")return null;const x=v,R=typeof x.name=="string"?x.name:"",P=typeof x.value=="string"?x.value:"";return R.trim()?{name:R,value:P}:null}).filter(v=>!!v):b&&typeof b=="object"?Object.entries(b).filter(([v])=>v.trim()).map(([v,x])=>({name:v,value:typeof x=="string"?x:""})):[],S=typeof n.connect_timeout_ms=="number"?n.connect_timeout_ms:Ss;return{valid:!0,config:{id:r,name:c,enabled:o,transport:{type:"sse",url:n.url,headers:p,connect_timeout_ms:S},request_timeout_ms:l,healthcheck_interval_ms:u,allowed_tools:g,denied_tools:m,reconnect:void 0}}}if(typeof n.command=="string"){const b=Array.isArray(n.args)?n.args.filter(x=>typeof x=="string"):[],p=n.env,S=p&&typeof p=="object"?Object.entries(p).reduce((x,[R,P])=>(typeof P=="string"&&(x[R]=P),x),{}):{},v=typeof n.startup_timeout_ms=="number"?n.startup_timeout_ms:ns;return{valid:!0,config:{id:r,name:c,enabled:o,transport:{type:"stdio",command:n.command,args:b,cwd:typeof n.cwd=="string"?n.cwd:void 0,env:S,startup_timeout_ms:v},request_timeout_ms:l,healthcheck_interval_ms:u,allowed_tools:g,denied_tools:m,reconnect:void 0}}}return{valid:!1,error:s("settings.mcpServerForm.missingTransportInfo")}}catch(a){return{valid:!1,error:s("settings.mcpServerForm.invalidJson",{message:a instanceof Error?a.message:s("settings.mcpServerForm.unknownError")})}}},di=({open:e,mode:s,initialConfig:a,confirmLoading:n=!1,onCancel:r,onSubmit:o})=>{const{t:l}=ae(),[u]=y.useForm(),[g,m]=i.useState("form"),[c,b]=i.useState(""),[p,S]=i.useState(null),v=i.useMemo(()=>ka(a),[a]),x=y.useWatch("transportType",u)??"stdio";i.useEffect(()=>{e&&(u.setFieldsValue(v),b(Ca(a)),S(null),m("form"))},[u,v,a,e]);const R=()=>{u.resetFields(),b(""),S(null),r()},P=async()=>{if(g==="json"){const h=Vs(c,l);if(!h.valid){S(h.error);return}S(null);try{await o(h.config),b("")}catch(k){console.error("MCP server JSON submission error:",k)}return}try{const h=await u.validateFields(),k=wa(h,s,a);await o(k),u.resetFields()}catch(h){console.error("MCP server form submission error:",h)}},C=h=>{b(h),p&&Vs(h,l).valid&&S(null)},I=h=>{if(h==="json")try{const k=u.getFieldsValue(),V=wa(k,s,a);b(JSON.stringify(V,null,2))}catch{b(Ca(a))}else{const k=Vs(c,l);k.valid&&u.setFieldsValue(ka(k.config))}m(h),S(null)};return t.jsxs(Qe,{title:l(s==="edit"?"settings.mcpServerForm.editTitle":"settings.mcpServerForm.addTitle"),open:e,onCancel:R,onOk:()=>{P()},okText:l("settings.mcpServerForm.save"),destroyOnClose:!0,forceRender:!0,confirmLoading:n,width:720,children:[t.jsx("div",{style:{marginBottom:16},children:t.jsxs(Ft.Group,{value:g,onChange:h=>I(h.target.value),optionType:"button",buttonStyle:"solid",children:[t.jsxs(Ft.Button,{value:"form",children:[t.jsx(qn,{})," ",l("settings.mcpServerForm.modeForm")]}),t.jsxs(Ft.Button,{value:"json",children:[t.jsx(Hn,{})," ",l("settings.mcpServerForm.modeJson")]})]})}),g==="json"&&p&&t.jsx(qe,{type:"error",message:l("settings.mcpServerForm.jsonError"),description:p,showIcon:!0,style:{marginBottom:16},closable:!0,onClose:()=>S(null)}),g==="json"?t.jsx(oi,{value:c,onChange:h=>C(h.target.value),rows:20,style:{fontFamily:"monospace",fontSize:13},placeholder:JSON.stringify(Cs("example-server"),null,2)}):t.jsxs(y,{layout:"vertical",form:u,preserve:!0,initialValues:v,children:[t.jsx(y.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(y.Item,{name:"name",label:l("settings.mcpServerForm.displayName"),children:t.jsx(H,{placeholder:"Filesystem MCP",autoComplete:"off"})}),t.jsx(y.Item,{name:"enabled",label:l("settings.mcpServerForm.enabled"),valuePropName:"checked",extra:l("settings.mcpServerForm.enabledHelp"),children:t.jsx(fe,{})}),t.jsx(y.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"}]})}),x==="stdio"?t.jsxs(t.Fragment,{children:[t.jsx(y.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(y.Item,{name:"args",label:l("settings.mcpServerForm.arguments"),children:t.jsx(te,{mode:"tags",tokenSeparators:[","],placeholder:l("settings.mcpServerForm.argumentsPlaceholder"),open:!1})}),t.jsx(y.List,{name:"envEntries",children:(h,{add:k,remove:V})=>t.jsxs(L,{direction:"vertical",style:{width:"100%"},children:[t.jsxs(L,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[t.jsx(Sa,{strong:!0,children:l("settings.mcpServerForm.envVars")}),t.jsx(z,{icon:t.jsx(dt,{}),onClick:()=>k({key:"",value:""}),type:"dashed",children:l("settings.mcpServerForm.addEnv")})]}),h.map(F=>t.jsxs(L,{align:"baseline",style:{display:"flex"},children:[t.jsx(y.Item,{...F,name:[F.name,"key"],rules:[{required:!0,message:l("settings.mcpServerForm.keyRequired")}],children:t.jsx(H,{placeholder:"MCP_ROOT",autoComplete:"off"})}),t.jsx(y.Item,{...F,name:[F.name,"value"],children:t.jsx(H,{placeholder:"/Users/me/workspace",autoComplete:"off"})}),t.jsx(z,{danger:!0,type:"text",icon:t.jsx(ya,{}),onClick:()=>V(F.name),"aria-label":l("settings.mcpServerForm.removeEnv","Remove environment variable")})]},F.key))]})})]}):t.jsxs(t.Fragment,{children:[t.jsx(y.Item,{name:"url",label:l("settings.mcpServerForm.sseUrl"),rules:[{required:!0,message:l("settings.mcpServerForm.sseUrlRequired")},{validator:async(h,k)=>{if(k)try{new URL(k)}catch{throw new Error(l("settings.mcpServerForm.validUrlRequired"))}}}],children:t.jsx(H,{placeholder:"http://localhost:4000/sse",autoComplete:"off"})}),t.jsx(y.List,{name:"headerEntries",children:(h,{add:k,remove:V})=>t.jsxs(L,{direction:"vertical",style:{width:"100%"},children:[t.jsxs(L,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[t.jsx(Sa,{strong:!0,children:l("settings.mcpServerForm.headers")}),t.jsx(z,{icon:t.jsx(dt,{}),onClick:()=>k({name:"",value:""}),type:"dashed",children:l("settings.mcpServerForm.addHeader")})]}),h.map(F=>t.jsxs(L,{align:"baseline",style:{display:"flex"},children:[t.jsx(y.Item,{...F,name:[F.name,"name"],rules:[{required:!0,message:l("settings.mcpServerForm.headerNameRequired")}],children:t.jsx(H,{placeholder:"Authorization",autoComplete:"off"})}),t.jsx(y.Item,{...F,name:[F.name,"value"],children:t.jsx(H,{placeholder:"Bearer token",autoComplete:"off"})}),t.jsx(z,{danger:!0,type:"text",icon:t.jsx(ya,{}),onClick:()=>V(F.name),"aria-label":l("settings.mcpServerForm.removeHeader","Remove header")})]},F.key))]})})]})]})]})},js=e=>!!e&&typeof e=="object"&&!Array.isArray(e),_t=(e,s)=>{const a=e[s];return typeof a=="string"?a:void 0},Ma=(e,s)=>{const a=e[s];return typeof a=="boolean"?a:void 0},ui=(e,s)=>{const a=e[s];return Array.isArray(a)?a:void 0},es=e=>{if(!js(e))return"any";const s=e.type;if(typeof s=="string"){if(s==="array"){const o=e.items;return`array<${es(o)}>`}return s==="object"?"object":s}if(Array.isArray(s)){const o=s.filter(l=>typeof l=="string").map(l=>l==="array"?"array<any>":l);return o.length>0?o.join(" | "):"any"}const a=Array.isArray(e.oneOf)?e.oneOf:null;if(a)return a.map(es).join(" | ")||"any";const n=Array.isArray(e.anyOf)?e.anyOf:null;if(n)return n.map(es).join(" | ")||"any";const r=Array.isArray(e.allOf)?e.allOf:null;return r&&r.map(es).join(" & ")||"any"},gi=e=>{if(!js(e))return null;const s=e.properties;if(!js(s))return{schemaUri:_t(e,"$schema"),title:_t(e,"title"),description:_t(e,"description"),additionalProperties:Ma(e,"additionalProperties"),fields:[]};const a=new Set((ui(e,"required")??[]).filter(r=>typeof r=="string").map(r=>r)),n=Object.entries(s).map(([r,o])=>{const l=js(o)?o:void 0;return{name:r,type:es(o),required:a.has(r),description:l?_t(l,"description"):void 0,defaultValue:l?l.default:void 0,enumValues:l&&Array.isArray(l.enum)?l.enum:void 0}});return n.sort((r,o)=>r.required!==o.required?r.required?-1:1:r.name.localeCompare(o.name)),{schemaUri:_t(e,"$schema"),title:_t(e,"title"),description:_t(e,"description"),additionalProperties:Ma(e,"additionalProperties"),fields:n}},{Text:et}=ue,mi=e=>e===void 0?"":e===null?"null":typeof e=="string"?e:Ya(e,0),pi=({schema:e})=>{const{token:s}=Te.useToken(),{t:a}=ae(),n=i.useMemo(()=>gi(e),[e]);if(!n)return t.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:Ya(e,2)});const r=[{title:a("components.jsonSchema.field"),dataIndex:"name",key:"name",width:180,render:l=>t.jsx(et,{code:!0,children:l})},{title:a("components.jsonSchema.type"),dataIndex:"type",key:"type",width:140,render:l=>t.jsx(et,{children:l})},{title:a("components.jsonSchema.required"),dataIndex:"required",key:"required",width:110,render:l=>l?t.jsx(et,{strong:!0,style:{color:s.colorError},children:a("components.jsonSchema.yes")}):t.jsx(et,{type:"secondary",children:a("components.jsonSchema.no")})},{title:a("components.jsonSchema.default"),dataIndex:"defaultValue",key:"default",width:160,render:l=>l===void 0?t.jsx(et,{type:"secondary",children:"-"}):t.jsx(et,{children:mi(l)})},{title:a("components.jsonSchema.description"),dataIndex:"description",key:"description",render:l=>l?t.jsx(et,{style:{whiteSpace:"pre-wrap"},children:l}):t.jsx(et,{type:"secondary",children:"-"})}],o=(n.fields??[]).map(l=>({...l,key:l.name}));return t.jsxs("div",{style:{width:"100%"},children:[t.jsx(ze,{size:"small",column:1,items:[n.schemaUri?{key:"schema",label:"$schema",children:t.jsx(et,{code:!0,children:n.schemaUri})}:null,typeof n.additionalProperties=="boolean"?{key:"additionalProperties",label:"additionalProperties",children:t.jsx(et,{children:n.additionalProperties?"true":"false"})}:null].filter(Boolean)}),t.jsx(at,{size:"small",pagination:!1,columns:r,dataSource:o,locale:{emptyText:a("components.jsonSchema.noProperties")},style:{marginTop:s.marginSM}})]})},{Text:Kt}=ue,hi=(e,s)=>`mcp__${e}__${s}`,fi=({server:e,tools:s,loading:a=!1})=>{const{t:n}=ae();return t.jsx(N,{title:n("settings.mcpToolList.title"),size:"small",children:e?t.jsx(Xe,{loading:a,dataSource:s,locale:{emptyText:n("settings.mcpToolList.empty")},renderItem:r=>{const o=hi(r.server_id,r.original_name);return t.jsx(Xe.Item,{children:t.jsxs(L,{direction:"vertical",size:2,style:{width:"100%"},children:[t.jsx(Kt,{strong:!0,children:r.original_name}),t.jsx(Kt,{type:"secondary",children:r.description||n("settings.mcpToolList.noDescription")}),t.jsx(Kt,{code:!0,children:r.alias}),t.jsxs(Kt,{type:"secondary",children:[n("settings.mcpToolList.aliasMapping"),": ",t.jsx(Kt,{code:!0,children:o})]}),r.parameters!==void 0&&t.jsx(ks,{size:"small",items:[{key:"schema",label:n("settings.mcpToolList.parametersSchema"),children:t.jsx(pi,{schema:r.parameters})}]})]})})}}):t.jsx(He,{image:He.PRESENTED_IMAGE_SIMPLE,description:n("settings.mcpToolList.selectServerHint")})})},{Text:Wt}=ue,{useToken:yi}=Te,{TextArea:xi}=H,Ea={[W.Connecting]:"processing",[W.Ready]:"success",[W.Degraded]:"warning",[W.Stopped]:"default",[W.Error]:"error"},bi=()=>({[W.Connecting]:0,[W.Ready]:0,[W.Degraded]:0,[W.Stopped]:0,[W.Error]:0}),St=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,vi=e=>{var a,n,r;const s={};for(const o of e){const l=(a=o.id)==null?void 0:a.trim();if(!l)continue;const g=!(o.enabled??o.config.enabled),m=o.config.transport;if(m.type==="sse"){const b={};for(const S of m.headers??[]){const v=(n=S.name)==null?void 0:n.trim();v&&(b[v]=S.value??"")}const p={url:m.url};g&&(p.disabled=!0),Object.keys(b).length&&(p.headers=b),s[l]=p;continue}const c={command:m.command};g&&(c.disabled=!0),(r=m.args)!=null&&r.length&&(c.args=m.args),m.cwd&&(c.cwd=m.cwd),m.env&&Object.keys(m.env).length&&(c.env=m.env),s[l]=c}return{mcpServers:s}},ji=()=>{const{t:e}=ae(),{token:s}=yi(),[a,n]=zt.useMessage(),{servers:r,selectedServerId:o,selectedServerTools:l,isLoadingServers:u,isMutatingConfig:g,isRefreshingAll:m,isSelectedServerToolsLoading:c,error:b,setSelectedServerId:p,addServer:S,updateServer:v,deleteServer:x,connectServer:R,disconnectServer:P,refreshServerTools:C,refreshAll:I,isServerActionLoading:h}=si(),k=i.useMemo(()=>({[W.Connecting]:e("settings.mcpTab.status.connecting"),[W.Ready]:e("settings.mcpTab.status.ready"),[W.Degraded]:e("settings.mcpTab.status.degraded"),[W.Stopped]:e("settings.mcpTab.status.stopped"),[W.Error]:e("settings.mcpTab.status.error")}),[e]),V=i.useMemo(()=>({[W.Connecting]:e("settings.mcpTab.statusHelp.connecting"),[W.Ready]:e("settings.mcpTab.statusHelp.ready"),[W.Degraded]:e("settings.mcpTab.statusHelp.degraded"),[W.Stopped]:e("settings.mcpTab.statusHelp.stopped"),[W.Error]:e("settings.mcpTab.statusHelp.error")}),[e]),[F,U]=i.useState(!1),[ee,$]=i.useState("create"),[j,T]=i.useState(null),[D,A]=i.useState(!1),[Q,O]=i.useState("merge"),[Y,G]=i.useState(""),[ne,ie]=i.useState(null),[be,d]=i.useState(!1),E=i.useMemo(()=>o?r.find(f=>f.id===o)??null:null,[o,r]),M=i.useMemo(()=>{const f=bi();let ce=0;return r.forEach(ve=>{var _e,Ve;const Ne=((_e=ve.runtime)==null?void 0:_e.status)??W.Stopped;f[Ne]+=1,ce+=((Ve=ve.runtime)==null?void 0:Ve.tool_count)??0}),{byStatus:f,totalServers:r.length,totalTools:ce}},[r]),K={background:s.colorFillSecondary,borderColor:s.colorBorderSecondary,color:s.colorTextSecondary},se=async f=>{try{await x(f.id),a.success(e("settings.mcpTab.serverDeleted"))}catch(ce){a.error(St(ce,e("settings.mcpTab.deleteServerFailed")))}},pe=async f=>{try{await R(f.id),a.success(e("settings.mcpTab.connectedTo",{name:f.name||f.id}))}catch(ce){a.error(St(ce,e("settings.mcpTab.connectServerFailed")))}},ye=async f=>{try{await P(f.id),a.success(e("settings.mcpTab.disconnected",{name:f.name||f.id}))}catch(ce){a.error(St(ce,e("settings.mcpTab.disconnectServerFailed")))}},je=async f=>{try{await C(f.id),a.success(e("settings.mcpTab.toolsRefreshedFor",{name:f.name||f.id}))}catch(ce){a.error(St(ce,e("settings.mcpTab.refreshToolsFailed")))}},B=async()=>{try{await I(),a.success(e("settings.mcpTab.statusRefreshed"))}catch(f){a.error(St(f,e("settings.mcpTab.refreshStatusFailed")))}},we=()=>{T(null),$("create"),U(!0)},We=f=>{T(f),$("edit"),U(!0)},Ie=async f=>{try{if(ee==="edit"){if(!j){a.error(e("settings.mcpTab.noServerForEditing"));return}await v(j.id,f),a.success(e("settings.mcpTab.savedServer",{name:j.name||j.id}))}else await S(f),a.success(e("settings.mcpTab.addedServer",{name:f.name||f.id}));U(!1),T(null)}catch(ce){a.error(St(ce,e("settings.mcpTab.saveServerFailed")))}},Oe=()=>{A(!0),ie(null),O("merge"),G("")},Pe=async()=>{const f=vi(r),ce=JSON.stringify(f,null,2);try{await aa(ce),a.success(e("settings.mcpTab.copiedConfig"))}catch{A(!0),ie(null),O("merge"),G(ce),a.warning(e("settings.mcpTab.clipboardUnavailable"))}},Ge=async()=>{var Ne;ie(null);let f;try{f=JSON.parse(Y)}catch(_e){ie(`${e("settings.mcpTab.invalidJsonPrefix")}: ${_e instanceof Error?_e.message:e("settings.mcpTab.unknownError")}`);return}if(!f||typeof f!="object"){ie(e("settings.mcpTab.jsonMustBeObject"));return}const ve=f.mcpServers;if(!ve||typeof ve!="object"){ie(e("settings.mcpTab.missingMcpServers"));return}d(!0);try{const _e=await sn.importServers({mcpServers:ve,mode:Q}),Ve=((Ne=_e.start_errors)==null?void 0:Ne.length)??0;a.success(e("settings.mcpTab.importSummary",{count:_e.server_ids.length,added:_e.added,updated:_e.updated,removed:_e.removed,failed:Ve})),Ve&&a.warning(e("settings.mcpTab.importStartFailures")),A(!1),G(""),await B()}catch(_e){ie(St(_e,e("settings.mcpTab.importFailed")))}finally{d(!1)}};return t.jsxs(L,{direction:"vertical",size:s.marginMD,style:{width:"100%"},children:[n,b?t.jsx(qe,{type:"error",showIcon:!0,message:b}):null,t.jsx(N,{size:"small",title:e("settings.mcpTab.overviewTitle"),children:t.jsxs(L,{direction:"vertical",size:s.marginXS,style:{width:"100%"},children:[t.jsx(Wt,{type:"secondary",children:e("settings.mcpTab.overviewDescription")}),t.jsxs(L,{wrap:!0,children:[t.jsx(re,{style:K,children:e("settings.mcpTab.totalServers",{count:M.totalServers})}),t.jsx(re,{style:K,children:e("settings.mcpTab.totalTools",{count:M.totalTools})}),Object.values(W).map(f=>t.jsx(ke,{title:V[f],children:t.jsxs(re,{color:f===W.Stopped?void 0:Ea[f],style:{cursor:"help",...f===W.Stopped?K:void 0},children:[k[f],": ",M.byStatus[f]]})},f))]}),t.jsx(Wt,{type:"secondary",children:e("settings.mcpTab.statusGuideTitle")}),t.jsx(L,{direction:"vertical",size:2,style:{width:"100%"},children:Object.values(W).map(f=>t.jsxs(Wt,{type:"secondary",children:[t.jsx(re,{color:f===W.Stopped?void 0:Ea[f],style:{marginInlineEnd:8,...f===W.Stopped?K:void 0},children:k[f]}),V[f]]},`guide-${f}`))})]})}),t.jsx(N,{size:"small",title:e("settings.mcpTab.serversTitle"),extra:t.jsxs(L,{children:[t.jsx(z,{type:"primary",onClick:we,children:e("settings.mcpTab.addServer")}),t.jsx(z,{icon:t.jsx(Lt,{}),loading:m,onClick:()=>{B()},children:e("settings.mcpTab.refreshAll")}),t.jsx(z,{icon:t.jsx(Za,{}),onClick:()=>void Pe(),children:e("settings.mcpTab.export")}),t.jsx(z,{icon:t.jsx(Un,{}),onClick:Oe,children:e("settings.mcpTab.import")})]}),children:t.jsx(ii,{servers:r,loading:u,selectedServerId:o,onSelectServer:p,onEditServer:We,onDeleteServer:se,onConnectServer:pe,onDisconnectServer:ye,onRefreshTools:je,isServerActionLoading:h})}),t.jsx(fi,{server:E,tools:l,loading:c}),t.jsx(di,{open:F,mode:ee,initialConfig:(j==null?void 0:j.config)??null,confirmLoading:g,onCancel:()=>{g||(U(!1),T(null))},onSubmit:f=>void Ie(f)}),t.jsx(Qe,{open:D,title:e("settings.mcpTab.importModalTitle"),okText:e("settings.mcpTab.import"),onOk:()=>void Ge(),okButtonProps:{loading:be},onCancel:()=>{be||(A(!1),ie(null))},width:800,destroyOnClose:!1,children:t.jsxs(L,{direction:"vertical",style:{width:"100%"},size:"middle",children:[t.jsxs(Wt,{type:"secondary",children:[e("settings.mcpTab.importHint"),t.jsx("br",{}),t.jsx(Wt,{code:!0,children:'{ "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "..."] } } }'})]}),t.jsxs(Ft.Group,{value:Q,onChange:f=>O(f.target.value),optionType:"button",buttonStyle:"solid",children:[t.jsx(Ft.Button,{value:"merge",children:e("settings.mcpTab.importModeMerge")}),t.jsx(Ft.Button,{value:"replace",children:e("settings.mcpTab.importModeReplace")})]}),Q==="replace"?t.jsx(qe,{type:"warning",showIcon:!0,message:e("settings.mcpTab.replaceWarning")}):null,ne?t.jsx(qe,{type:"error",showIcon:!0,message:ne}):null,t.jsx(xi,{value:Y,onChange:f=>G(f.target.value),rows:14,placeholder:'{"mcpServers": { "filesystem": { "command": "...", "args": [], "env": {} } }}',spellCheck:!1})]})})]})},an=1,Ti=365,nn=e=>Number.isFinite(e)?Math.min(Ti,Math.max(an,Math.floor(e??30))):30,$s=e=>{if(!e)return null;const s=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!s)return null;const a=Number(s[1]),n=Number(s[2]),r=Number(s[3]),o=new Date(Date.UTC(a,n-1,r));return o.getUTCFullYear()!==a||o.getUTCMonth()!==n-1||o.getUTCDate()!==r?null:o},Gt=e=>e.toISOString().slice(0,10),_i=(e,s)=>{const a=new Date(e.getTime());return a.setUTCDate(a.getUTCDate()+s),a},Si=(e,s)=>{const a=s.getTime()-e.getTime(),n=Math.floor(a/864e5)+1;return nn(n)},ia=(e,s=new Date)=>{const a=nn(e.days),n=Gt(s),r=$s(e.endDate)??$s(n);if(!r)return{startDate:n,endDate:n,days:an};const o=$s(e.startDate);if(o){const u=r<o?o:r;return{startDate:Gt(o),endDate:Gt(u),days:Si(o,u)}}const l=_i(r,-(a-1));return{startDate:Gt(l),endDate:Gt(r),days:a}},ki=15e3,wi=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,Ci=(e={})=>{const{filters:s,autoRefreshMs:a=ki}=e,n=i.useMemo(()=>({startDate:s==null?void 0:s.startDate,endDate:s==null?void 0:s.endDate,days:(s==null?void 0:s.days)??30,endpoint:s==null?void 0:s.endpoint,model:s==null?void 0:s.model,limit:(s==null?void 0:s.limit)??100}),[s==null?void 0:s.startDate,s==null?void 0:s.endDate,s==null?void 0:s.days,s==null?void 0:s.endpoint,s==null?void 0:s.model,s==null?void 0:s.limit]),r=i.useMemo(()=>ia({startDate:n.startDate,endDate:n.endDate,days:n.days}),[n.days,n.endDate,n.startDate]),[o,l]=i.useState(null),[u,g]=i.useState([]),[m,c]=i.useState([]),[b,p]=i.useState(!1),[S,v]=i.useState(!1),[x,R]=i.useState(null),P=i.useCallback(async I=>{I?p(!0):v(!0);try{const h={startDate:r.startDate,endDate:r.endDate,endpoint:n.endpoint,model:n.model,limit:n.limit},[k,V,F]=await Promise.all([ts.getForwardSummary(h),ts.getForwardByEndpoint(h),ts.getForwardRequests(h)]);l(k),g(V),c(F),R(null)}catch(h){R(wi(h,"Failed to load forward metrics"))}finally{I?p(!1):v(!1)}},[n.endpoint,n.model,n.limit,r.endDate,r.startDate]),C=i.useCallback(async()=>{await P(!1)},[P]);return i.useEffect(()=>{P(!0)},[P]),i.useEffect(()=>{if(a<=0)return;const I=window.setInterval(()=>{P(!1)},a);return()=>{window.clearInterval(I)}},[a,P]),{summary:o,endpointMetrics:u,requests:m,isLoading:b,isRefreshing:S,error:x,refresh:C}},Mi=15e3,Pa=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,Ei=(e={})=>{const{filters:s,autoRefreshMs:a=Mi,service:n=ts}=e,r=i.useMemo(()=>({startDate:s==null?void 0:s.startDate,endDate:s==null?void 0:s.endDate,model:s==null?void 0:s.model,days:(s==null?void 0:s.days)??30,granularity:(s==null?void 0:s.granularity)??"daily",sessionLimit:(s==null?void 0:s.sessionLimit)??200}),[s==null?void 0:s.startDate,s==null?void 0:s.endDate,s==null?void 0:s.model,s==null?void 0:s.days,s==null?void 0:s.granularity,s==null?void 0:s.sessionLimit]),o=i.useMemo(()=>ia({startDate:r.startDate,endDate:r.endDate,days:r.days}),[r.days,r.endDate,r.startDate]),[l,u]=i.useState(null),[g,m]=i.useState([]),[c,b]=i.useState([]),[p,S]=i.useState([]),[v,x]=i.useState(null),[R,P]=i.useState([]),[C,I]=i.useState(null),[h,k]=i.useState(!1),[V,F]=i.useState(!1),[U,ee]=i.useState(!1),[$,j]=i.useState(null),T=i.useCallback(async O=>{O?F(!0):ee(!0);try{const Y=n.getMemorySummary?n.getMemorySummary().catch(()=>null):Promise.resolve(null),G=n.getMemoryTimeline?n.getMemoryTimeline({days:o.days,endDate:o.endDate,granularity:r.granularity}).catch(()=>[]):Promise.resolve([]),[ne,ie,be,d,E,M]=await Promise.all([n.getSummary({startDate:o.startDate,endDate:o.endDate}),n.getByModel({startDate:o.startDate,endDate:o.endDate}),n.getSessions({startDate:o.startDate,endDate:o.endDate,model:r.model,limit:r.sessionLimit}),n.getDaily({days:o.days,endDate:o.endDate,granularity:r.granularity}),Y,G]);u(ne),m(ie),b(be),S(d),x(E),P(M),j(null)}catch(Y){j(Pa(Y,"Failed to load metrics"))}finally{O?F(!1):ee(!1)}},[r.granularity,r.model,r.sessionLimit,o.days,o.endDate,o.startDate,n]),D=i.useCallback(async()=>{await T(!1)},[T]),A=i.useCallback(async O=>{k(!0);try{const Y=await n.getSessionDetail(O);I(Y)}catch(Y){j(Pa(Y,"Failed to load session detail"))}finally{k(!1)}},[n]),Q=i.useCallback(()=>{I(null)},[]);return i.useEffect(()=>{T(!0)},[T]),i.useEffect(()=>{if(a<=0)return;const O=window.setInterval(()=>{T(!1)},a);return()=>{window.clearInterval(O)}},[a,T]),{summary:l,modelMetrics:g,sessions:c,timeline:p,memorySummary:v,memoryTimeline:R,sessionDetail:C,isLoading:V,isRefreshing:U,isSessionDetailLoading:h,error:$,refresh:D,loadSessionDetail:A,clearSessionDetail:Q}},Pi=15e3,Di=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,Ii=(e={})=>{const{filters:s,autoRefreshMs:a=Pi}=e,n=i.useMemo(()=>({startDate:s==null?void 0:s.startDate,endDate:s==null?void 0:s.endDate,days:(s==null?void 0:s.days)??30,model:s==null?void 0:s.model}),[s==null?void 0:s.days,s==null?void 0:s.endDate,s==null?void 0:s.model,s==null?void 0:s.startDate]),r=i.useMemo(()=>ia({startDate:n.startDate,endDate:n.endDate,days:n.days}),[n.days,n.endDate,n.startDate]),[o,l]=i.useState(null),[u,g]=i.useState(!1),[m,c]=i.useState(!1),[b,p]=i.useState(null),S=i.useCallback(async x=>{x?g(!0):c(!0);try{const R=await ts.getUsageBreakdown({startDate:r.startDate,endDate:r.endDate,model:n.model});l(R),p(null)}catch(R){p(Di(R,"Failed to load usage breakdown"))}finally{x?g(!1):c(!1)}},[n.model,r.endDate,r.startDate]),v=i.useCallback(async()=>{await S(!1)},[S]);return i.useEffect(()=>{S(!0)},[S]),i.useEffect(()=>{if(a<=0)return;const x=window.setInterval(()=>{S(!1)},a);return()=>{window.clearInterval(x)}},[a,S]),{data:o,isLoading:u,isRefreshing:m,error:b,refresh:v}},{useToken:Fi}=Te,Ai=({data:e,loading:s})=>{const{t:a}=ae(),{token:n}=Fi();if(s)return t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.charts.endpointDistribution"),children:t.jsx("div",{style:{width:"100%",height:240},children:t.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100%",color:n.colorTextSecondary},children:a("settings.common.loading")})})});if(e.length===0)return t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.charts.endpointDistribution"),children:t.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:240,color:n.colorTextSecondary},children:a("settings.charts.noForwardMetrics")})});const r=e.map(o=>({endpoint:o.endpoint.split(".").pop()||o.endpoint,requests:o.requests,successful:o.successful,failed:o.failed}));return t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.charts.endpointDistribution"),children:t.jsx("div",{style:{width:"100%",height:240},children:t.jsx(Ot,{children:t.jsxs(na,{data:r,children:[t.jsx(os,{strokeDasharray:"3 3"}),t.jsx(ls,{dataKey:"endpoint"}),t.jsx(cs,{}),t.jsx(Nt,{formatter:(o,l)=>[`${o}`,l.charAt(0).toUpperCase()+l.slice(1)]}),t.jsx(ra,{}),t.jsx(_s,{dataKey:"successful",fill:"var(--lotus-chart-secondary)",name:a("settings.common.successful"),fillOpacity:.9,radius:[4,4,0,0]}),t.jsx(_s,{dataKey:"failed",fill:"var(--lotus-chart-danger)",name:a("settings.common.failed"),fillOpacity:.9,radius:[4,4,0,0]})]})})})})},Bs=e=>e.replace(/\.0$/,""),rn=e=>e.toLocaleString(),on=e=>Number.isFinite(e)?e.toLocaleString(void 0,{maximumFractionDigits:20}):String(e),oa=e=>{if(!Number.isFinite(e))return String(e);const s=Math.abs(e);if(s>=1e9){const a=s>=1e10?0:1;return`${Bs((e/1e9).toFixed(a))}B`}if(s>=1e6){const a=s>=1e7?0:1;return`${Bs((e/1e6).toFixed(a))}M`}if(s>=1e3){const a=s>=1e4?0:1;return`${Bs((e/1e3).toFixed(a))}K`}return rn(e)},Ri=e=>Number.isFinite(e)&&Math.abs(e)>=1e3,ln=e=>on(e),rs=e=>{if(!Number.isFinite(e))return String(e);const s=oa(e);return Ri(e)?t.jsx(ke,{title:t.jsx("div",{children:on(e)}),children:t.jsx("span",{children:s})}):s},lt=e=>{const s=Number(e??0);return Number.isFinite(s)?rs(s):e==null?"-":String(e)},{useToken:zi}=Te,Li=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),a=Math.floor(s/60),n=s%60;if(a>=60){const r=Math.floor(a/60),o=a%60;return`${r}h ${o}m`}return a>0?`${a}m ${n}s`:`${n}s`},Da=({summary:e,loading:s})=>{const{t:a}=ae(),{token:n}=zi();if(s)return t.jsx(gt,{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(Je,{gutter:[n.marginSM,n.marginSM],children:[t.jsx(me,{xs:24,sm:12,xl:6,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:a("settings.forwardMetricsCards.totalForwardRequests"),value:(e==null?void 0:e.total_requests)??0,precision:0,formatter:lt,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),t.jsx(me,{xs:24,sm:12,xl:6,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:a("settings.forwardMetricsCards.successRate"),value:r,suffix:"%",valueStyle:{color:Number(r)>=95?"var(--lotus-chart-secondary)":Number(r)>=80?"var(--lotus-chart-accent)":"var(--lotus-chart-danger)"}})})}),t.jsx(me,{xs:24,sm:12,xl:6,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:a("settings.forwardMetricsCards.forwardTokens"),value:(e==null?void 0:e.total_tokens.total_tokens)??0,precision:0,formatter:lt,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})}),t.jsx(me,{xs:24,sm:12,xl:6,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:a("settings.forwardMetricsCards.avgResponseTime"),value:Li(e==null?void 0:e.avg_duration_ms),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:kt}=ue,Oi=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),a=Math.floor(s/60),n=s%60;return a>0?`${a}m ${n}s`:`${n}s`},Ni=e=>new Date(e).toLocaleString(),Vi=({requests:e,loading:s})=>{const{t:a}=ae(),n=[{title:a("settings.metricsTable.forward.columns.id"),dataIndex:"forward_id",key:"forward_id",width:120,render:r=>t.jsxs(kt,{style:{fontSize:12},copyable:!0,children:[r.slice(0,8),"..."]})},{title:a("settings.metricsTable.forward.columns.endpoint"),dataIndex:"endpoint",key:"endpoint",width:150,render:r=>t.jsx(re,{color:"processing",children:r.split(".").pop()||r})},{title:a("settings.metricsTable.forward.columns.model"),dataIndex:"model",key:"model",width:120},{title:a("settings.metricsTable.forward.columns.type"),dataIndex:"is_stream",key:"is_stream",width:80,render:r=>t.jsx(re,{color:r?"purple":"processing",children:a(r?"settings.metricsTable.forward.typeStream":"settings.metricsTable.forward.typeSync")})},{title:a("settings.metricsTable.forward.columns.status"),key:"status",width:100,render:(r,o)=>{const l=o.status==="success"?"success":o.status==="error"?"error":"default";return t.jsx(Kn,{status:l,text:o.status_code?t.jsxs("span",{children:[o.status,t.jsxs(kt,{type:"secondary",style:{marginLeft:4},children:["(",o.status_code,")"]})]}):o.status||"-"})}},{title:a("settings.metricsTable.forward.columns.tokens"),key:"tokens",width:100,render:(r,o)=>o.token_usage?t.jsx(kt,{children:rs(o.token_usage.total_tokens)}):t.jsx(kt,{type:"secondary",children:"-"})},{title:a("settings.metricsTable.forward.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",width:100,render:r=>Oi(r)},{title:a("settings.metricsTable.forward.columns.started"),dataIndex:"started_at",key:"started_at",width:160,render:r=>t.jsx(kt,{type:"secondary",style:{fontSize:12},children:Ni(r)})},{title:a("settings.metricsTable.forward.columns.error"),dataIndex:"error",key:"error",width:200,render:r=>r?t.jsx(kt,{type:"danger",ellipsis:!0,style:{maxWidth:180},children:r}):t.jsx(kt,{type:"secondary",children:"-"})}];return t.jsx(at,{rowKey:"forward_id",className:"lotus-metric-table",columns:n,dataSource:e,loading:s,size:"small",pagination:{pageSize:10,showSizeChanger:!0,showTotal:r=>a("settings.metricsTable.forward.totalRequests",{total:r}),pageSizeOptions:["10","20","50","100"]},scroll:{x:1200},locale:{emptyText:a("settings.metricsTable.forward.empty")}})},{useToken:$i}=Te,Bi=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString()},Ia=({summary:e,loading:s})=>{const{t:a}=ae(),{token:n}=$i();return s?t.jsx(gt,{active:!0,paragraph:{rows:1}}):t.jsxs(Je,{gutter:[n.marginSM,n.marginSM],children:[t.jsx(me,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:a("settings.unifiedMetricsCards.totalMemories"),value:(e==null?void 0:e.total_memories)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:a("settings.unifiedMetricsCards.staleCandidates"),value:(e==null?void 0:e.stale_candidate_count)??0,precision:0,valueStyle:{color:((e==null?void 0:e.stale_candidate_count)??0)>0?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:a("settings.unifiedMetricsCards.memoryProjects"),value:(e==null?void 0:e.project_count)??0,precision:0,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:a("settings.unifiedMetricsCards.lastReindex"),value:Bi(e==null?void 0:e.last_reindex_at),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:qi}=ue,Hi=({data:e,loading:s})=>{const{t:a}=ae();return s?t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.charts.memoryTrendTitle"),children:t.jsx(gt,{active:!0,paragraph:{rows:5}})}):t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.charts.memoryTrendTitle"),children:e.length===0?t.jsx(He,{image:He.PRESENTED_IMAGE_SIMPLE,description:a("settings.charts.noMemoryTrend")}):t.jsxs(t.Fragment,{children:[t.jsx(qi,{type:"secondary",children:a("settings.charts.memoryTrendDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(Ot,{children:t.jsxs(en,{data:e,children:[t.jsx(os,{strokeDasharray:"3 3"}),t.jsx(ls,{dataKey:"label",minTickGap:24}),t.jsx(cs,{allowDecimals:!1}),t.jsx(Nt,{}),t.jsx(ra,{}),t.jsx(At,{type:"monotone",dataKey:"total_memories",name:a("settings.charts.totalMemories"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),t.jsx(At,{type:"monotone",dataKey:"created_memories",name:a("settings.charts.createdMemories"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),t.jsx(At,{type:"monotone",dataKey:"updated_memories",name:a("settings.charts.updatedMemories"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{useToken:Ui}=Te,Ki=e=>{const s=Math.floor(e/1e3),a=Math.floor(s/60),n=s%60;return a>0?`${a}m ${n}s`:`${n}s`},Wi=e=>{const s=e.filter(n=>typeof n.duration_ms=="number"&&n.duration_ms>0);if(s.length===0)return 0;const a=s.reduce((n,r)=>n+(r.duration_ms??0),0);return Math.floor(a/s.length)},Fa=({summary:e,sessions:s,loading:a})=>{const{t:n}=ae(),{token:r}=Ui();if(a)return t.jsx(gt,{active:!0,paragraph:{rows:1}});const o=Wi(s);return t.jsxs(Je,{gutter:[r.marginSM,r.marginSM],children:[t.jsx(me,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:n("settings.metricsCards.syncMismatches",{defaultValue:"Sync Mismatches"}),value:(e==null?void 0:e.total_sync_mismatches)??0,precision:0,valueStyle:{color:((e==null?void 0:e.total_sync_mismatches)??0)>0?"var(--lotus-chart-danger)":"var(--lotus-chart-secondary)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:n("settings.metricsCards.totalSessions"),value:(e==null?void 0:e.total_sessions)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:n("settings.metricsCards.chatTokens"),value:(e==null?void 0:e.total_tokens.total_tokens)??0,precision:0,formatter:lt,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:n("settings.metricsCards.totalToolCalls"),value:(e==null?void 0:e.total_tool_calls)??0,precision:0,formatter:lt,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:n("settings.metricsCards.tokensSaved",{defaultValue:"Saved Tokens"}),value:(e==null?void 0:e.total_tokens_saved)??0,precision:0,formatter:lt,valueStyle:{color:"var(--lotus-chart-cyan)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:n("settings.metricsCards.toolContextSavedTokens",{defaultValue:"Tool Context Saved Tokens"}),value:(e==null?void 0:e.tool_context_tokens_saved)??0,precision:0,formatter:lt,valueStyle:{color:"var(--lotus-chart-accent)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:n("settings.metricsCards.compressionEvents",{defaultValue:"Compression Events"}),value:(e==null?void 0:e.total_compression_events)??0,precision:0,formatter:lt,valueStyle:{color:"var(--lotus-chart-secondary)"}})})}),t.jsx(me,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:n("settings.metricsCards.avgSessionDuration"),value:o>0?Ki(o):"-",valueStyle:{color:"var(--lotus-chart-accent)"}})})})]})},{Text:Gi}=ue,Aa=["var(--lotus-chart-primary)","var(--lotus-chart-secondary)","var(--lotus-chart-accent)","var(--lotus-chart-purple)","var(--lotus-chart-cyan)"],Ji=({data:e,loading:s})=>{const{t:a}=ae();if(s)return t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.charts.modelDistribution"),children:t.jsx(gt,{active:!0,paragraph:{rows:5}})});const n=e.map(r=>({name:r.model,value:r.tokens.total_tokens}));return t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.charts.modelDistribution"),children:n.length===0?t.jsx(He,{image:He.PRESENTED_IMAGE_SIMPLE,description:a("settings.charts.noModelMetrics")}):t.jsxs(t.Fragment,{children:[t.jsx(Gi,{type:"secondary",children:a("settings.charts.modelDistributionDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(Ot,{children:t.jsxs(ar,{children:[t.jsx(nr,{data:n,cx:"50%",cy:"50%",outerRadius:90,fill:"var(--lotus-chart-primary)",dataKey:"value",nameKey:"name",label:!0,children:n.map((r,o)=>t.jsx(rr,{fill:Aa[o%Aa.length]},`${r.name}-${o}`))}),t.jsx(Nt,{formatter:r=>ln(r)})]})})})]})})},Xi=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?"-":s.toLocaleString()},Yi=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),a=Math.floor(s/60),n=s%60;if(a>=60){const r=Math.floor(a/60),o=a%60;return`${r}h ${o}m`}return a>0?`${a}m ${n}s`:`${n}s`},Zi=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"}},Qi=(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}},eo=({sessions:e,loading:s,onSelectSession:a})=>{const{t:n}=ae(),r=[{title:n("settings.metricsTable.session.columns.session"),dataIndex:"session_id",key:"session_id",render:o=>t.jsx(ke,{title:o,children:t.jsxs("span",{children:[o.slice(0,8),"..."]})}),width:120},{title:n("settings.metricsTable.session.columns.model"),dataIndex:"model",key:"model",width:160},{title:n("settings.metricsTable.session.columns.status"),dataIndex:"status",key:"status",width:120,render:o=>t.jsx(re,{color:Zi(o),children:Qi(o,n)})},{title:n("settings.metricsTable.session.columns.started"),dataIndex:"started_at",key:"started_at",render:o=>Xi(o),width:200,sorter:(o,l)=>new Date(o.started_at).getTime()-new Date(l.started_at).getTime(),defaultSortOrder:"descend"},{title:n("settings.metricsTable.session.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",render:o=>Yi(o),width:120},{title:n("settings.metricsTable.session.columns.tokens"),key:"tokens",render:(o,l)=>rs(l.total_token_usage.total_tokens),width:120,sorter:(o,l)=>o.total_token_usage.total_tokens-l.total_token_usage.total_tokens},{title:n("settings.metricsTable.session.columns.toolCalls"),dataIndex:"tool_call_count",key:"tool_call_count",width:120,sorter:(o,l)=>o.tool_call_count-l.tool_call_count},{title:n("settings.metricsTable.session.columns.messages"),dataIndex:"message_count",key:"message_count",width:120,sorter:(o,l)=>o.message_count-l.message_count},{title:n("settings.metricsTable.session.columns.action"),key:"action",fixed:"right",width:120,render:(o,l)=>t.jsx(z,{type:"link",onClick:()=>{a(l.session_id)},children:n("settings.metricsTable.session.view")})}];return t.jsx(at,{rowKey:"session_id",size:"small",className:"lotus-metric-table",columns:r,loading:s,dataSource:e,pagination:{pageSize:10,showSizeChanger:!1},scroll:{x:1100}})},{Text:to}=ue,Ra={message_count:"Message Count",last_message_id:"Last Message",pending_question:"Pending Question"},so=e=>Ra[e]?Ra[e]:e.split("_").map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "),ao=({breakdown:e,loading:s})=>{const{t:a}=ae();if(s)return t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),children:t.jsx(gt,{active:!0,paragraph:{rows:5}})});const n=Object.entries(e??{}).map(([r,o])=>({reason:r,label:a(`settings.syncMismatchReasons.${r}`,{defaultValue:so(r)}),count:o})).sort((r,o)=>o.count-r.count);return t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),extra:t.jsx(to,{type:"secondary",children:a("settings.metricsDashboard.syncMismatchBreakdownSubtitle",{defaultValue:"Grouped by execute sync mismatch reason"})}),children:n.length===0?t.jsx(He,{image:He.PRESENTED_IMAGE_SIMPLE,description:a("settings.metricsDashboard.noSyncMismatchBreakdown",{defaultValue:"No sync mismatches recorded for the selected range"})}):t.jsx("div",{style:{width:"100%",minWidth:0,height:280,minHeight:280},children:t.jsx(Ot,{children:t.jsxs(na,{data:n,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[t.jsx(os,{strokeDasharray:"3 3"}),t.jsx(ls,{type:"number",allowDecimals:!1}),t.jsx(cs,{dataKey:"label",type:"category",width:110}),t.jsx(Nt,{formatter:r=>[r.toLocaleString(),a("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})],labelFormatter:r=>a("settings.metricsDashboard.syncMismatchReasonLabel",{defaultValue:"Reason: {{label}}",label:r})}),t.jsx(_s,{dataKey:"count",fill:"var(--lotus-chart-danger)",radius:[0,6,6,0],name:a("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})})]})})})})},{Text:no}=ue,ro=({data:e,loading:s})=>{const{t:a}=ae();return s?t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.charts.tokenUsageOverTime"),children:t.jsx(gt,{active:!0,paragraph:{rows:5}})}):t.jsx(N,{size:"small",className:"lotus-metric-card",title:a("settings.charts.tokenUsageOverTime"),children:e.length===0?t.jsx(He,{image:He.PRESENTED_IMAGE_SIMPLE,description:a("settings.charts.noTokenUsage")}):t.jsxs(t.Fragment,{children:[t.jsx(no,{type:"secondary",children:a("settings.charts.tokenUsageDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(Ot,{children:t.jsxs(en,{data:e,children:[t.jsx(os,{strokeDasharray:"3 3"}),t.jsx(ls,{dataKey:"label",minTickGap:24}),t.jsx(cs,{allowDecimals:!1,tickFormatter:oa}),t.jsx(Nt,{formatter:n=>ln(n)}),t.jsx(ra,{}),t.jsx(At,{type:"monotone",dataKey:"totalTokens",name:a("settings.charts.total"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),t.jsx(At,{type:"monotone",dataKey:"promptTokens",name:a("settings.charts.prompt"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),t.jsx(At,{type:"monotone",dataKey:"completionTokens",name:a("settings.charts.completion"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{Text:io}=ue,Jt=({title:e,subtitle:s,emptyText:a,color:n="var(--lotus-chart-primary)",data:r,loading:o,countLabel:l})=>{const{t:u}=ae();return o?t.jsx(N,{size:"small",className:"lotus-metric-card",title:e,children:t.jsx(gt,{active:!0,paragraph:{rows:5}})}):t.jsx(N,{size:"small",className:"lotus-metric-card",title:e,children:r.length===0?t.jsx(He,{image:He.PRESENTED_IMAGE_SIMPLE,description:a}):t.jsxs(t.Fragment,{children:[s?t.jsx(io,{type:"secondary",children:s}):null,t.jsx("div",{style:{width:"100%",minWidth:0,height:280,marginTop:s?12:0},children:t.jsx(Ot,{children:t.jsxs(na,{data:r,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[t.jsx(os,{strokeDasharray:"3 3"}),t.jsx(ls,{type:"number",allowDecimals:!1}),t.jsx(cs,{dataKey:"label",type:"category",width:110}),t.jsx(Nt,{formatter:g=>[g.toLocaleString(),l??u("settings.metricsDashboard.calls",{defaultValue:"Calls"})],labelFormatter:(g,m)=>{var b,p;const c=(p=(b=m==null?void 0:m[0])==null?void 0:b.payload)==null?void 0:p.meta;return c?`${g} · ${c}`:String(g)}}),t.jsx(_s,{dataKey:"count",fill:n,radius:[0,6,6,0],name:l??u("settings.metricsDashboard.calls",{defaultValue:"Calls"})})]})})})]})})},{useToken:oo}=Te,za=({summary:e,loading:s})=>{const{t:a}=ae(),{token:n}=oo();if(s)return t.jsx(gt,{active:!0,paragraph:{rows:1}});const r=[{key:"skill-load-calls",title:a("settings.metricsDashboard.skillsAndMcp.cards.skillLoadCalls",{defaultValue:"Skill Loads"}),value:(e==null?void 0:e.skill_load_calls)??0,color:"var(--lotus-chart-primary)"},{key:"unique-skills",title:a("settings.metricsDashboard.skillsAndMcp.cards.uniqueSkills",{defaultValue:"Unique Skills"}),value:(e==null?void 0:e.unique_skills)??0,color:"var(--lotus-chart-purple)"},{key:"mcp-calls",title:a("settings.metricsDashboard.skillsAndMcp.cards.mcpCalls",{defaultValue:"MCP Calls"}),value:(e==null?void 0:e.mcp_calls)??0,color:"var(--lotus-chart-accent)"},{key:"unique-mcp-servers",title:a("settings.metricsDashboard.skillsAndMcp.cards.uniqueMcpServers",{defaultValue:"MCP Servers"}),value:(e==null?void 0:e.unique_mcp_servers)??0,color:"var(--lotus-chart-cyan)"},{key:"unique-mcp-tools",title:a("settings.metricsDashboard.skillsAndMcp.cards.uniqueMcpTools",{defaultValue:"MCP Tools"}),value:(e==null?void 0:e.unique_mcp_tools)??0,color:"var(--lotus-chart-secondary)"},{key:"core-tool-calls",title:a("settings.metricsDashboard.skillsAndMcp.cards.coreToolCalls",{defaultValue:"Core Tool Calls"}),value:(e==null?void 0:e.core_tool_calls)??0,color:"var(--lotus-metric-text-strong)"}].filter(o=>o.value>0);return r.length===0?null:t.jsx(Je,{gutter:[n.marginSM,n.marginSM],children:r.map(o=>t.jsx(me,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(N,{size:"small",className:"lotus-metric-card",children:t.jsx(Ee,{title:o.title,value:o.value,precision:0,formatter:lt,valueStyle:{color:o.color}})})},o.key))})},{Text:wt}=ue,{useToken:lo}=Te,La=e=>"date"in e?e.date:e.label,co=(e,s)=>{if(s<=0||e<=0)return"var(--lotus-heat-0)";const a=e/s;return a>=.8?"var(--lotus-heat-4)":a>=.6?"var(--lotus-heat-3)":a>=.4?"var(--lotus-heat-2)":a>=.2?"var(--lotus-heat-1)":"var(--lotus-heat-0)"},hs=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),a=Math.floor(s/60),n=s%60;if(a>=60){const r=Math.floor(a/60),o=a%60;return`${r}h ${o}m`}return a>0?`${a}m ${n}s`:`${n}s`},Oa=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString()},qs=e=>{const s=Object.entries(e??{}).sort((a,n)=>n[1]-a[1]);return s.length===0?"-":s.slice(0,6).map(([a,n])=>`${a}: ${rn(n)}`).join(" • ")},Hs=(e,s=320)=>({width:"100%",display:"grid",gridTemplateColumns:`repeat(auto-fit, minmax(${s}px, 1fr))`,gap:e}),uo=()=>{const{t:e}=ae(),{token:s}=lo(),a=Sn(f=>f.themeMode)==="dark",[n,r]=i.useState(void 0),[o,l]=i.useState(void 0),[u,g]=i.useState(void 0),[m,c]=i.useState(30),[b,p]=i.useState("daily"),{summary:S,modelMetrics:v,sessions:x,timeline:R,memorySummary:P,memoryTimeline:C,sessionDetail:I,isLoading:h,isRefreshing:k,isSessionDetailLoading:V,error:F,refresh:U,loadSessionDetail:ee,clearSessionDetail:$}=Ei({filters:{startDate:n,endDate:o,model:u,days:m,granularity:b}}),{summary:j,endpointMetrics:T,requests:D,isLoading:A,isRefreshing:Q,error:O,refresh:Y}=Ci({filters:{startDate:n,endDate:o,days:m,model:u}}),{data:G,isLoading:ne,isRefreshing:ie,error:be,refresh:d}=Ii({filters:{startDate:n,endDate:o,days:m,model:u}}),E=i.useMemo(()=>R.map(f=>({label:La(f),promptTokens:f.total_token_usage.prompt_tokens,completionTokens:f.total_token_usage.completion_tokens,totalTokens:f.total_token_usage.total_tokens})),[R]),M=i.useMemo(()=>v.map(f=>({label:f.model,value:f.model})),[v]),K=i.useMemo(()=>{const f=R.map(ve=>({label:La(ve),sessions:ve.total_sessions,tokens:ve.total_token_usage.total_tokens})),ce=f.reduce((ve,Ne)=>Math.max(ve,Ne.sessions),0);return{points:f,maxSessions:ce}},[R]),se=i.useMemo(()=>{const f=D.map(ve=>ve.duration_ms).filter(ve=>typeof ve=="number"&&ve>0).sort((ve,Ne)=>ve-Ne);if(f.length===0)return null;const ce=Math.ceil(f.length*.95)-1;return f[Math.max(0,Math.min(ce,f.length-1))]},[D]),pe=i.useMemo(()=>[{title:e("settings.metricsDashboard.roundColumns.round"),dataIndex:"round_id",key:"round_id",render:f=>`${f.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:f=>hs(f)},{title:e("settings.metricsDashboard.roundColumns.tokens"),key:"tokens",render:(f,ce)=>rs(ce.token_usage.total_tokens)},{title:e("settings.metricsDashboard.roundColumns.toolCalls"),key:"tool_calls",render:(f,ce)=>ce.tool_calls.length}],[e]),ye=i.useMemo(()=>{const f=(S==null?void 0:S.total_sessions)??0,ce=(S==null?void 0:S.total_tokens.total_tokens)??0,ve=(S==null?void 0:S.total_tool_calls)??0,Ne=(S==null?void 0:S.active_sessions)??0,_e=x.reduce(($t,_)=>$t+_.total_rounds,0),Ve=(S==null?void 0:S.total_tokens_saved)??0,gs=(S==null?void 0:S.tool_context_tokens_saved)??0,Ms=(S==null?void 0:S.non_tool_compression_tokens_saved)??0,Es=(S==null?void 0:S.prompt_cached_tool_outputs)??0,Vt=(S==null?void 0:S.total_compression_events)??0,mt=(j==null?void 0:j.total_requests)??0,Ps=(j==null?void 0:j.total_tokens.total_tokens)??0,Ds=(j==null?void 0:j.failed_requests)??0,Is=D.filter($t=>$t.is_stream).length,ms=f>0?Ne/f*100:0,Fs=mt>0?Ds/mt*100:0,As=D.length>0?Is/D.length*100:0,bt=ce>0?Number((Ve/ce*100).toFixed(1)):0,Rs=Ve>0?Number((gs/Ve*100).toFixed(1)):0;return[{title:e("settings.metricsDashboard.compactStats.avgTokensPerSession"),value:f>0?Math.round(ce/f):0},{title:e("settings.metricsDashboard.compactStats.savedTokens",{defaultValue:"Saved Tokens"}),value:Ve},{title:e("settings.metricsDashboard.compactStats.toolContextSavedTokens",{defaultValue:"Tool Context Saved Tokens"}),value:gs},{title:e("settings.metricsDashboard.compactStats.nonToolCompressionSavedTokens",{defaultValue:"Non-Tool Compression Saved Tokens"}),value:Ms},{title:e("settings.metricsDashboard.compactStats.savedTokenRatio",{defaultValue:"Saved / Chat Tokens"}),value:bt,suffix:"%"},{title:e("settings.metricsDashboard.compactStats.toolSavedShare",{defaultValue:"Tool Share of Saved Tokens"}),value:Rs,suffix:"%"},{title:e("settings.metricsDashboard.compactStats.promptCachedToolOutputs",{defaultValue:"Prompt-Cached Tool Outputs"}),value:Es},{title:e("settings.metricsDashboard.compactStats.compressionEvents",{defaultValue:"Compression Events"}),value:Vt},{title:e("settings.metricsDashboard.compactStats.avgRoundsPerSession"),value:f>0?Number((_e/f).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.toolCallsPerSession"),value:f>0?Number((ve/f).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.activeSessionRate"),value:Number(ms.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.avgTokensPerForward"),value:mt>0?Math.round(Ps/mt):0},{title:e("settings.metricsDashboard.compactStats.forwardErrorRate"),value:Number(Fs.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.streamingRatio"),value:Number(As.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.p95ForwardLatency"),value:hs(se)},{title:e("settings.metricsDashboard.compactStats.modelCoverage"),value:v.length},{title:e("settings.metricsDashboard.compactStats.endpointCoverage"),value:T.length}]},[T.length,D,j,v.length,se,x,S,e]),je=i.useMemo(()=>{const f=(j==null?void 0:j.total_requests)??0,ce=(j==null?void 0:j.failed_requests)??0,ve=D.filter(Ve=>Ve.is_stream).length,Ne=D.length>0?ve/D.length*100:0,_e=f>0?ce/f*100:0;return[{title:e("settings.metricsDashboard.forward.performance.p95Latency",{defaultValue:"P95 Latency"}),value:hs(se)},{title:e("settings.metricsDashboard.forward.performance.errorRate",{defaultValue:"Error Rate"}),value:Number(_e.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.streamingRatio",{defaultValue:"Streaming Ratio"}),value:Number(Ne.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.endpointCoverage",{defaultValue:"Endpoint Coverage"}),value:T.length}]},[T.length,D,j,se,e]),B=i.useMemo(()=>G?[{label:e("settings.metricsDashboard.skillsAndMcp.mix.coreTools",{defaultValue:"Core Tools"}),count:G.core_tool_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.skillLoads",{defaultValue:"Skill Loads"}),count:G.skill_load_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.mcpCalls",{defaultValue:"MCP Calls"}),count:G.mcp_calls}].filter(f=>f.count>0):[],[e,G]),we=i.useMemo(()=>((G==null?void 0:G.top_skills)??[]).map(f=>({label:f.skill_id,count:f.count})),[G]),We=i.useMemo(()=>((G==null?void 0:G.top_mcp_servers)??[]).map(f=>({label:f.server_id,count:f.count,meta:e("settings.metricsDashboard.skillsAndMcp.meta.uniqueTools",{defaultValue:"{{count}} tools",count:f.unique_tools})})),[e,G]),Ie=i.useMemo(()=>((G==null?void 0:G.top_mcp_tools)??[]).map(f=>({label:f.tool_name,count:f.count,meta:f.server_id})),[G]),Oe=i.useMemo(()=>((G==null?void 0:G.top_core_tools)??[]).map(f=>({label:f.name,count:f.count})),[G]),Pe=I==null?void 0:I.session,Ge=k||Q||ie;return t.jsxs(L,{direction:"vertical",size:s.marginMD,style:{width:"100%"},children:[F?t.jsx(qe,{type:"error",showIcon:!0,message:F}):null,O?t.jsx(qe,{type:"error",showIcon:!0,message:O}):null,be?t.jsx(qe,{type:"error",showIcon:!0,message:be}):null,t.jsx(N,{size:"small",title:e("settings.metricsDashboard.filtersTitle"),extra:t.jsx(z,{icon:t.jsx(Lt,{}),loading:Ge,onClick:()=>{U(),Y(),d()},children:e("settings.metricsDashboard.refresh")}),children:t.jsxs(L,{wrap:!0,children:[t.jsx(xa,{placeholder:e("settings.metricsDashboard.startDate"),onChange:f=>{r(f?f.format("YYYY-MM-DD"):void 0)}}),t.jsx(xa,{placeholder:e("settings.metricsDashboard.endDate"),onChange:f=>{l(f?f.format("YYYY-MM-DD"):void 0)}}),t.jsx(te,{allowClear:!0,style:{minWidth:180},placeholder:e("settings.metricsDashboard.model"),value:u,options:M,onChange:f=>{g(f)}}),t.jsx(te,{style:{width:120},value:m,options:[7,14,30,90].map(f=>({label:e("settings.metricsDashboard.daysOption",{value:f}),value:f})),onChange:f=>{c(f)}}),t.jsx(te,{style:{width:140},value:b,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:f=>{p(f)}})]})}),t.jsx(N,{size:"small",title:e("settings.metricsDashboard.dashboardTitle"),children:t.jsx(Ts,{size:"small",destroyInactiveTabPane:!0,items:[{key:"overview",label:e("settings.metricsDashboard.tabs.overview"),children:t.jsxs(L,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(N,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.overviewSections.scaleTitle",{defaultValue:"Scale & Activity"}),extra:t.jsx(wt,{type:"secondary",children:e("settings.metricsDashboard.overviewSections.scaleSubtitle",{defaultValue:"Current usage volume across chat, forward, skills, and memory."})}),children:t.jsxs(L,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(Fa,{summary:S,sessions:x,loading:h}),t.jsx(Da,{summary:j,loading:A}),t.jsx(za,{summary:G,loading:ne}),t.jsx(Ia,{summary:P,loading:h})]})}),t.jsxs(N,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.overviewSections.efficiencyTitle",{defaultValue:"Compression & Efficiency Advantage"}),extra:t.jsx(wt,{type:"secondary",children:e("settings.metricsDashboard.overviewSections.efficiencySubtitle",{defaultValue:"Real savings from context compression, especially around tool-heavy workflows."})}),children:[t.jsx(Je,{gutter:[s.marginSM,s.marginSM],children:ye.map(f=>t.jsx(me,{xs:24,sm:12,md:8,xl:6,children:t.jsx("div",{style:{borderRadius:s.borderRadiusSM,padding:s.paddingXS,background:a?"rgba(255, 255, 255, 0.05)":"rgba(255, 255, 255, 0.82)",border:a?"1px solid rgba(255,255,255,0.08)":"1px solid rgba(148,163,184,0.18)"},children:t.jsx(Ee,{title:f.title,value:f.value,suffix:f.suffix,formatter:typeof f.value=="number"?lt:void 0,valueStyle:{fontSize:s.fontSizeHeading4}})})},f.title))}),t.jsx(wt,{type:"secondary",style:{display:"block",marginTop:s.marginXS},children:e("settings.metricsDashboard.efficiencyHint",{defaultValue:"这些指标优先使用真实运行统计:总节约 Tokens、工具上下文压缩节约、非工具压缩节约、压缩事件数,以及会话 / Forward 的平均负载与质量指标。"})})]})]})},{key:"chat",label:e("settings.metricsDashboard.tabs.chat",{defaultValue:"Chat"}),children:t.jsxs(L,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(Fa,{summary:S,sessions:x,loading:h}),t.jsxs("div",{style:Hs(s.marginSM,360),children:[t.jsx(ro,{data:E,loading:h}),t.jsx(Ji,{data:v,loading:h})]}),t.jsxs("div",{style:Hs(s.marginSM,360),children:[t.jsx(ao,{breakdown:S==null?void 0:S.sync_mismatch_breakdown,loading:h}),t.jsx(N,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.activityHeatmapTitle"),children:K.points.length===0?t.jsx(wt,{type:"secondary",children:e("settings.metricsDashboard.noActivity")}):t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(72px, 1fr))",gap:s.marginXS},children:K.points.map(f=>t.jsxs("div",{style:{borderRadius:s.borderRadiusSM,padding:s.paddingXS,background:co(f.sessions,K.maxSessions),minHeight:64,color:f.sessions>0?"var(--lotus-metric-text-strong)":s.colorTextSecondary},children:[t.jsx("div",{style:{fontSize:12,lineHeight:1.2},children:f.label}),t.jsx("div",{style:{fontWeight:600,marginTop:4},children:e("settings.metricsDashboard.sessionsCount",{count:f.sessions})}),t.jsx("div",{style:{fontSize:12},children:e("settings.metricsDashboard.tokensAmount",{value:oa(f.tokens)})})]},f.label))})})]})]})},{key:"skills-and-mcp",label:e("settings.metricsDashboard.tabs.skillsAndMcp",{defaultValue:"Skills & MCP"}),children:t.jsxs(L,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(za,{summary:G,loading:ne}),t.jsxs("div",{style:Hs(s.marginSM,360),children:[t.jsx(Jt,{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:ne,color:"var(--lotus-chart-primary)"}),t.jsx(Jt,{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:we,loading:ne,color:"var(--lotus-chart-purple)"}),t.jsx(Jt,{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:We,loading:ne,color:"var(--lotus-chart-cyan)"}),t.jsx(Jt,{title:e("settings.metricsDashboard.skillsAndMcp.topMcpToolsTitle",{defaultValue:"Top MCP Tools"}),subtitle:e("settings.metricsDashboard.skillsAndMcp.topMcpToolsSubtitle",{defaultValue:"Most frequently called MCP tool aliases."}),emptyText:e("settings.metricsDashboard.skillsAndMcp.noMcpTools",{defaultValue:"No MCP tools were called in this range."}),data:Ie,loading:ne,color:"var(--lotus-chart-accent)"}),t.jsx(Jt,{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:ne,color:"var(--lotus-chart-secondary)"})]})]})},{key:"forward",label:e("settings.metricsDashboard.tabs.forward",{defaultValue:"Forward"}),children:t.jsxs(L,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(Da,{summary:j,loading:A}),t.jsx(N,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.forward.performanceTitle",{defaultValue:"Forward Performance"}),children:t.jsx(Je,{gutter:[s.marginSM,s.marginSM],children:je.map(f=>t.jsx(me,{xs:24,sm:12,xl:6,children:t.jsx("div",{style:{borderRadius:s.borderRadiusSM,padding:s.paddingXS,background:a?"rgba(255, 255, 255, 0.05)":"rgba(255, 255, 255, 0.82)",border:a?"1px solid rgba(255,255,255,0.08)":"1px solid rgba(148,163,184,0.18)"},children:t.jsx(Ee,{title:f.title,value:f.value,suffix:f.suffix,valueStyle:{fontSize:s.fontSizeHeading4}})})},f.title))})}),t.jsx(Ai,{data:T,loading:A})]})},{key:"memory",label:e("settings.metricsDashboard.tabs.memory",{defaultValue:"Memory"}),children:t.jsxs(L,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(Ia,{summary:P,loading:h}),t.jsx(Hi,{data:C,loading:h}),t.jsx(N,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.memory.breakdownTitle",{defaultValue:"Memory Breakdown"}),children:t.jsxs(ze,{size:"small",bordered:!0,column:1,children:[t.jsx(ze.Item,{label:e("settings.metricsDashboard.memory.byType",{defaultValue:"By Type"}),children:qs(P==null?void 0:P.by_type)}),t.jsx(ze.Item,{label:e("settings.metricsDashboard.memory.byStatus",{defaultValue:"By Status"}),children:qs(P==null?void 0:P.by_status)}),t.jsx(ze.Item,{label:e("settings.metricsDashboard.memory.byScope",{defaultValue:"By Scope"}),children:qs(P==null?void 0:P.by_scope)}),t.jsx(ze.Item,{label:e("settings.metricsDashboard.memory.lastDream",{defaultValue:"Last Dream"}),children:Oa(P==null?void 0:P.last_dream_at)}),t.jsx(ze.Item,{label:e("settings.metricsDashboard.memory.lastReindex",{defaultValue:"Last Reindex"}),children:Oa(P==null?void 0:P.last_reindex_at)})]})})]})},{key:"records",label:e("settings.metricsDashboard.tabs.records"),children:t.jsx(Ts,{size:"small",destroyInactiveTabPane:!0,items:[{key:"sessions",label:e("settings.metricsDashboard.sessionsTabLabel",{count:x.length}),children:t.jsx(N,{size:"small",extra:t.jsx(wt,{type:"secondary",children:e("settings.metricsDashboard.sessionsHint")}),children:t.jsx(eo,{sessions:x,loading:h,onSelectSession:f=>{ee(f)}})})},{key:"forward-requests",label:e("settings.metricsDashboard.forwardTabLabel",{count:D.length}),children:t.jsx(N,{size:"small",children:t.jsx(Vi,{requests:D,loading:A})})}]})}]})}),t.jsx(Qe,{title:e("settings.metricsDashboard.sessionMetricsTitle"),open:!!I,onCancel:$,onOk:$,width:960,destroyOnClose:!0,children:V?t.jsx(wt,{children:e("settings.metricsDashboard.loadingSessionDetails")}):Pe?t.jsxs(L,{direction:"vertical",style:{width:"100%"},size:s.marginMD,children:[t.jsxs(ze,{size:"small",bordered:!0,column:2,children:[t.jsx(ze.Item,{label:e("settings.metricsDashboard.sessionDetail.sessionId"),span:2,children:Pe.session_id}),t.jsx(ze.Item,{label:e("settings.metricsDashboard.sessionDetail.model"),children:Pe.model}),t.jsx(ze.Item,{label:e("settings.metricsDashboard.sessionDetail.status"),children:Pe.status}),t.jsx(ze.Item,{label:e("settings.metricsDashboard.sessionDetail.duration"),children:hs(Pe.duration_ms)}),t.jsx(ze.Item,{label:e("settings.metricsDashboard.sessionDetail.messages"),children:Pe.message_count}),t.jsx(ze.Item,{label:e("settings.metricsDashboard.sessionDetail.totalTokens"),children:rs(Pe.total_token_usage.total_tokens)}),t.jsx(ze.Item,{label:e("settings.metricsDashboard.sessionDetail.toolCalls"),children:Pe.tool_call_count})]}),t.jsx(at,{rowKey:"round_id",size:"small",columns:pe,dataSource:I.rounds,pagination:{pageSize:6,showSizeChanger:!1}})]}):t.jsx(wt,{type:"secondary",children:e("settings.metricsDashboard.noDetail")})})]})},{Text:fs}=ue,{useToken:go}=Te,mo=e=>{const s=e==null?void 0:e.hooks,a=s==null?void 0:s.image_fallback,n=String((a==null?void 0:a.mode)||"placeholder").trim().toLowerCase();return n==="error"||n==="ocr"||n==="vision"?n:"placeholder"},po=e=>{const s=e==null?void 0:e.hooks,a=s==null?void 0:s.image_fallback,n=a==null?void 0:a.enabled;return typeof n=="boolean"?n:!1},ho=()=>{const{t:e}=ae(),{token:s}=go(),[a,n]=zt.useMessage(),[r,o]=i.useState(!1),[l,u]=i.useState(!0),[g,m]=i.useState("placeholder"),c=i.useMemo(()=>[{label:e("settings.hooksTab.mode.placeholder"),value:"placeholder"},{label:e("settings.hooksTab.mode.error"),value:"error"},{label:e("settings.hooksTab.mode.ocr"),value:"ocr"},{label:e("settings.hooksTab.mode.vision"),value:"vision"}],[e]),b=i.useCallback(async()=>{o(!0);try{const x=await Re.getBambooConfig();u(po(x)),m(mo(x))}catch(x){a.error(x instanceof Error?x.message:e("settings.hooksTab.loadFailed"))}finally{o(!1)}},[a,e]),p=i.useCallback(async(x,R)=>{await Re.setBambooConfig({hooks:{image_fallback:{enabled:x,mode:R}}})},[]),S=i.useCallback(async x=>{o(!0);try{await p(x,g),a.success(e(x?"settings.hooksTab.enabled":"settings.hooksTab.disabled")),await b()}catch(R){a.error(R instanceof Error?R.message:e("settings.hooksTab.updateFailed"))}finally{o(!1)}},[b,g,a,p,e]),v=i.useCallback(async x=>{var R;o(!0);try{await p(l,x),a.success(e("settings.hooksTab.modeUpdated",{mode:((R=c.find(P=>P.value===x))==null?void 0:R.label)??x})),await b()}catch(P){a.error(P instanceof Error?P.message:e("settings.hooksTab.modeUpdateFailed"))}finally{o(!1)}},[l,b,c,a,p,e]);return i.useEffect(()=>{b()},[b]),t.jsxs(X,{vertical:!0,gap:s.marginLG,children:[n,t.jsx(N,{size:"small",loading:r,children:t.jsxs(X,{vertical:!0,gap:s.marginXS,children:[t.jsx(fs,{strong:!0,children:e("settings.hooksTab.title")}),t.jsxs(X,{align:"center",justify:"space-between",children:[t.jsx(fs,{children:e("settings.hooksTab.enableImagePreflight")}),t.jsx(fe,{checked:l,onChange:S})]}),t.jsxs(X,{align:"center",justify:"space-between",children:[t.jsx(fs,{children:e("settings.hooksTab.modeLabel")}),t.jsx(te,{style:{width:180},value:g,options:c,onChange:v,disabled:!l})]}),t.jsx(fs,{type:"secondary",style:{fontSize:s.fontSizeSM},children:e("settings.hooksTab.description")})]})})]})};function De(e){return String(e??"").trim()||void 0}function cn(e){return{type:"interval",every_seconds:e}}function fo(e){const s=De(e);if(!s)return{days:[],invalid:!1};const n=s.split(/[\s,]+/).filter(Boolean).map(l=>Number(l)),r=n.some(l=>!Number.isInteger(l)||l<1||l>31);return{days:Array.from(new Set(n.filter(l=>Number.isInteger(l)&&l>=1&&l<=31))),invalid:r}}function Na(e){switch(e.trigger_type){case"interval":{const s=Number(e.interval_seconds||0);return s<=0?{errorKey:"settings.schedulesTab.validation.intervalRequired"}:{trigger:cn(s)}}case"daily":{const s=e.daily_hour,a=e.daily_minute;return s==null||a==null?{errorKey:"settings.schedulesTab.validation.triggerRequired"}:{trigger:{type:"daily",hour:s,minute:a,second:0}}}case"weekly":{const s=e.weekly_weekdays||[],a=e.weekly_hour,n=e.weekly_minute;return s.length===0?{errorKey:"settings.schedulesTab.validation.weekdaysRequired"}:a==null||n==null?{errorKey:"settings.schedulesTab.validation.triggerRequired"}:{trigger:{type:"weekly",weekdays:s,hour:a,minute:n,second:0}}}case"monthly":{const{days:s,invalid:a}=fo(e.monthly_days);if(a)return{errorKey:"settings.schedulesTab.validation.invalidMonthDays"};if(s.length===0)return{errorKey:"settings.schedulesTab.validation.monthDaysRequired"};const n=e.monthly_hour,r=e.monthly_minute;return n==null||r==null?{errorKey:"settings.schedulesTab.validation.triggerRequired"}:{trigger:{type:"monthly",days:s,hour:n,minute:r,second:0}}}case"cron":{const s=De(e.cron_expr);return s?{trigger:{type:"cron",expr:s}}:{errorKey:"settings.schedulesTab.validation.cronRequired"}}default:return{errorKey:"settings.schedulesTab.validation.triggerRequired"}}}function Va(e){switch(e.misfire_policy){case"skip":return{type:"skip"};case"catch_up_all":return{type:"catch_up_all"};case"catch_up_window":return{type:"catch_up_window",max_catch_up_runs:Number(e.catch_up_window_max_runs||1),max_lateness_seconds:Number(e.catch_up_window_max_lateness_seconds||60)};case"run_once":default:return{type:"run_once"}}}const{Text:Fe}=ue,rt=sa.getInstance();function yo(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 xo=[{label:oe.t("settings.schedulesTab.weekdays.mon"),value:"mon"},{label:oe.t("settings.schedulesTab.weekdays.tue"),value:"tue"},{label:oe.t("settings.schedulesTab.weekdays.wed"),value:"wed"},{label:oe.t("settings.schedulesTab.weekdays.thu"),value:"thu"},{label:oe.t("settings.schedulesTab.weekdays.fri"),value:"fri"},{label:oe.t("settings.schedulesTab.weekdays.sat"),value:"sat"},{label:oe.t("settings.schedulesTab.weekdays.sun"),value:"sun"}];function bo(e){return(e==null?void 0:e.type)==="interval"?e.every_seconds:null}function vo(e){switch(e.type){case"interval":return oe.t("settings.schedulesTab.triggerLabels.interval",{type:oe.t("settings.schedulesTab.triggerTypes.interval"),seconds:e.every_seconds});case"daily":return oe.t("settings.schedulesTab.triggerLabels.daily",{type:oe.t("settings.schedulesTab.triggerTypes.daily"),time:`${String(e.hour).padStart(2,"0")}:${String(e.minute).padStart(2,"0")}`});case"weekly":return oe.t("settings.schedulesTab.triggerLabels.weekly",{type:oe.t("settings.schedulesTab.triggerTypes.weekly"),weekdays:e.weekdays.join(", ")});case"monthly":return oe.t("settings.schedulesTab.triggerLabels.monthly",{type:oe.t("settings.schedulesTab.triggerTypes.monthly"),days:e.days.join(", ")});case"cron":return oe.t("settings.schedulesTab.triggerLabels.cron",{type:oe.t("settings.schedulesTab.triggerTypes.cron"),expr:e.expr})}}function jo(e){switch(e==null?void 0:e.type){case"skip":return oe.t("settings.schedulesTab.misfirePolicyOptions.skip");case"catch_up_all":return oe.t("settings.schedulesTab.misfirePolicyOptions.catchUpAll");case"catch_up_window":return oe.t("settings.schedulesTab.misfirePolicyOptions.catchUpWindow");case"run_once":default:return oe.t("settings.schedulesTab.misfirePolicyOptions.runOnce")}}function To(e){switch(e){case"allow":return oe.t("settings.schedulesTab.overlapPolicyOptions.allow");case"skip":return oe.t("settings.schedulesTab.overlapPolicyOptions.skip");case"queue_one":default:return oe.t("settings.schedulesTab.overlapPolicyOptions.queueOne")}}function _o(e){var s;return(s=e.state)!=null&&s.next_fire_at?String(e.state.next_fire_at):"-"}function So(e){var s,a;return(s=e.state)!=null&&s.last_success_at?String(e.state.last_success_at):(a=e.state)!=null&&a.last_finished_at?String(e.state.last_finished_at):"-"}function ko(e){var s,a,n,r;return((s=e.state)==null?void 0:s.running_run_count)>0?{color:"processing",label:oe.t("settings.schedulesTab.statusLabels.running"),detail:oe.t("settings.schedulesTab.statusDetails.active",{count:e.state.running_run_count})}:(((a=e.state)==null?void 0:a.queued_run_count)||0)>0?{color:"gold",label:oe.t("settings.schedulesTab.statusLabels.queued"),detail:oe.t("settings.schedulesTab.statusDetails.pending",{count:e.state.queued_run_count})}:(((n=e.state)==null?void 0:n.consecutive_failures)||0)>0?{color:"error",label:oe.t("settings.schedulesTab.statusLabels.failing"),detail:oe.t("settings.schedulesTab.statusDetails.consecutiveFailures",{count:e.state.consecutive_failures})}:e.enabled?(r=e.state)!=null&&r.last_success_at?{color:"success",label:oe.t("settings.schedulesTab.statusLabels.healthy"),detail:oe.t("settings.schedulesTab.statusDetails.lastRunSucceeded")}:{color:"default",label:oe.t("settings.schedulesTab.statusLabels.idle")}:{color:"default",label:oe.t("settings.schedulesTab.statusLabels.disabled")}}function wo(e){var a,n,r,o,l,u,g,m;const s={name:e.name,enabled:e.enabled,trigger_type:e.trigger.type,timezone:e.timezone||"",start_at:e.start_at||"",end_at:e.end_at||"",misfire_policy:((a=e.misfire_policy)==null?void 0:a.type)||"run_once",overlap_policy:e.overlap_policy||"queue_one",system_prompt:((n=e.run_config)==null?void 0:n.system_prompt)||"",task_message:((r=e.run_config)==null?void 0:r.task_message)||"",model:((o=e.run_config)==null?void 0:o.model)||"",workspace_path:((l=e.run_config)==null?void 0:l.workspace_path)||"",enhance_prompt:((u=e.run_config)==null?void 0:u.enhance_prompt)||"",auto_execute:!!((g=e.run_config)!=null&&g.auto_execute)};switch(((m=e.misfire_policy)==null?void 0:m.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 Us({hourName:e,minuteName:s}){const{t:a}=ae();return t.jsxs(X,{gap:12,wrap:"wrap",children:[t.jsx(y.Item,{label:a("settings.schedulesTab.form.dailyHour"),name:e,style:{width:180},children:t.jsx(Me,{min:0,max:23,style:{width:"100%"}})}),t.jsx(y.Item,{label:a("settings.schedulesTab.form.dailyMinute"),name:s,style:{width:180},children:t.jsx(Me,{min:0,max:59,style:{width:"100%"}})})]})}function Co(){const{t:e}=ae(),[s,a]=zt.useMessage(),[n,r]=i.useState(!1),[o,l]=i.useState([]),[u,g]=i.useState({open:!1,scheduleId:null,sessions:[],loading:!1}),[m,c]=i.useState({open:!1,scheduleId:null,runs:[],loading:!1}),[b,p]=i.useState({open:!1,schedule:null,saving:!1}),S=Ys(j=>j.close),[v]=y.useForm(),[x]=y.useForm(),R=y.useWatch("trigger_type",v),P=y.useWatch("misfire_policy",v),C=y.useWatch("trigger_type",x),I=y.useWatch("misfire_policy",x),h=i.useCallback(async()=>{r(!0);try{const j=await rt.listSchedules();l(j.schedules||[])}catch(j){console.error("[Schedules] Failed to load schedules:",j),s.error(e("settings.schedulesTab.loadFailed"))}finally{r(!1)}},[s,e]),k=i.useCallback(async(j,T,D)=>{try{await D()}catch(A){console.error(`[Schedules] ${j}:`,A),s.error(e(T))}},[s,e]);i.useEffect(()=>{h()},[h]);const V=[{value:"interval",label:e("settings.schedulesTab.triggerTypes.interval")},{value:"daily",label:e("settings.schedulesTab.triggerTypes.daily")},{value:"weekly",label:e("settings.schedulesTab.triggerTypes.weekly")},{value:"monthly",label:e("settings.schedulesTab.triggerTypes.monthly")},{value:"cron",label:e("settings.schedulesTab.triggerTypes.cron")}],F=[{value:"run_once",label:e("settings.schedulesTab.misfirePolicyOptions.runOnce")},{value:"skip",label:e("settings.schedulesTab.misfirePolicyOptions.skip")},{value:"catch_up_all",label:e("settings.schedulesTab.misfirePolicyOptions.catchUpAll")},{value:"catch_up_window",label:e("settings.schedulesTab.misfirePolicyOptions.catchUpWindow")}],U=[{value:"queue_one",label:e("settings.schedulesTab.overlapPolicyOptions.queueOne")},{value:"skip",label:e("settings.schedulesTab.overlapPolicyOptions.skip")},{value:"allow",label:e("settings.schedulesTab.overlapPolicyOptions.allow")}],ee=(j,T)=>t.jsxs(t.Fragment,{children:[t.jsxs(X,{gap:12,wrap:"wrap",children:[t.jsx(y.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(y.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:V})}),t.jsx(y.Item,{label:e("settings.schedulesTab.form.enabled"),name:"enabled",valuePropName:"checked",style:{width:120},children:t.jsx(fe,{})})]}),j==="interval"?t.jsx(y.Item,{label:e("settings.schedulesTab.form.intervalSeconds"),name:"interval_seconds",rules:[{required:!0,message:e("settings.schedulesTab.validation.intervalRequired")}],style:{width:220},children:t.jsx(Me,{min:1,style:{width:"100%"}})}):null,j==="daily"?t.jsx(Us,{hourName:"daily_hour",minuteName:"daily_minute"}):null,j==="weekly"?t.jsxs(t.Fragment,{children:[t.jsx(y.Item,{label:e("settings.schedulesTab.form.weeklyWeekdays"),name:"weekly_weekdays",style:{minWidth:320},children:t.jsx(te,{mode:"multiple",options:xo})}),t.jsx(Us,{hourName:"weekly_hour",minuteName:"weekly_minute"})]}):null,j==="monthly"?t.jsxs(t.Fragment,{children:[t.jsx(y.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(Us,{hourName:"monthly_hour",minuteName:"monthly_minute"})]}):null,j==="cron"?t.jsx(y.Item,{label:e("settings.schedulesTab.form.cronExpr"),name:"cron_expr",children:t.jsx(H,{placeholder:e("settings.schedulesTab.form.cronExprPlaceholder")})}):null,t.jsxs(X,{gap:12,wrap:"wrap",children:[t.jsx(y.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(y.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(y.Item,{label:e("settings.schedulesTab.form.endAt"),name:"end_at",style:{flex:"1 1 240px"},children:t.jsx(H,{placeholder:e("settings.schedulesTab.form.datetimePlaceholder")})})]}),t.jsxs(X,{gap:12,wrap:"wrap",children:[t.jsx(y.Item,{label:e("settings.schedulesTab.form.misfirePolicy"),name:"misfire_policy",style:{flex:"1 1 240px"},children:t.jsx(te,{options:F})}),t.jsx(y.Item,{label:e("settings.schedulesTab.form.overlapPolicy"),name:"overlap_policy",style:{flex:"1 1 240px"},children:t.jsx(te,{options:U})})]}),T==="catch_up_window"?t.jsxs(X,{gap:12,wrap:"wrap",children:[t.jsx(y.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxRuns"),name:"catch_up_window_max_runs",style:{width:220},children:t.jsx(Me,{min:1,style:{width:"100%"}})}),t.jsx(y.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxLatenessSeconds"),name:"catch_up_window_max_lateness_seconds",style:{width:260},children:t.jsx(Me,{min:1,style:{width:"100%"}})})]}):null,t.jsx(y.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(y.Item,{label:e("settings.schedulesTab.form.systemPrompt"),name:"system_prompt",children:t.jsx(H.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})}),t.jsxs(X,{gap:12,wrap:"wrap",children:[t.jsx(y.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(y.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(y.Item,{label:e("settings.schedulesTab.form.autoExecute"),name:"auto_execute",valuePropName:"checked",style:{width:160},children:t.jsx(fe,{})})]}),t.jsx(y.Item,{label:e("settings.schedulesTab.form.enhancePrompt"),name:"enhance_prompt",children:t.jsx(H.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})})]}),$=i.useMemo(()=>[{title:e("settings.schedulesTab.columns.name"),key:"name",render:(j,T)=>t.jsxs(X,{vertical:!0,gap:6,children:[t.jsx(Fe,{strong:!0,children:T.name}),t.jsxs(X,{gap:6,wrap:"wrap",children:[t.jsx(re,{children:vo(T.trigger)}),T.timezone?t.jsx(re,{color:"blue",children:T.timezone}):null,t.jsx(re,{children:jo(T.misfire_policy)}),t.jsx(re,{children:To(T.overlap_policy)})]})]})},{title:e("settings.schedulesTab.columns.status"),key:"status",render:(j,T)=>{const D=ko(T);return t.jsxs(X,{vertical:!0,gap:4,children:[t.jsx(re,{color:D.color,children:D.label}),D.detail?t.jsx(Fe,{type:"secondary",children:D.detail}):null]})}},{title:e("settings.schedulesTab.columns.activity"),key:"activity",render:(j,T)=>{var D,A,Q,O;return t.jsxs(X,{vertical:!0,gap:2,children:[t.jsx(Fe,{type:"secondary",children:e("settings.schedulesTab.activityLabels.queued",{count:((D=T.state)==null?void 0:D.queued_run_count)??0})}),t.jsx(Fe,{type:"secondary",children:e("settings.schedulesTab.activityLabels.running",{count:((A=T.state)==null?void 0:A.running_run_count)??0})}),t.jsx(Fe,{type:"secondary",children:e("settings.schedulesTab.activityLabels.ok",{count:((Q=T.state)==null?void 0:Q.total_success_count)??0})}),t.jsx(Fe,{type:"secondary",children:e("settings.schedulesTab.activityLabels.fail",{count:((O=T.state)==null?void 0:O.total_failure_count)??0})})]})}},{title:e("settings.schedulesTab.columns.nextRun"),key:"next_run_at",render:(j,T)=>t.jsx(Fe,{type:"secondary",children:_o(T)})},{title:e("settings.schedulesTab.columns.lastRun"),key:"last_run_at",render:(j,T)=>t.jsx(Fe,{type:"secondary",children:So(T)})},{title:e("settings.schedulesTab.columns.autoExecute"),key:"auto_execute",render:(j,T)=>{var D,A;return t.jsx(Fe,{type:(D=T.run_config)!=null&&D.auto_execute?void 0:"secondary",children:(A=T.run_config)!=null&&A.auto_execute?e("settings.schedulesTab.yes"):e("settings.schedulesTab.no")})}},{title:e("settings.schedulesTab.columns.model"),key:"model",render:(j,T)=>{var D;return t.jsx(Fe,{type:"secondary",children:(D=T.run_config)!=null&&D.model?String(T.run_config.model):"-"})}},{title:e("settings.schedulesTab.columns.enabled"),key:"enabled",render:(j,T)=>t.jsx(fe,{checked:T.enabled,onChange:async D=>{await k("Failed to toggle","settings.schedulesTab.updateFailed",async()=>{await rt.patchSchedule(T.id,{enabled:D}),await h()})}})},{title:e("settings.schedulesTab.columns.actions"),key:"actions",render:(j,T)=>{const D=t.jsx(Me,{min:1,value:bo(T.trigger)??void 0,disabled:T.trigger.type!=="interval",onChange:async A=>{const Q=typeof A=="number"?A:null;!Q||Q<=0||await k("Failed to patch interval","settings.schedulesTab.updateFailed",async()=>{await rt.patchSchedule(T.id,{trigger:cn(Q)}),await h()})}});return t.jsxs(X,{vertical:!0,gap:8,children:[t.jsxs(X,{gap:8,wrap:"wrap",children:[t.jsx(z,{size:"small",onClick:()=>{p({open:!0,schedule:T,saving:!1}),x.setFieldsValue(wo(T))},children:e("settings.schedulesTab.actions.edit")}),t.jsx(z,{size:"small",onClick:async()=>{await k("Failed to run now","settings.schedulesTab.runNowFailed",async()=>{await rt.runScheduleNow(T.id),s.success(e("settings.schedulesTab.enqueuedRun")),await h()})},children:e("settings.schedulesTab.actions.runNow")}),t.jsx(z,{size:"small",onClick:async()=>{g(A=>({...A,open:!0,scheduleId:T.id,loading:!0,sessions:[]}));try{const A=await rt.listScheduleSessions(T.id);g(Q=>({...Q,open:!0,scheduleId:T.id,loading:!1,sessions:(A.sessions||[]).map(O=>({id:O.id,title:O.title,updated_at:O.updated_at}))}))}catch(A){console.error("[Schedules] Failed to list sessions:",A),s.error(e("settings.schedulesTab.loadSessionsFailed")),g(Q=>({...Q,loading:!1}))}},children:e("settings.schedulesTab.actions.sessions")}),t.jsx(z,{size:"small",onClick:async()=>{c(A=>({...A,open:!0,scheduleId:T.id,loading:!0,runs:[]}));try{const A=await rt.listScheduleRuns(T.id);c(Q=>({...Q,open:!0,scheduleId:T.id,loading:!1,runs:A.runs||[]}))}catch(A){console.error("[Schedules] Failed to list runs:",A),s.error(e("settings.schedulesTab.loadRunsFailed")),c(Q=>({...Q,loading:!1}))}},children:e("settings.schedulesTab.actions.runs")}),t.jsx(z,{danger:!0,size:"small",onClick:async()=>{await k("Failed to delete","settings.schedulesTab.deleteFailed",async()=>{await rt.deleteSchedule(T.id),s.success(e("settings.schedulesTab.deleted")),await h()})},children:e("settings.schedulesTab.actions.delete")})]}),t.jsxs(X,{gap:8,align:"center",wrap:"wrap",children:[t.jsx(Fe,{type:"secondary",children:e("settings.schedulesTab.columns.intervalSeconds")}),T.trigger.type==="interval"?D:t.jsx(ke,{title:e("settings.schedulesTab.nonIntervalReadOnly"),children:t.jsx("span",{children:D})})]})]})}}],[x,s,h,k,e]);return t.jsxs(X,{vertical:!0,gap:16,children:[a,t.jsx(N,{title:e("settings.schedulesTab.createTitle"),className:"lotus-settings-card",children:t.jsxs(y,{form:v,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 j=>{try{const T=!!j.auto_execute,D=De(j.task_message),A=De(j.model);if(T&&!D){s.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:Q,errorKey:O}=Na(j);if(!Q){s.error(e(O||"settings.schedulesTab.validation.triggerRequired"));return}await rt.createSchedule({name:String(j.name||"").trim(),trigger:Q,timezone:De(j.timezone),start_at:De(j.start_at),end_at:De(j.end_at),misfire_policy:Va(j),overlap_policy:j.overlap_policy,enabled:!!j.enabled,run_config:{system_prompt:De(j.system_prompt),task_message:D,model:A,workspace_path:De(j.workspace_path),enhance_prompt:De(j.enhance_prompt),auto_execute:T}}),s.success(e("settings.schedulesTab.created")),v.resetFields(),await h()}catch(T){console.error("[Schedules] Failed to create schedule:",T),s.error(e("settings.schedulesTab.createFailed"))}},children:[ee(R,P),t.jsx(z,{type:"primary",htmlType:"submit",children:e("settings.schedulesTab.actions.create")})]})}),t.jsx(N,{title:e("settings.schedulesTab.listTitle"),className:"lotus-settings-card",extra:t.jsx(z,{onClick:()=>void h(),loading:n,children:e("settings.schedulesTab.actions.refresh")}),children:t.jsx(at,{rowKey:"id",columns:$,dataSource:o,loading:n,pagination:{pageSize:10},scroll:{x:1500}})}),t.jsx(Qe,{title:e("settings.schedulesTab.scheduleSessionsTitle"),open:u.open,onCancel:()=>g(j=>({...j,open:!1,scheduleId:null})),footer:null,children:u.loading?t.jsx(Fe,{type:"secondary",children:e("settings.schedulesTab.loading")}):t.jsx(X,{vertical:!0,gap:8,children:u.sessions.length===0?t.jsx(Fe,{type:"secondary",children:e("settings.schedulesTab.noSessionsYet")}):u.sessions.map(j=>t.jsxs(X,{justify:"space-between",align:"center",children:[t.jsxs(X,{vertical:!0,style:{minWidth:0},children:[t.jsx(Fe,{strong:!0,ellipsis:!0,children:j.title}),t.jsxs(Fe,{type:"secondary",ellipsis:!0,children:[j.id," • ",j.updated_at]})]}),t.jsx(z,{size:"small",onClick:()=>{kn(j.id,{forceRefreshIndex:!0,forceLoadHistory:!0,subscribeIfRunning:!0,forceSubscribe:!0}),S()},children:e("settings.schedulesTab.actions.open")})]},j.id))})}),t.jsx(Qe,{title:e("settings.schedulesTab.scheduleRunsTitle"),open:m.open,onCancel:()=>c(j=>({...j,open:!1,scheduleId:null})),footer:null,width:960,children:m.loading?t.jsx(Fe,{type:"secondary",children:e("settings.schedulesTab.loading")}):m.runs.length===0?t.jsx(Fe,{type:"secondary",children:e("settings.schedulesTab.noRunsYet")}):t.jsx(at,{rowKey:"run_id",pagination:{pageSize:8},dataSource:m.runs,columns:[{title:e("settings.schedulesTab.runHistory.columns.status"),key:"status",render:(j,T)=>t.jsx(re,{color:yo(T.status),children:T.status})},{title:e("settings.schedulesTab.runHistory.columns.scheduledFor"),dataIndex:"scheduled_for",key:"scheduled_for"},{title:e("settings.schedulesTab.runHistory.columns.startedAt"),key:"started_at",render:(j,T)=>T.started_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.completedAt"),key:"completed_at",render:(j,T)=>T.completed_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.session"),key:"session_id",render:(j,T)=>T.session_id||"-"},{title:e("settings.schedulesTab.runHistory.columns.duration"),key:"execution_duration_ms",render:(j,T)=>T.execution_duration_ms!=null?`${T.execution_duration_ms}ms`:"-"},{title:e("settings.schedulesTab.runHistory.columns.outcome"),key:"outcome_reason",render:(j,T)=>T.outcome_reason||(T.was_catch_up?"catch-up":"-")}]})}),t.jsx(Qe,{title:e("settings.schedulesTab.editTitle"),open:b.open,onCancel:()=>p({open:!1,schedule:null,saving:!1}),okText:e("settings.schedulesTab.actions.save"),confirmLoading:b.saving,onOk:()=>x.submit(),forceRender:!0,children:t.jsx(y,{form:x,layout:"vertical",onFinish:async j=>{const T=b.schedule;if(!T)return;const D=!!j.auto_execute,A=De(j.task_message),Q=De(j.model);if(D&&!A){s.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:O,errorKey:Y}=Na(j);if(!O){s.error(e(Y||"settings.schedulesTab.validation.triggerRequired"));return}p(G=>({...G,saving:!0}));try{await rt.patchSchedule(T.id,{name:String(j.name||"").trim()||void 0,enabled:!!j.enabled,trigger:O,timezone:De(j.timezone),start_at:De(j.start_at),end_at:De(j.end_at),misfire_policy:Va(j),overlap_policy:j.overlap_policy,run_config:{system_prompt:De(j.system_prompt),task_message:A,model:Q,workspace_path:De(j.workspace_path),enhance_prompt:De(j.enhance_prompt),auto_execute:D}}),s.success(e("settings.schedulesTab.updated")),p({open:!1,schedule:null,saving:!1}),await h()}catch(G){console.error("[Schedules] Failed to patch schedule:",G),s.error(e("settings.schedulesTab.updateFailed")),p(ne=>({...ne,saving:!1}))}},children:ee(C,I)})})]})}const{Text:Xt}=ue,Yt=sa.getInstance();function Mo(){const{t:e}=ae(),{modal:s,message:a}=ut.useApp(),n=Ke(v=>v.chats),r=Ke(v=>v.currentSessionId),o=Ke(v=>v.refreshChats),l=Ke(v=>v.loadChats),u=Ke(v=>v.loadChatHistory),[g,m]=i.useState(!0),[c,b]=i.useState(!1),p=i.useMemo(()=>r?n.find(v=>v.id===r)??null:null,[n,r]),S=async v=>{if(!c){b(!0);try{await v()}finally{b(!1)}}};return t.jsxs(X,{vertical:!0,gap:16,children:[t.jsx(N,{size:"small",title:e("settings.sessionsTab.currentSessionTitle"),children:p?t.jsxs(X,{vertical:!0,gap:4,children:[t.jsx(Xt,{strong:!0,ellipsis:!0,children:p.title}),t.jsxs(Xt,{type:"secondary",ellipsis:!0,children:[e("settings.sessionsTab.id"),": ",p.id," ","•"," ",e("settings.sessionsTab.kind"),": ",p.kind]}),t.jsx(X,{gap:8,wrap:"wrap",style:{marginTop:8},children:t.jsx(z,{danger:!0,loading:c,onClick:()=>{s.confirm({title:e("settings.sessionsTab.clearMessagesTitle"),content:e("settings.sessionsTab.clearMessagesContent"),okText:e("settings.sessionsTab.clear"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await S(async()=>{await Yt.clearSession(p.id),await u(p.id),await o(),a.success(e("settings.sessionsTab.sessionCleared"))})}})},children:e("settings.sessionsTab.clearMessages")})})]}):t.jsx(Xt,{type:"secondary",children:e("settings.sessionsTab.noActiveSession")})}),t.jsxs(N,{size:"small",title:e("settings.sessionsTab.bulkCleanupTitle"),children:[t.jsxs(X,{align:"center",gap:8,style:{marginBottom:12},children:[t.jsx(Xt,{children:e("settings.sessionsTab.keepPinned")}),t.jsx(fe,{checked:g,onChange:m})]}),t.jsxs(X,{gap:8,wrap:"wrap",children:[t.jsx(z,{danger:!0,loading:c,onClick:()=>{s.confirm({title:e("settings.sessionsTab.deleteAllTitle"),content:e(g?"settings.sessionsTab.deleteAllKeepPinned":"settings.sessionsTab.deleteAllIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await S(async()=>{await Yt.cleanupSessions("all",g),await l(),a.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteAll")}),t.jsx(z,{danger:!0,loading:c,onClick:()=>{s.confirm({title:e("settings.sessionsTab.deleteEmptyTitle"),content:e(g?"settings.sessionsTab.deleteEmptyKeepPinned":"settings.sessionsTab.deleteEmptyIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await S(async()=>{await Yt.cleanupSessions("empty",g),await l(),a.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteEmpty")}),t.jsx(z,{danger:!0,loading:c,onClick:()=>{s.confirm({title:e("settings.sessionsTab.deleteChildrenTitle"),content:e(g?"settings.sessionsTab.deleteChildrenKeepPinned":"settings.sessionsTab.deleteChildrenIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await S(async()=>{await Yt.cleanupSessions("children",g),await l(),a.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteChildren")})]})]}),t.jsxs(N,{size:"small",title:e("settings.sessionsTab.devResetTitle"),children:[t.jsx(Xt,{type:"secondary",children:e("settings.sessionsTab.devResetDescription")}),t.jsx(X,{style:{marginTop:12},children:t.jsx(z,{danger:!0,type:"primary",loading:c,onClick:()=>{s.confirm({title:e("settings.sessionsTab.devResetConfirmTitle"),content:e("settings.sessionsTab.devResetConfirmContent"),okText:e("settings.sessionsTab.reset"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await S(async()=>{await Yt.devResetSessions(),await l(),a.success(e("settings.sessionsTab.devResetDone"))})}})},children:e("settings.sessionsTab.devResetAction")})})]})]})}const dn="notifications/preferences";function un(e){return{enabled:e.enabled,onClarification:e.on_clarification,onToolApproval:e.on_tool_approval,onContextPressure:e.on_context_pressure,onSubAgentComplete:e.on_subagent_complete,onBackgroundTaskComplete:e.on_background_task_complete}}function Eo(e){return{enabled:e.enabled,on_clarification:e.onClarification,on_tool_approval:e.onToolApproval,on_context_pressure:e.onContextPressure,on_subagent_complete:e.onSubAgentComplete,on_background_task_complete:e.onBackgroundTaskComplete}}async function Po(){const e=await Ye.get(dn);return un(e)}async function Do(e){const s=await Ye.put(dn,Eo(e));return un(s)}const{Text:tt}=ue,{useToken:Io}=Te,Fo={enabled:!0,onClarification:!0,onToolApproval:!0,onContextPressure:!0,onSubAgentComplete:!0,onBackgroundTaskComplete:!0},Ao=()=>{const{t:e}=ae(),{token:s}=Io(),{message:a}=ut.useApp(),[n,r]=i.useState(Fo),[o,l]=i.useState(!0),u=wn();i.useEffect(()=>{let c=!1;return(async()=>{try{const b=await Po();c||r(b)}catch{c||a.error(e("settings.notificationsTab.loadError","Failed to load notification preferences"))}finally{c||l(!1)}})(),()=>{c=!0}},[a,e]);const g=(c,b)=>{const p=n,S={...n,[c]:b};r(S),Do(S).then(v=>{r(v)}).catch(()=>{r(p),a.error(e("settings.notificationsTab.saveError","Failed to save notification preferences"))})},m=!u||o;return t.jsx(N,{size:"small",className:"lotus-settings-card",children:t.jsxs(X,{vertical:!0,gap:s.marginMD,children:[!u&&t.jsx(qe,{type:"info",showIcon:!0,message:e("settings.notificationsTab.desktopOnly","Desktop notifications are only available in the Bodhi desktop app.")}),t.jsxs(X,{align:"center",gap:s.marginSM,children:[t.jsx(Wn,{}),t.jsx(tt,{strong:!0,children:e("settings.notificationsTab.title","Desktop Notifications")})]}),t.jsx(tt,{type:"secondary",style:{fontSize:s.fontSizeSM},children:e("settings.notificationsTab.description","Receive OS-level notifications when the app is in the background and user action is required.")}),t.jsx(Le,{style:{margin:`${s.marginXS}px 0`}}),t.jsxs(X,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(tt,{children:e("settings.notificationsTab.enabled","Enable desktop notifications")}),t.jsx(fe,{"data-testid":"notification-enabled-toggle",checked:n.enabled,onChange:c=>g("enabled",c),disabled:m})]}),t.jsx(Le,{style:{margin:`${s.marginXS}px 0`}}),t.jsx(tt,{strong:!0,style:{fontSize:s.fontSizeSM,opacity:n.enabled?1:.5},children:e("settings.notificationsTab.events","Notify when:")}),t.jsxs(X,{vertical:!0,gap:s.marginSM,style:{opacity:n.enabled?1:.5,pointerEvents:n.enabled?"auto":"none"},children:[t.jsxs(X,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(tt,{children:e("settings.notificationsTab.onClarification","Agent needs clarification")}),t.jsx(fe,{"data-testid":"notification-clarification-toggle",checked:n.onClarification,onChange:c=>g("onClarification",c),disabled:m})]}),t.jsxs(X,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(tt,{children:e("settings.notificationsTab.onToolApproval","Tool execution needs approval")}),t.jsx(fe,{"data-testid":"notification-tool-approval-toggle",checked:n.onToolApproval,onChange:c=>g("onToolApproval",c),disabled:m})]}),t.jsxs(X,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(tt,{children:e("settings.notificationsTab.onContextPressure","Context window is critically full")}),t.jsx(fe,{"data-testid":"notification-context-pressure-toggle",checked:n.onContextPressure,onChange:c=>g("onContextPressure",c),disabled:m})]}),t.jsxs(X,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(tt,{children:e("settings.notificationsTab.onSubAgentComplete","Background task completes")}),t.jsx(fe,{"data-testid":"notification-subagent-complete-toggle",checked:n.onSubAgentComplete,onChange:c=>g("onSubAgentComplete",c),disabled:m})]}),t.jsxs(X,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(tt,{children:e("settings.notificationsTab.onBackgroundTaskComplete","Background command finishes")}),t.jsx(fe,{"data-testid":"notification-background-task-complete-toggle",checked:n.onBackgroundTaskComplete,onChange:c=>g("onBackgroundTaskComplete",c),disabled:m})]})]}),t.jsx(Le,{style:{margin:`${s.marginXS}px 0`}}),t.jsxs(X,{align:"center",gap:s.marginSM,children:[t.jsx(Gn,{style:{color:s.colorPrimary}}),t.jsx(tt,{type:"secondary",style:{fontSize:s.fontSizeSM},children:e("settings.notificationsTab.osNote","OS notification permissions may also be required. You can manage them in your system settings.")})]})]})})},{Text:ys,Paragraph:Ro}=ue,gn=({open:e,onCancel:s,onComplete:a,onCopyCode:n,completingAuth:r,copiedUserCode:o,deviceCodeInfo:l,timeRemaining:u,token:g})=>{const{t:m}=ae();return t.jsx(Qe,{title:m("settings.providerTab.copilotAuthModalTitle"),open:e,onCancel:s,footer:[t.jsx(z,{onClick:s,children:m("settings.providerTab.cancel")},"cancel"),t.jsx(z,{type:"primary",onClick:a,loading:r,children:m("settings.providerTab.completedAuthorization")},"complete")],children:l&&t.jsxs(L,{direction:"vertical",size:"large",style:{width:"100%"},children:[t.jsx(qe,{message:m("settings.providerTab.browserOpened"),description:t.jsxs("ol",{children:[t.jsx("li",{children:m("settings.providerTab.authStep1")}),t.jsx("li",{children:m("settings.providerTab.authStep2")}),t.jsx("li",{children:m("settings.providerTab.authStep3")})]}),type:"info"}),t.jsx(N,{size:"small",className:"lotus-settings-card",children:t.jsxs(L,{direction:"vertical",style:{width:"100%"},children:[t.jsx(ys,{type:"secondary",children:m("settings.providerTab.visitUrl")}),t.jsx(L,{children:t.jsx(ys,{copyable:{text:l.verification_uri},children:l.verification_uri})})]})}),t.jsx(N,{style:{textAlign:"center",background:g.colorFillTertiary,borderColor:g.colorBorderSecondary},children:t.jsxs(L,{direction:"vertical",style:{width:"100%"},children:[t.jsx(ys,{type:"secondary",children:m("settings.providerTab.enterCode")}),t.jsxs(L,{children:[t.jsx(ys,{style:{color:g.colorText,fontSize:"32px",fontFamily:"monospace",fontWeight:"bold",letterSpacing:"4px"},children:l.user_code}),t.jsx(z,{icon:o?t.jsx(Zs,{}):t.jsx(Za,{}),onClick:n,type:o?"default":"primary",children:m(o?"settings.providerTab.copied":"settings.providerTab.copyCode")})]}),t.jsx("div",{style:{marginTop:8},children:t.jsxs(re,{color:u<60?"error":u<180?"warning":"success",children:[t.jsx(Jn,{style:{marginRight:4}}),"Expires in ",Math.floor(u/60),":",(u%60).toString().padStart(2,"0")]})})]})}),t.jsx(Ro,{type:"secondary",children:m("settings.providerTab.afterContinueHint")})]})})},zo=new Set(["id","type","provider_type","label","enabled","api_key_encrypted"]),$a=e=>e?Object.fromEntries(Object.entries(e).filter(([s])=>!zo.has(s))):{},{Password:Ba}=H,{Text:ht,Paragraph:Ks}=ue,Lo=["low","medium","high","xhigh","max"],Zt=(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:Lo.map(a=>t.jsx(te.Option,{value:a,children:e(`chat.input.reasoning.${a}`)},a))}),qa=e=>t.jsx(y.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})}),Oo=e=>Array.isArray(e)?e.map(s=>typeof s=="string"?s.trim():"").filter(s=>!!s):[],No=({type:e})=>{const{t:s}=ae();if(!e)return null;switch(e){case"openai":return t.jsxs(t.Fragment,{children:[t.jsx(y.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(xt,{})})}),t.jsx(y.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(y.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Zt(s)}),qa(s)]});case"anthropic":return t.jsxs(t.Fragment,{children:[t.jsx(y.Item,{name:"api_key",label:s("settings.providerTab.anthropicApiKey"),rules:[{required:!0,message:s("settings.providerTab.anthropicApiKeyRequired")}],children:t.jsx(Ba,{placeholder:s("settings.providerTab.anthropicApiKeyPlaceholder","sk-ant-..."),prefix:t.jsx(xt,{})})}),t.jsx(y.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(y.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(y.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Zt(s)})]});case"gemini":return t.jsxs(t.Fragment,{children:[t.jsx(y.Item,{name:"api_key",label:s("settings.providerTab.geminiApiKey"),rules:[{required:!0,message:s("settings.providerTab.geminiApiKeyRequired")}],children:t.jsx(Ba,{placeholder:s("settings.providerTab.geminiApiKeyPlaceholder","AIza..."),prefix:t.jsx(xt,{})})}),t.jsx(y.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(y.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Zt(s)})]});case"copilot":return t.jsxs(t.Fragment,{children:[t.jsx(y.Item,{name:"headless_auth",label:s("settings.providerTab.headlessAuth"),valuePropName:"checked",extra:s("settings.providerTab.headlessAuthHelp"),children:t.jsx(fe,{})}),t.jsx(y.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Zt(s)}),qa(s)]});case"bodhi":return t.jsxs(t.Fragment,{children:[t.jsx(y.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(xt,{})})}),t.jsx(y.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(y.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(y.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Zt(s)})]});default:return null}},Vo=({instances:e,defaultInstanceId:s,onInstancesChanged:a})=>{const{t:n}=ae(),{message:r}=ut.useApp(),{token:o}=Te.useToken(),[l]=y.useForm(),[u,g]=i.useState(!1),[m,c]=i.useState(null),[b,p]=i.useState(!1),[S,v]=i.useState(null),[x,R]=i.useState(void 0),[P,C]=i.useState(null),[I,h]=i.useState(!1),[k,V]=i.useState(!1),[F,U]=i.useState(0),[ee,$]=i.useState(!1),[j,T]=i.useState(!1),[D,A]=i.useState("unknown"),[Q,O]=i.useState(!1),Y=i.useCallback(B=>({type:B.type,label:B.label,enabled:B.enabled,...$a(B.config)}),[]),G=i.useCallback(()=>{c(null),R(void 0),g(!0)},[]),ne=async()=>{try{T(!0);const B=await de.startCopilotAuth();C(B),h(!0),U(B.expires_in)}catch(B){r.error(n("settings.providerTab.startCopilotAuthFailed","Failed to start Copilot authentication")),console.error("Failed to start Copilot authentication:",B)}finally{T(!1)}},ie=async()=>{if(P)try{V(!0),await de.completeCopilotAuth({device_code:P.device_code,interval:P.interval||5,expires_in:P.expires_in}),r.success(n("settings.providerTab.copilotAuthSuccess","Copilot authentication successful!")),h(!1),C(null),await d()}catch(B){r.error(n("settings.providerTab.completeAuthFailed","Authentication completion failed")),console.error("Authentication completion failed:",B)}finally{V(!1)}},be=async()=>{if(P)try{await aa(P.user_code),$(!0),r.success(n("settings.providerTab.userCodeCopied","User code copied!")),setTimeout(()=>$(!1),2e3)}catch{r.error(n("settings.providerTab.copyCodeFailed","Failed to copy code"))}},d=i.useCallback(async()=>{try{O(!0);const B=await de.getCopilotAuthStatus();A(B.authenticated?"authenticated":"not_authenticated")}catch(B){console.error("Failed to check Copilot auth status:",B),A("unknown")}finally{O(!1)}},[]);i.useEffect(()=>{u&&x==="copilot"&&d()},[d,u,x]);const E=i.useCallback(B=>{if(!B){l.resetFields();return}if(m){l.setFieldsValue(Y(m)),R(m.type);return}l.setFieldsValue({enabled:!0})},[Y,m,l]),M=(B="small")=>t.jsx(N,{size:"small",title:n("settings.providerTab.copilotAuth","GitHub Copilot Authentication"),style:{marginTop:8},children:t.jsxs(L,{direction:"vertical",style:{width:"100%"},children:[t.jsxs(L,{children:[t.jsx(ht,{strong:!0,children:n("settings.providerTab.authStatus","Status:")}),D==="authenticated"?t.jsx(re,{color:"success",children:n("settings.providerTab.authenticated","Authenticated")}):D==="not_authenticated"?t.jsx(re,{color:"warning",children:n("settings.providerTab.notAuthenticated","Not Authenticated")}):t.jsx(re,{children:n("settings.providerTab.unknown","Unknown")}),t.jsx(z,{type:"text",size:"small",onClick:()=>void d(),loading:Q,children:n("settings.providerTab.refreshStatus","Refresh")})]}),t.jsx(Ks,{type:"secondary",style:{marginBottom:8},children:n("settings.providerTab.copilotAuthHelp","Copilot requires OAuth authentication. Click the button below to start the Device Code Flow.")}),t.jsx(z,{type:"primary",icon:t.jsx(Qa,{}),onClick:()=>void ne(),loading:j,size:B,children:n("settings.providerTab.authenticateCopilot","Authenticate Copilot")})]})}),K=i.useCallback(B=>{c(B),R(B.type),g(!0)},[]),se=i.useCallback(async()=>{try{const B=await l.validateFields();p(!0);const{type:we,label:We,enabled:Ie,request_overrides_json:Oe,...Pe}=B,Ge=$a(Pe);if("responses_only_models"in Ge&&(Ge.responses_only_models=Oo(Ge.responses_only_models)),typeof Oe=="string"&&Oe.trim()&&(Ge.request_overrides=JSON.parse(Oe)),m){const f={label:We,enabled:Ie,config:Ge};await de.updateProviderInstance(m.id,f),r.success(n("settings.providerTab.instanceUpdated","Provider instance updated"))}else{const f={type:we,label:We||yt[we]||we,enabled:Ie??!0,config:Ge};await de.createProviderInstance(f),r.success(n("settings.providerTab.instanceCreated","Provider instance created"))}g(!1),await a(),await st.getState().loadProviderInstances()}catch(B){(vs(B)||B instanceof Error&&!tn(B))&&r.error(B.message)}finally{p(!1)}},[m,l,r,a,n]),pe=i.useCallback(async B=>{try{v(B),await de.deleteProviderInstance(B),r.success(n("settings.providerTab.instanceDeleted","Provider instance deleted")),await a(),await st.getState().loadProviderInstances()}catch(we){r.error(vs(we)?we.message:n("settings.providerTab.instanceDeleteFailed","Failed to delete instance"))}finally{v(null)}},[a,r,n]),ye=i.useCallback(async B=>{try{await de.setDefaultProviderInstance(B),r.success(n("settings.providerTab.defaultInstanceSet","Default provider updated")),await a(),await st.getState().loadProviderInstances()}catch(we){r.error(vs(we)?we.message:n("settings.providerTab.defaultInstanceFailed","Failed to set default"))}},[a,r,n]),je=i.useCallback(async()=>{await a()},[a]);return i.useEffect(()=>{je()},[]),t.jsxs("div",{style:{marginBottom:16},children:[t.jsxs("div",{style:{marginBottom:12,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[t.jsx(ht,{strong:!0,children:n("settings.providerTab.providerInstances","Provider Instances")}),t.jsx(z,{type:"dashed",icon:t.jsx(dt,{}),onClick:G,"data-testid":"add-provider-instance",children:n("settings.providerTab.addInstance","Add Provider")})]}),e.length===0&&t.jsx(Ks,{type:"secondary",children:n("settings.providerTab.noInstances",'No provider instances configured. Click "Add Provider" to create one.')}),t.jsx(ks,{ghost:!0,items:e.map(B=>{const we=B.id===s,We=yt[B.type]||B.type;return{key:B.id,label:t.jsxs(L,{size:"small",children:[t.jsx("span",{style:{fontWeight:500},children:B.label||We}),t.jsx(re,{color:"processing",style:{fontSize:11},children:We}),we&&t.jsxs(re,{color:"gold",style:{fontSize:11},children:[t.jsx(Yn,{})," ",n("settings.providerTab.default","Default")]}),!B.enabled&&t.jsx(re,{color:"default",style:{fontSize:11},children:n("settings.providerTab.disabled","Disabled")})]}),extra:t.jsxs(L,{size:4,onClick:Ie=>Ie.stopPropagation(),children:[!we&&t.jsx(ke,{title:n("settings.providerTab.setDefault","Set as default"),children:t.jsx(z,{type:"text",size:"small",icon:t.jsx(Xn,{}),onClick:()=>void ye(B.id)})}),t.jsx(z,{type:"text",size:"small",icon:t.jsx(is,{}),onClick:()=>K(B)}),t.jsx(Rt,{title:n("settings.providerTab.confirmDeleteInstance","Delete this provider instance?"),onConfirm:()=>void pe(B.id),okText:n("settings.providerTab.delete","Delete"),cancelText:n("settings.providerTab.cancel","Cancel"),children:t.jsx(z,{type:"text",size:"small",danger:!0,icon:t.jsx(Et,{}),loading:S===B.id})})]}),children:t.jsxs("div",{children:[t.jsxs(Ks,{type:"secondary",style:{marginBottom:8},children:["ID: ",t.jsx(ht,{code:!0,children:B.id})," · Type: ",t.jsx(ht,{code:!0,children:B.type})]}),B.config&&Object.keys(B.config).length>0&&t.jsx(N,{size:"small",style:{marginBottom:8},children:Object.entries(B.config).map(([Ie,Oe])=>Ie==="api_key"?t.jsxs("div",{style:{marginBottom:4},children:[t.jsxs(ht,{type:"secondary",children:[Ie,": "]}),t.jsx(ht,{children:"••••••••"})]},Ie):t.jsxs("div",{style:{marginBottom:4},children:[t.jsxs(ht,{type:"secondary",children:[Ie,": "]}),t.jsx(ht,{children:typeof Oe=="object"?JSON.stringify(Oe):String(Oe)})]},Ie))}),B.type==="copilot"&&M("small")]})}})}),t.jsx(Qe,{open:u,title:m?n("settings.providerTab.editInstance","Edit Provider Instance"):n("settings.providerTab.createInstance","Create Provider Instance"),onCancel:()=>g(!1),onOk:()=>void se(),afterOpenChange:E,confirmLoading:b,width:560,forceRender:!0,destroyOnClose:!0,children:t.jsxs(y,{form:l,layout:"vertical",preserve:!1,children:[t.jsx(y.Item,{name:"type",label:n("settings.providerTab.providerType","Provider Type"),rules:[{required:!0,message:n("settings.providerTab.typeRequired","Please select a provider type")}],children:t.jsx(te,{disabled:!!m,placeholder:n("settings.providerTab.selectType","Select provider type"),onChange:B=>R(B),children:Object.entries(yt).map(([B,we])=>t.jsx(te.Option,{value:B,children:we},B))})}),t.jsx(y.Item,{name:"label",label:n("settings.providerTab.instanceLabel","Label"),extra:n("settings.providerTab.labelHelp","A display name for this provider instance"),children:t.jsx(H,{placeholder:n("settings.providerTab.labelPlaceholder","My OpenAI Instance")})}),t.jsx(y.Item,{name:"enabled",label:n("settings.providerTab.enabled","Enabled"),valuePropName:"checked",initialValue:!0,children:t.jsx(fe,{})}),t.jsx(Le,{children:n("settings.providerTab.instanceConfig","Configuration")}),t.jsx(y.Item,{noStyle:!0,shouldUpdate:!0,children:()=>t.jsx(No,{form:l,type:x})}),x==="copilot"&&M("middle")]})}),t.jsx(gn,{open:I,onCancel:()=>h(!1),onComplete:()=>void ie(),onCopyCode:()=>void be(),completingAuth:k,copiedUserCode:ee,deviceCodeInfo:P,timeRemaining:F,token:o})]})},{Password:Ha}=H,{Text:Ze,Paragraph:Ws}=ue,xs=["openai","anthropic","gemini","copilot","bodhi"],Dt=()=>null,Gs=e=>{var a,n;if(!e||typeof e!="object")return!1;const s=e;return!!((a=s.provider)!=null&&a.trim()&&((n=s.model)!=null&&n.trim()))},$o=(e,s,a)=>{const n=e;n[s]={...n[s]??{},model:a}},Ua=e=>{var a,n;const s=(n=(a=e.memory)==null?void 0:a.background_model)==null?void 0:n.trim();return s||void 0},Ka=(e,s)=>{var a,n,r;return s||((a=e==null?void 0:e.chat)==null?void 0:a.provider)||((n=e==null?void 0:e.fast)==null?void 0:n.provider)||((r=e==null?void 0:e.memory_background)==null?void 0:r.provider)||void 0},Wa=e=>t.jsxs(L,{direction:"vertical",size:4,children:[t.jsxs(Ze,{type:"secondary",children:[e("settings.providerTab.responsesOnlyHelp1")," ",t.jsx(Ze,{code:!0,children:"/responses"}),"."]}),t.jsx(Ze,{type:"secondary",children:e("settings.providerTab.responsesOnlyHelp2")})]}),Bo=["low","medium","high","xhigh","max"],It=(e,s)=>t.jsx(te,{placeholder:e("settings.providerTab.reasoningEffortDefault"),allowClear:!0,value:s==null?void 0:s.value,onChange:s!=null&&s.onChange?a=>{var n;return(n=s.onChange)==null?void 0:n.call(s,a??void 0)}:void 0,disabled:s==null?void 0:s.disabled,size:s==null?void 0:s.size,style:s==null?void 0:s.style,"data-testid":s==null?void 0:s["data-testid"],children:Bo.map(a=>t.jsx(te.Option,{value:a,children:e(`chat.input.reasoning.${a}`)},a))}),qo=()=>{const{t:e}=ae(),{token:s}=Te.useToken(),{message:a}=ut.useApp(),[n]=y.useForm(),[r,o]=i.useState(!1),[l,u]=i.useState(!1),[g,m]=i.useState("copilot"),[c,b]=i.useState(!1),[p,S]=i.useState(null),[v,x]=i.useState(!1),[R,P]=i.useState(!1),[C,I]=i.useState(null),[h,k]=i.useState(!1),[V,F]=i.useState(!1),[U,ee]=i.useState(0),[$,j]=i.useState(!1),[T,D]=i.useState([]),[A,Q]=i.useState(!1),[O,Y]=i.useState([]),[G,ne]=i.useState(null),[ie,be]=i.useState(!1),[d,E]=i.useState([]),[M,K]=i.useState("idle"),[se,pe]=i.useState(null),ye=i.useCallback((_,w)=>{const Z=_.instances??[],q=Z.reduce((ge,le)=>{const $e={...le.config};return $e.request_overrides&&typeof $e.request_overrides=="object"&&($e.request_overrides_json=JSON.stringify($e.request_overrides,null,2)),ge[le.id]=$e,ge},{});let J=_.defaults?{..._.defaults}:void 0;const xe=_.default_provider_instance_id??null,he=xe?Z.find(ge=>ge.id===xe):void 0,Se=typeof(he==null?void 0:he.config.model)=="string"?he.config.model.trim():void 0;!Gs(J==null?void 0:J.chat)&&xe&&Se&&(J={...J||{},chat:{provider:xe,model:Se}});const Ae=w?Ua(w):void 0,Ce=Ka(J,xe);return Ae&&!(J!=null&&J.memory_background)&&Ce&&(J={...J||{},memory_background:{provider:Ce,model:Ae}}),{defaults:J,features:_.features,providers:q}},[]),je=i.useCallback((_,w)=>{Y(_.instances??[]),ne(_.default_provider_instance_id??null),be(!0),n.setFieldsValue(ye(_,w)),b(!0)},[ye,n]),B=i.useCallback(_=>{if(!(_!=null&&_.trim()))return;const w=O.find(Z=>Z.id===_);return w?w.label||yt[w.type]:yt[_]||_},[O]),we=i.useCallback((_,w)=>{const Z=new Set;_!=null&&_.trim()&&Z.add(_);for(const q of xs){const J=w==null?void 0:w[q];J&&Object.keys(J).length>0&&Z.add(q)}return Array.from(Z)},[]);i.useEffect(()=>{if(M!=="success")return;const _=setTimeout(()=>{K("idle"),pe(null)},2e3);return()=>clearTimeout(_)},[M]),i.useEffect(()=>{if(!h||!C){ee(0);return}ee(C.expires_in);const _=setInterval(()=>{ee(w=>w<=1?(clearInterval(_),0):w-1)},1e3);return()=>clearInterval(_)},[h,C]);const We=i.useCallback(async()=>{var _;try{o(!0);const[w,Z]=await Promise.all([de.getProviderConfig(),it.getInstance().getBambooConfig().catch(()=>({}))]);let q=w.defaults?{...w.defaults}:void 0;if(!((_=q==null?void 0:q.chat)!=null&&_.model)&&w.provider&&w.providers){const Ce=w.provider,ge=w.providers[Ce],le=ge==null?void 0:ge.model;le&&(q={...q||{},chat:{provider:Ce,model:le}})}const J=Ua(Z),xe=Ka(q,w.provider||null);J&&!(q!=null&&q.memory_background)&&xe&&(q={...q||{},memory_background:{provider:xe,model:J}});const he=Gs(q==null?void 0:q.chat)?q:void 0,Se={provider:w.provider,defaults:he,providers:w.providers||{},features:w.features};ct("[Provider]","Loaded provider config:",Se);const Ae={...Se.providers||{}};xs.forEach(Ce=>{const ge=Ae[Ce];ge&&ge.request_overrides&&typeof ge.request_overrides=="object"&&(ge.request_overrides_json=JSON.stringify(ge.request_overrides,null,2))}),m(Se.provider),be(!1),E(we(Se.provider,Ae)),n.setFieldsValue({...Se,providers:Ae,defaults:Se.defaults}),b(!0)}catch(w){a.error(e("settings.providerTab.loadConfigFailed")),console.error("Failed to load provider config:",w)}finally{o(!1)}},[n,we,a,e]),Ie=i.useCallback(async()=>{try{const _=await de.getEnvVars();D(_.entries||[])}catch(_){console.warn("Failed to load env vars for provider overrides:",_)}},[]),Oe=i.useCallback(async()=>{try{const[_,w]=await Promise.all([de.getProviderInstances(),it.getInstance().getBambooConfig().catch(()=>({}))]);if(!Array.isArray(_.instances))throw new Error("Provider instances API returned an invalid payload");je(_,w)}catch{}},[je]),Pe=i.useCallback(async()=>{try{x(!0);const _=await de.getCopilotAuthStatus();S(_)}catch(_){console.error("Failed to check Copilot auth status:",_),S({authenticated:!1,message:e("settings.providerTab.checkStatusFailed")})}finally{x(!1)}},[e]);i.useEffect(()=>{Ie(),st.getState().loadCatalog(),Pe(),(async()=>{try{const[_,w]=await Promise.all([de.getProviderInstances(),it.getInstance().getBambooConfig().catch(()=>({}))]);if(!Array.isArray(_.instances))throw new Error("Provider instances API returned an invalid payload");je(_,w)}catch{await We()}})()},[We,Ie,Pe,je]);const Ge=async()=>{try{P(!0);const _=await de.startCopilotAuth();I(_),k(!0)}catch(_){a.error(e("settings.providerTab.startCopilotAuthFailed")),console.error("Failed to start Copilot authentication:",_)}finally{P(!1)}},f=async()=>{if(C)try{F(!0),await de.completeCopilotAuth({device_code:C.device_code,interval:C.interval||5,expires_in:C.expires_in}),a.success(e("settings.providerTab.copilotAuthSuccess")),k(!1),I(null),await Pe()}catch(_){a.error(e("settings.providerTab.completeAuthFailed")),console.error("Authentication completion failed:",_)}finally{F(!1)}},ce=async()=>{if(C)try{await aa(C.user_code),j(!0),a.success(e("settings.providerTab.userCodeCopied")),setTimeout(()=>j(!1),2e3)}catch{a.error(`${e("settings.providerTab.copyCodeFailedPrefix")} ${C.user_code}`)}},ve=async()=>{try{P(!0),await de.logoutCopilot(),a.success(e("settings.providerTab.logoutSuccess")),await Pe()}catch(_){a.error(e("settings.providerTab.logoutFailed")),console.error("Failed to logout:",_)}finally{P(!1)}},Ne=i.useCallback(async()=>{Q(!0);try{const _=await de.fetchCatalogModels();await st.getState().loadCatalog();const w=_.fetched.filter(q=>q.models&&q.models.length>0).length;_.fetched.filter(q=>q.error).length>0?a.warning(e("settings.providerTab.fetchModelsPartialSuccess",{success:w,total:_.fetched.length})):a.success(e("settings.providerTab.fetchModelsSuccess",{count:w}))}catch{a.error(e("settings.providerTab.fetchModelsFailed"))}finally{Q(!1)}},[a,e]),_e=_=>vs(_)||_ instanceof Error?_.message:e("settings.providerTab.unknownError"),Ve=_=>{n.setFields([{name:["provider"],errors:[]},{name:["providers",_,"api_key"],errors:[]},{name:["defaults","chat"],errors:[]}])},gs=_=>{const w=_.trim();return w?w.includes(".")?w.split(".").filter(Boolean):w==="provider"?["provider"]:w==="provider/providers"?["provider"]:null:null},Ms=(_,w)=>{if(!_.length)return;const Z=_.map(q=>{const J=gs(q.path);return J?{name:J,errors:[q.message]}:q.message.toLowerCase().includes("api key")?{name:["providers",w,"api_key"],errors:[q.message]}:{name:["provider"],errors:[q.message]}}).filter((q,J,xe)=>xe.findIndex(he=>JSON.stringify(he.name)===JSON.stringify(q.name))===J);Z.length&&n.setFields(Z)},Es=async _=>{var Z;const w=_.provider||g;Ve(w);try{const J=await it.getInstance().validateBambooConfigPatch({provider:_.provider,providers:_.providers||{},defaults:_.defaults,features:{..._.features||{},provider_model_ref:!0}});if(J.valid)return{valid:!0};const xe=((Z=J.errors)==null?void 0:Z.provider)||[];Ms(xe,w);const he=xe[0];return{valid:!1,message:(he==null?void 0:he.message)||e("settings.providerTab.invalidConfig")}}catch(q){return console.warn("Config validation failed, falling back to save:",q),{valid:!0}}},Vt=async(_,w)=>{var Z,q;try{o(!0);const J={provider:_.provider,defaults:_.defaults,providers:{..._.providers||{}},features:{..._.features||{},provider_model_ref:!0}},xe=(Z=J.defaults)==null?void 0:Z.chat;if(!Gs(xe)){const ge=e("settings.providerTab.selectModelRequired");if(n.setFields([{name:["defaults","chat"],errors:[ge]}]),(w==null?void 0:w.showMessage)!==!1&&a.error(ge),w!=null&&w.throwOnError)throw new Error(ge);return}const he=J.providers;for(const ge of xs){const le=he[ge];if(!le)continue;const $e=le.request_overrides_json;if(typeof $e!="string")continue;const vt=$e.trim();if(!vt)delete le.request_overrides;else try{le.request_overrides=JSON.parse(vt)}catch(Bt){const qt=e("settings.providerTab.invalidRequestOverridesJson",{provider:ge,error:Bt.message});if(n.setFields([{name:["providers",ge,"request_overrides_json"],errors:[qt]}]),(w==null?void 0:w.showMessage)!==!1&&a.error(qt),w!=null&&w.throwOnError)throw Bt;return}delete le.request_overrides_json}const Se={...J.providers||{}},Ae=J.provider,Ce=(q=J.defaults)==null?void 0:q.chat;if(Ce!=null&&Ce.model&&Ae&&$o(Se,Ae,Ce.model),ie){const ge=it.getInstance(),le={defaults:J.defaults,features:{...J.features||{},provider_model_ref:!0}};ct("[Provider]","Saving instance-mode config:",le),await ge.setBambooConfig(le)}else{const le={provider:J.provider||g,defaults:J.defaults,providers:Se,features:J.features},$e=await Es(J);if(!$e.valid){const vt=$e.message||e("settings.providerTab.invalidConfig");if((w==null?void 0:w.showMessage)!==!1&&a.error(`${e("settings.providerTab.invalidConfigPrefix")}: ${vt}`),w!=null&&w.throwOnError)throw new Error(vt);return}ct("[Provider]","Saving provider config:",le),await de.saveProviderConfig(le)}(w==null?void 0:w.showMessage)!==!1&&a.success(e("settings.providerTab.saveConfigSuccess"))}catch(J){const xe=_e(J);if((w==null?void 0:w.showMessage)!==!1&&a.error(xe?`${e("settings.providerTab.saveConfigErrorPrefix")}: ${xe}`:e("settings.providerTab.saveConfigFailed")),console.error("Failed to save configuration:",J),w!=null&&w.throwOnError)throw J}finally{o(!1)}},mt=async _=>{var w,Z,q,J,xe;try{u(!0);const{useProviderStore:he}=await Qs(async()=>{const{useProviderStore:Ht}=await import("./App-DlBGZjWK.js").then(zs=>zs.ak);return{useProviderStore:Ht}},__vite__mapDeps([4,1,2,3,5,6,7,8]),import.meta.url),{useAppStore:Se}=await Qs(async()=>{const{useAppStore:Ht}=await import("./App-DlBGZjWK.js").then(zs=>zs.al);return{useAppStore:Ht}},__vite__mapDeps([4,1,2,3,5,6,7,8]),import.meta.url),Ae=(w=he.getState().providerConfig.defaults)==null?void 0:w.chat;ie?await he.getState().loadProviderInstances():await he.getState().loadProviderConfig();const Ce=(Z=he.getState().providerConfig.defaults)==null?void 0:Z.chat;he.getState().setSelectedModelRef(null);const ge=Se.getState().currentSessionId,le=ge&&Se.getState().chats.find(Ht=>Ht.id===ge)||null,$e=Ae?`${Ae.provider}/${Ae.model}`:null,vt=Ce?`${Ce.provider}/${Ce.model}`:null,Bt=(q=le==null?void 0:le.config)!=null&&q.model_ref?`${le.config.model_ref.provider}/${le.config.model_ref.model}`:null,qt=((xe=(J=le==null?void 0:le.config)==null?void 0:J.model)==null?void 0:xe.trim())||null;!!(ge&&(le!=null&&le.config)&&Ce&&vt!==$e&&(!Bt||Bt===$e)&&(!qt||qt===(Ae==null?void 0:Ae.model)))&&ge&&(le!=null&&le.config)&&Ce&&Se.getState().updateSession(ge,{config:{...le.config,model:Ce.model,model_ref:Ce}}),(_==null?void 0:_.showMessage)!==!1&&a.success(e("settings.providerTab.applyConfigSuccess"))}catch(he){const Se=_e(he);if((_==null?void 0:_.showMessage)!==!1&&a.error(Se?`${e("settings.providerTab.applyConfigErrorPrefix")}: ${Se}`:e("settings.providerTab.applyConfigFailed")),console.error("Failed to apply configuration:",he),_!=null&&_.throwOnError)throw he}finally{u(!1)}},Ps=async _=>{try{const w=n.getFieldsValue(!0);await Vt(w,{throwOnError:!0}),await mt({throwOnError:!0})}catch{}},Ds=async(_,w)=>{if(!(_==="chat"&&!w)&&M!=="saving"){K("saving"),pe(null);try{const Z=n.getFieldsValue(!0),q=Z.defaults;if(!(q!=null&&q.chat))throw new Error(e("settings.providerTab.selectModelRequired"));Z.defaults={...q,[_]:w},await Vt(Z,{showMessage:!1,throwOnError:!0}),await mt({showMessage:!1,throwOnError:!0}),K("success"),a.success(e("settings.providerTab.modelUpdated"))}catch(Z){const q=_e(Z);K("error"),pe(q),a.error(q?`${e("settings.providerTab.updateModelErrorPrefix")}: ${q}`:e("settings.providerTab.updateModelFailed"))}}},Is=async(_,w)=>{if(M!=="saving"){K("saving"),pe(null);try{if(ie){const Z=O.find(q=>q.id===_);if(!Z)throw new Error(e("settings.providerTab.providerNotConfigured"));await de.updateProviderInstance(Z.id,{config:{reasoning_effort:w??null}}),await Oe(),await st.getState().loadProviderInstances()}else{const Z=n.getFieldsValue(!0);await Vt(Z,{showMessage:!1,throwOnError:!0}),await mt({showMessage:!1,throwOnError:!0})}K("success"),a.success(e("settings.providerTab.reasoningEffortUpdated"))}catch(Z){const q=_e(Z);K("error"),pe(q),a.error(q?`${e("settings.providerTab.updateReasoningEffortErrorPrefix")}: ${q}`:e("settings.providerTab.updateReasoningEffortFailed"))}}},ms=(_,w)=>{if(!_)return null;const Z=B(_)||_,q=n.getFieldValue(["providers",_,"reasoning_effort"]),J=(w==null?void 0:w.emphasis)==="subtle",xe=(w==null?void 0:w.label)||e("settings.providerTab.reasoningEffortOptional"),he=(w==null?void 0:w.helperText)||e("settings.providerTab.reasoningEffortHelp");return t.jsx("div",{style:{marginTop:(w==null?void 0:w.marginTop)??8,width:"100%"},children:t.jsxs(L,{direction:"vertical",size:J?6:4,style:{width:"100%"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,flexWrap:"wrap"},children:[t.jsx(Ze,{strong:!J,type:J?"secondary":void 0,style:J?{fontSize:s.fontSizeSM,lineHeight:1.4}:void 0,children:xe}),w!=null&&w.showProviderLabel?t.jsx(Ze,{type:"secondary",style:{fontSize:s.fontSizeSM,lineHeight:1.4},children:Z}):null]}),It(e,{value:q,disabled:M==="saving",size:(w==null?void 0:w.size)??(J?"small":void 0),style:{width:"100%"},"data-testid":w==null?void 0:w.dataTestId,onChange:Se=>{n.setFieldValue(["providers",_,"reasoning_effort"],Se),w!=null&&w.autoSave&&Is(_,Se)}}),t.jsx(Ze,{type:"secondary",style:J?{fontSize:s.fontSizeSM,lineHeight:1.5}:void 0,children:he})]})})},Fs=i.useCallback(_=>{const w=n.getFieldValue(["providers",_]);return w?_==="copilot"?(p==null?void 0:p.authenticated)??!1:!!w.api_key:!1},[n,p]),As=()=>{const _=Z=>{const q=n.getFieldValue(["defaults",Z]);return t.jsx(Cn,{value:q,dataTestId:`model-preference-${Z}-picker`,appearance:"contrast",disabled:M==="saving",onChange:J=>{n.setFieldValue(["defaults",Z],J),Ds(Z,J)}})},w=(Z,q,J)=>t.jsxs("div",{style:{width:"100%",display:"flex",alignItems:"flex-start",gap:s.marginLG,flexWrap:"wrap"},children:[t.jsx("div",{style:{flex:"1 1 420px",minWidth:0},children:t.jsxs(L,{direction:"vertical",size:8,style:{width:"100%"},children:[t.jsx(Ze,{strong:!0,children:q}),_(Z),J?t.jsx(Ze,{type:"secondary",children:J}):null]})}),t.jsx("div",{style:{flex:"0 1 320px",minWidth:280},children:t.jsx(y.Item,{noStyle:!0,shouldUpdate:!0,children:()=>{const xe=n.getFieldValue(["defaults",Z]),he=xe==null?void 0:xe.provider;return ms(he,{autoSave:!0,dataTestId:`model-preference-${Z}-reasoning-effort`,label:e("settings.providerTab.reasoningEffortOptional"),helperText:e("settings.providerTab.reasoningEffortHelp"),marginTop:0,size:"small",emphasis:"subtle",showProviderLabel:!!he})}})})]});return t.jsxs(N,{size:"small",title:e("settings.providerTab.modelPreferences"),style:{marginBottom:16},children:[t.jsx(y.Item,{name:["defaults","chat"],noStyle:!0,preserve:!0,children:t.jsx(Dt,{})}),t.jsx(y.Item,{name:["defaults","fast"],noStyle:!0,preserve:!0,children:t.jsx(Dt,{})}),t.jsx(y.Item,{name:["defaults","task_summary"],noStyle:!0,preserve:!0,children:t.jsx(Dt,{})}),t.jsx(y.Item,{name:["defaults","memory_background"],noStyle:!0,preserve:!0,children:t.jsx(Dt,{})}),t.jsx(y.Item,{name:["defaults","sub_agent"],noStyle:!0,preserve:!0,children:t.jsx(Dt,{})}),t.jsx(y.Item,{name:["defaults","vision"],noStyle:!0,preserve:!0,children:t.jsx(Dt,{})}),t.jsxs(L,{direction:"vertical",size:16,style:{width:"100%"},children:[w("chat",e("settings.providerTab.defaultModel")),w("fast",e("settings.providerTab.fastModel"),e("settings.providerTab.fastModelHelp")),w("task_summary",e("settings.providerTab.taskSummaryModel"),e("settings.providerTab.taskSummaryModelHelp")),w("memory_background",e("settings.providerTab.memoryBackgroundModel"),e("settings.providerTab.memoryBackgroundModelHelp")),w("sub_agent",e("settings.providerTab.subAgentModel"),e("settings.providerTab.subAgentModelHelp")),w("vision",e("settings.providerTab.visionModel"),e("settings.providerTab.visionModelHelp"))]})]})},bt=_=>{const w=T.map(q=>q.name);return t.jsx(y.Item,{name:["providers",_,"request_overrides_json"],label:e("settings.providerTab.advancedRequestOverrides"),extra:t.jsxs(L,{direction:"vertical",size:4,children:[t.jsx(Ze,{type:"secondary",children:e("settings.providerTab.advancedRequestOverridesHelp")}),t.jsxs(Ze,{type:"secondary",children:[e("settings.providerTab.envVarInjection")," ",t.jsx(Ze,{code:!0,children:'{ "type": "env_ref", "name": "YOUR_ENV_NAME" }'})]}),w.length>0&&t.jsx(L,{wrap:!0,size:[6,6],children:w.map(q=>t.jsx(re,{children:q},q))})]}),children:t.jsx(H.TextArea,{autoSize:{minRows:8,maxRows:20},placeholder:`{
|
|
4
4
|
"common": {
|
|
5
5
|
"headers": {
|
|
6
6
|
"x-request-id": { "type": "generated", "generator": "uuid" },
|