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