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