@bigduu/lotus 2026.7.13 → 2026.7.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +2 -0
  2. package/README.zh-CN.md +2 -0
  3. package/dist/assets/{ChildApprovalDialog-B8LV5Brg.js → ChildApprovalDialog-MnpDFKzH.js} +1 -1
  4. package/dist/assets/{CommandPalette-Bv7nlRLt.js → CommandPalette-D1atuulX.js} +1 -1
  5. package/dist/assets/{CommandSelector-C3ulsDEO.js → CommandSelector-CNYv9TD_.js} +1 -1
  6. package/dist/assets/{ContextBar-BZbSoylh.js → ContextBar-D55kxbWQ.js} +1 -1
  7. package/dist/assets/{HomeDashboard-CgF7UUMa.js → HomeDashboard-WjzlXY6L.js} +1 -1
  8. package/dist/assets/{MetricsService-D9UHnvd2.js → MetricsService-Cncz4Wn7.js} +9 -9
  9. package/dist/assets/{QuestionDialog--OHAcOEw.js → QuestionDialog-DqTR1Bfi.js} +1 -1
  10. package/dist/assets/{SessionSummaryCard-k8eqS5lA.js → SessionSummaryCard-rWg4kae2.js} +1 -1
  11. package/dist/assets/{SubAgentsPanel-DrzlO9tS.js → SubAgentsPanel-C1Zt2sJq.js} +1 -1
  12. package/dist/assets/{SystemPromptSelector-Cgw6oRAS.js → SystemPromptSelector-oLKY5OxV.js} +1 -1
  13. package/dist/assets/SystemSettingsPage-DITQ98iL.js +22 -0
  14. package/dist/assets/{TodoList-Bf7mCaiV.js → TodoList-DeGB_kfz.js} +1 -1
  15. package/dist/assets/{WorkspacePathModal-BAca14jc.js → WorkspacePathModal-DN1m7RXU.js} +1 -1
  16. package/dist/assets/{architectureDiagram-3BPJPVTR-Cc0X2SOX.js → architectureDiagram-3BPJPVTR-CbevEGn3.js} +1 -1
  17. package/dist/assets/{blockDiagram-GPEHLZMM-C0KHavBI.js → blockDiagram-GPEHLZMM-BxMwTU63.js} +1 -1
  18. package/dist/assets/{c4Diagram-AAUBKEIU-CUf6i_A7.js → c4Diagram-AAUBKEIU-DXtujyjB.js} +1 -1
  19. package/dist/assets/{chunk-4BX2VUAB-BJh4D-bi.js → chunk-4BX2VUAB-BFMQnMIG.js} +1 -1
  20. package/dist/assets/{chunk-QZHKN3VN-BPX3Wbyh.js → chunk-QZHKN3VN-BXkRL_rn.js} +1 -1
  21. package/dist/assets/{classDiagram-v2-Q7XG4LA2-BJbnmQ0y.js → classDiagram-v2-Q7XG4LA2-BdH4VFzX.js} +1 -1
  22. package/dist/assets/{cose-bilkent-S5V4N54A-zbmmH2SQ.js → cose-bilkent-S5V4N54A-DCkZzESS.js} +1 -1
  23. package/dist/assets/{dagre-BM42HDAG-D2ARftVi.js → dagre-BM42HDAG-BkFUV3DD.js} +1 -1
  24. package/dist/assets/{diagram-2AECGRRQ-DS_VIDcC.js → diagram-2AECGRRQ-DF5bhWsS.js} +1 -1
  25. package/dist/assets/{diagram-5GNKFQAL-DdKodxQe.js → diagram-5GNKFQAL-C4OMRMl4.js} +1 -1
  26. package/dist/assets/{diagram-KO2AKTUF-DyYogOtU.js → diagram-KO2AKTUF-wODWwMnc.js} +1 -1
  27. package/dist/assets/{diagram-LMA3HP47-CRsDsyq7.js → diagram-LMA3HP47-CbU-4gVW.js} +1 -1
  28. package/dist/assets/{diagram-OG6HWLK6-B8vR2DMt.js → diagram-OG6HWLK6-DcqvYHkr.js} +1 -1
  29. package/dist/assets/{erDiagram-TEJ5UH35-Bli7r7qi.js → erDiagram-TEJ5UH35-DFO8ihoJ.js} +1 -1
  30. package/dist/assets/{flowDiagram-I6XJVG4X-CYBm2UVK.js → flowDiagram-I6XJVG4X-D2WdBFot.js} +1 -1
  31. package/dist/assets/{ganttDiagram-6RSMTGT7-C1M6PTcZ.js → ganttDiagram-6RSMTGT7-C3jqysPv.js} +1 -1
  32. package/dist/assets/{gitGraphDiagram-PVQCEYII-CfzDNeeT.js → gitGraphDiagram-PVQCEYII-Dbqb9y0l.js} +1 -1
  33. package/dist/assets/{ishikawaDiagram-YF4QCWOH-CXNXjWYv.js → ishikawaDiagram-YF4QCWOH-D6d8mzB1.js} +1 -1
  34. package/dist/assets/{journeyDiagram-JHISSGLW-k2I2en9e.js → journeyDiagram-JHISSGLW-BortyUjA.js} +1 -1
  35. package/dist/assets/{kanban-definition-UN3LZRKU-fBzcWVq1.js → kanban-definition-UN3LZRKU-C2RNw2kj.js} +1 -1
  36. package/dist/assets/{main-CMBp6TFR.js → main-Bm_td6Y3.js} +6 -6
  37. package/dist/assets/{mindmap-definition-RKZ34NQL-C0aMOvXZ.js → mindmap-definition-RKZ34NQL-KdlUBBen.js} +1 -1
  38. package/dist/assets/{pieDiagram-4H26LBE5-3JdASr15.js → pieDiagram-4H26LBE5-Brh_y6dV.js} +1 -1
  39. package/dist/assets/{quadrantDiagram-W4KKPZXB-DjWz9ih0.js → quadrantDiagram-W4KKPZXB-DDcFGc8G.js} +1 -1
  40. package/dist/assets/{requirementDiagram-4Y6WPE33-Cuya5SaT.js → requirementDiagram-4Y6WPE33-C_iapLQW.js} +1 -1
  41. package/dist/assets/{sankeyDiagram-5OEKKPKP-DYfSOmpL.js → sankeyDiagram-5OEKKPKP-C5IGzDJl.js} +1 -1
  42. package/dist/assets/{sequenceDiagram-3UESZ5HK-B5UJcnmP.js → sequenceDiagram-3UESZ5HK-D-iPBZzc.js} +1 -1
  43. package/dist/assets/{stateDiagram-AJRCARHV-DZXWrQl1.js → stateDiagram-AJRCARHV-BUcBjCHw.js} +1 -1
  44. package/dist/assets/{stateDiagram-v2-BHNVJYJU-DVbPbZiG.js → stateDiagram-v2-BHNVJYJU-BLRmGLIw.js} +1 -1
  45. package/dist/assets/{timeline-definition-PNZ67QCA-B40Lgfp8.js → timeline-definition-PNZ67QCA-CgjhGxB5.js} +1 -1
  46. package/dist/assets/{vendor-charts-CNLSFcom.js → vendor-charts-Cddnk1Vn.js} +1 -1
  47. package/dist/assets/{vendor-mermaid-GjPwPGd2.js → vendor-mermaid-DIRrTQU1.js} +3 -3
  48. package/dist/assets/{vendor-pdf-B2zC5nd1.js → vendor-pdf-BkH3r1kx.js} +3 -3
  49. package/dist/assets/{vennDiagram-CIIHVFJN-CZvfEIkq.js → vennDiagram-CIIHVFJN-DIN_Q5ND.js} +1 -1
  50. package/dist/assets/{wardley-L42UT6IY-BiXJ6t8a.js → wardley-L42UT6IY-9HfVkYgx.js} +1 -1
  51. package/dist/assets/{wardleyDiagram-YWT4CUSO-D49vkhGv.js → wardleyDiagram-YWT4CUSO-U39P90SF.js} +1 -1
  52. package/dist/assets/{xychartDiagram-2RQKCTM6-DPMEuY_W.js → xychartDiagram-2RQKCTM6-CqQnkZEa.js} +1 -1
  53. package/dist/index.html +2 -2
  54. package/package.json +1 -1
  55. package/dist/assets/SystemSettingsPage-CBDYfyHt.js +0 -22
@@ -0,0 +1,22 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./MetricsService-Cncz4Wn7.js","./vendor-markdown-Bz_2-zkk.js","./vendor-i18n-Dm-c3D_C.js","./vendor-antd-IzIw5qDM.js","./vendor-mermaid-DIRrTQU1.js","./main-Bm_td6Y3.js","./main-B6snAd4S.css","./MetricsService-CPTVCb46.css"])))=>i.map(i=>d[i]);
2
+ var Pa=Object.defineProperty;var Da=(e,s,n)=>s in e?Pa(e,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[s]=n;var kn=(e,s,n)=>Da(e,typeof s!="symbol"?s+"":s,n);import{j as t}from"./vendor-markdown-Bz_2-zkk.js";import{a as o,u as re,R as Sn,i as de}from"./vendor-i18n-Dm-c3D_C.js";import{M as Ia,u as Le,h as Fa,V as Aa,d as Ra,W as fn,l as nt,e as ut,X as za,Y as xt,Z as Re,_ as La,$ as Oa,a0 as Na,a1 as Va,a2 as ma,a3 as lt,a4 as me,J as _n,t as $e,a5 as ha,g as bn,m as is,y as $a,x as dn,F as Ba,a6 as qa,a7 as vt,i as ws,a8 as Ua,a9 as Ha,aa as wn,ab as Ka,ac as Cn,ad as Mn,ae as En,af as Pn,A as Wa,ag as Ga,B as Xa,ah as Ja,ai as Ya,aj as Za,ak as Qa,al as er}from"./MetricsService-Cncz4Wn7.js";import{q as V,j as O,u as Ie,T as ue,ao as B,B as R,t as Se,bl as b,y as ls,b6 as Es,bm as ae,bn as pe,bo as Ee,v as He,bp as Ye,bq as he,l as we,b3 as We,br as tr,av as Pe,F as W,a$ as Fs,aV as sr,bs as Tt,aD as kt,ad as nr,b9 as ar,A as rt,bt as As,af as Vt,ah as at,n as oe,bu as Dn,bv as et,aa as Xe,bw as rr,a9 as At,x as $t,a5 as Ot,bx as ir,D as or,b5 as In,by as Ue,E as Be,a8 as ya,bz as lr,aJ as cr,bA as gt,bB as De,X as dr,bC as Fn,bD as ur,bE as gr,Y as un,N as pr,bF as mr,bG as hr,bH as fa,bI as jt,b4 as An,bJ as yr,an as fr,ar as br,be as xr}from"./vendor-antd-IzIw5qDM.js";import{_ as gn}from"./vendor-mermaid-DIRrTQU1.js";import{l as vr}from"./main-Bm_td6Y3.js";import{R as Bt,B as xn,C as gs,X as ps,Y as ms,T as qt,L as vn,a as Ps,b as ba,c as Nt,P as jr,d as Tr,e as kr}from"./vendor-charts-Cddnk1Vn.js";function hs(e){return e instanceof Ia}function Hs(e){var s;return hs(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 Sr(){const{chats:e,currentSessionId:s,currentChat:n,addMessage:a,selectSession:r,deleteSession:i,deleteSessions:l,deleteMessage:g,updateSession:p,persistSessionTitle:m,pinSession:c,unpinSession:u,loadChats:f}=Le(Fa(j=>({chats:j.chats,currentSessionId:j.currentSessionId,currentChat:Aa(j),addMessage:j.addMessage,selectSession:j.selectSession,deleteSession:j.deleteSession,deleteSessions:j.deleteSessions,deleteMessage:j.deleteMessage,updateSession:j.updateSession,persistSessionTitle:j.persistSessionTitle,pinSession:j.pinSession,unpinSession:j.unpinSession,loadChats:j.loadChats}))),D=Le(Ra(s)),y=o.useMemo(()=>(n==null?void 0:n.messages)||[],[n]),d=o.useMemo(()=>e.filter(j=>j.pinned),[e]),I=o.useMemo(()=>e.filter(j=>!j.pinned),[e]),E=e.length;return{chats:e,currentSessionId:s,currentChat:n,isProcessing:D,baseMessages:y,pinnedChats:d,unpinnedChats:I,chatCount:E,addMessage:a,deleteMessage:g,selectSession:r,deleteSession:i,deleteSessions:l,pinSession:c,unpinSession:u,updateSession:p,persistSessionTitle:m,loadChats:f}}function _r(e){const s=Le(f=>f.addChat),n=Le(f=>f.lastSelectedPromptId),a=Le(f=>f.systemPrompts),r=fn.getInstance(),i=o.useCallback(async(f,D)=>{var E,j;const y=a.find(w=>w.id===n),d=(y==null?void 0:y.id)||(a.length>0?((E=a.find(w=>w.id==="general_assistant"))==null?void 0:E.id)||a[0].id:""),I={title:f||"New Session",createdAt:Date.now(),messages:[],config:{systemPromptId:d,baseSystemPrompt:(y==null?void 0:y.content)||(a.length>0?((j=a.find(w=>w.id==="general_assistant"))==null?void 0:j.content)||a[0].content:""),lastUsedEnhancedPrompt:null,...nt.getState().isProviderModelRefEnabled()?{model_ref:nt.getState().selectedModelRef}:{}},...D};await s(I)},[s,n,a]),l=o.useCallback(async f=>{ut("[ChatOps]","[useChatOperations] createChatWithSystemPrompt started with prompt:",f);const D={title:`New Session - ${f.name}`,createdAt:Date.now(),messages:[],config:{systemPromptId:f.id,baseSystemPrompt:f.content,lastUsedEnhancedPrompt:null}};ut("[ChatOps]","[useChatOperations] Calling addChat with newChatData.config:",D.config),await s(D)},[s]),g=o.useCallback(f=>{const D=e.chats.find(y=>y.id===f);D&&(D.pinned?e.unpinSession(f):e.pinSession(f))},[e]),p=o.useCallback((f,D)=>{e.updateSession(f,{title:D})},[e]),m=o.useCallback(async()=>{await r.cleanupSessions("empty",!0),await Le.getState().loadChats()},[r]),c=o.useCallback(async()=>{await r.cleanupSessions("all",!0),await Le.getState().loadChats()},[r]),u=o.useCallback(async()=>{await r.cleanupSessions("all",!1),await Le.getState().loadChats()},[r]);return{createNewChat:i,createChatWithSystemPrompt:l,toggleChatPin:g,updateChatTitle:p,deleteEmptyChats:m,deleteAllUnpinnedChats:c,deleteAllChats:u}}function wr(e,s){const n=o.useMemo(()=>e.baseMessages,[e.baseMessages]),a=o.useCallback(async()=>{var m;if(!e.currentSessionId||!e.currentChat)return;const r=[...e.baseMessages];if(r.length===0)return;const i=r[r.length-1];let l=r;if((i==null?void 0:i.role)==="assistant"){if(!(await e.deleteMessage(e.currentSessionId,i.id)).success)return;l=r.slice(0,-1)}const g=[...l].reverse().find(c=>c.role==="user");if(!g)return;const p="content"in g?g.content:g.displayText;typeof p=="string"&&await((m=s==null?void 0:s.onRetry)==null?void 0:m.call(s,p))},[e,s]);return{currentMessages:n,retryLastMessage:a}}const Cr=()=>{const e=Sr(),s=_r(e),n=za({sessionId:e.currentSessionId,addMessage:e.addMessage,updateSession:e.updateSession}),a=wr(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:vs}=ue,{useToken:Mr}=Se,Er=({httpProxy:e,httpsProxy:s,onHttpProxyChange:n,onHttpsProxyChange:a,onReload:r,onSave:i,isLoading:l})=>{const{t:g}=re(),{token:p}=Mr(),m=xt(x=>x.proxyAuthStatus),c=xt(x=>x.isLoadingProxyAuthStatus),u=xt(x=>x.loadProxyAuthStatus),f=xt(x=>x.applyProxyAuth),D=xt(x=>x.clearProxyAuth),[y,d]=o.useState({username:"",password:""}),[I,E]=o.useState(!1);o.useEffect(()=>{u()},[u]);const j=async()=>{const x=y.username.trim();if(x){E(!0);try{await f({username:x,password:y.password}),d({username:"",password:""})}catch(v){console.error("Failed to apply proxy auth:",v)}finally{E(!1)}}},w=async()=>{E(!0);try{await D()}catch(x){console.error("Failed to clear proxy auth:",x)}finally{E(!1)}};return t.jsx(V,{size:"small",title:t.jsx(vs,{strong:!0,children:g("settings.networkCard.title")}),className:"lotus-settings-card",children:t.jsxs(O,{direction:"vertical",size:p.marginSM,style:{width:"100%"},children:[t.jsx(Ie,{message:g("settings.networkCard.guideTip"),type:"info",showIcon:!0}),t.jsxs(O,{direction:"vertical",size:p.marginXXS,style:{width:"100%"},children:[t.jsx(vs,{type:"secondary",children:g("settings.networkCard.httpProxy")}),t.jsx(B,{"data-testid":"proxy-url",style:{width:"100%"},value:e,onChange:x=>n(x.target.value),placeholder:g("settings.networkCard.proxyPlaceholder"),disabled:l})]}),t.jsxs(O,{direction:"vertical",size:p.marginXXS,style:{width:"100%"},children:[t.jsx(vs,{type:"secondary",children:g("settings.networkCard.httpsProxy")}),t.jsx(B,{style:{width:"100%"},value:s,onChange:x=>a(x.target.value),placeholder:g("settings.networkCard.proxyPlaceholder"),disabled:l})]}),t.jsx(V,{size:"small",title:g("settings.networkCard.proxyAuthTitle"),className:"lotus-settings-card",style:{marginTop:p.marginSM},children:m!=null&&m.configured?t.jsxs(O,{direction:"vertical",style:{width:"100%"},children:[t.jsx(Ie,{type:"success",message:g("settings.networkCard.proxyConfiguredForUser",{username:m.username??""}),showIcon:!0}),t.jsx(R,{onClick:w,loading:I||c,danger:!0,children:g("settings.networkCard.clearCredentials")})]}):t.jsxs(O,{direction:"vertical",size:p.marginXS,style:{width:"100%"},children:[t.jsx(B,{placeholder:g("settings.networkCard.username"),value:y.username,onChange:x=>d(v=>({...v,username:x.target.value}))}),t.jsx(B.Password,{placeholder:g("settings.networkCard.password"),value:y.password,onChange:x=>d(v=>({...v,password:x.target.value}))}),t.jsx(R,{type:"primary",onClick:j,loading:I||c,disabled:!y.username.trim(),children:g("settings.networkCard.apply")})]})}),t.jsx(vs,{type:"secondary",style:{fontSize:p.fontSizeSM},children:g("settings.networkCard.credentialsStorageNote")}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:p.marginSM},children:[t.jsx(R,{onClick:()=>Promise.resolve(r()).finally(()=>u({force:!0})),disabled:l,children:g("settings.networkCard.reload")}),t.jsx(R,{"data-testid":"save-proxy-settings",type:"primary",onClick:()=>Promise.resolve(i()).finally(()=>u({force:!0})),disabled:l,children:g("settings.networkCard.save")})]})]})})};function xa(e){return typeof e=="object"&&e!==null&&"errorFields"in e}const{Text:Pr}=ue,{useToken:Dr}=Se,Ir=({msgApi:e})=>{const{t:s}=re(),{token:n}=Dr(),[a]=b.useForm(),[r,i]=o.useState(!1),[l,g]=o.useState(!1),[p,m]=o.useState(!1),[c,u]=o.useState(!1),[f,D]=o.useState(null),y=p&&!c,d=o.useMemo(()=>s(p?c?"settings.configTab.accessPassword.helperLocalBypass":"settings.configTab.accessPassword.helperRemote":"settings.configTab.accessPassword.helperNotEnabled"),[c,p,s]),I=o.useCallback(async()=>{i(!0),D(null);try{const j=await Re.getAccessStatus();m(j.password_enabled),u(j.local_bypass)}catch(j){const w=j instanceof Error?j.message:s("settings.configTab.accessPassword.loadStatusFailed","Failed to load access status");D(w)}finally{i(!1)}},[s]);o.useEffect(()=>{I()},[I]);const E=async()=>{var j;try{const w=await a.validateFields();g(!0),await Re.updateAccessPassword({current_password:((j=w.currentPassword)==null?void 0:j.trim())||void 0,new_password:w.newPassword.trim()}),e.success(s(p?"settings.configTab.accessPassword.updated":"settings.configTab.accessPassword.enabled")),a.resetFields(),await I()}catch(w){if(xa(w))return;const x=w instanceof Error?w.message:s("settings.configTab.accessPassword.updateFailed","Failed to update access password");e.error(x)}finally{g(!1)}};return t.jsx(V,{size:"small",className:"lotus-settings-card",title:t.jsx(Pr,{strong:!0,children:s("settings.configTab.accessPasswordTitle")}),children:t.jsxs(O,{direction:"vertical",size:n.marginMD,style:{width:"100%"},children:[t.jsx(Ie,{type:p?"info":"warning",showIcon:!0,message:s(p?"settings.configTab.accessPassword.statusEnabled":"settings.configTab.accessPassword.statusDisabled"),description:d}),f?t.jsx(Ie,{type:"error",showIcon:!0,message:f}):null,t.jsxs(b,{form:a,layout:"vertical",disabled:r||l,children:[y?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(B.Password,{autoComplete:"current-password"})}):null,t.jsx(b.Item,{label:s(p?"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(B.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:j})=>({validator(w,x){return!x||j("newPassword")===x?Promise.resolve():Promise.reject(new Error(s("settings.configTab.accessPassword.validation.passwordMismatch")))}})],children:t.jsx(B.Password,{autoComplete:"new-password"})}),t.jsx(R,{type:"primary",loading:l,onClick:()=>void E(),children:s(p?"settings.configTab.accessPassword.updateAction":"settings.configTab.accessPassword.enableAction")})]})]})})},{Text:Ke}=ue,{useToken:Fr}=Se,Rn="http://127.0.0.1:9562/v1",as=e=>[...new Set(e.map(s=>s.trim()).filter(s=>s.length>0))].sort(),Ar=e=>{var n;const s=(n=e.tools)==null?void 0:n.disabled;return Array.isArray(s)?as(s.filter(a=>typeof a=="string")):[]},Rr=({msgApi:e,locale:s,onLocaleChange:n})=>{const{t:a}=re(),{token:r}=Fr(),[i,l]=o.useState({http_proxy:"",https_proxy:"",memory:{auto_dream_enabled:!1},subagents:{}}),[g,p]=o.useState(Rn),[m,c]=o.useState([]),[u,f]=o.useState([]),[D,y]=o.useState([]),[d,I]=o.useState(!1),[E,j]=o.useState(!1),w=o.useCallback(async()=>{var $,ee;I(!0);try{const[se,le]=await Promise.all([Re.getBambooConfig(),Re.getBambooTools()]);l({http_proxy:se.http_proxy||"",https_proxy:se.https_proxy||"",memory:{auto_dream_enabled:(($=se.memory)==null?void 0:$.auto_dream_enabled)??!1},subagents:{max_concurrent:(ee=se.subagents)==null?void 0:ee.max_concurrent}});const Q=Ar(se);f(Q),y(Q),c(as(le.tools||[]))}catch(se){console.error("Failed to load config:",se),e.error(a("settings.configTab.loadConfigFailed"))}finally{I(!1)}},[e,a]);o.useEffect(()=>{w()},[w]);const x=$=>{l(ee=>({...ee,http_proxy:$}))},v=$=>{l(ee=>({...ee,https_proxy:$}))},L=$=>{l(ee=>({...ee,memory:{...ee.memory,auto_dream_enabled:$}}))},A=$=>{l(ee=>({...ee,subagents:{...ee.subagents,max_concurrent:$!==null&&Number.isFinite($)&&$>0?$:void 0}}))},U=async $=>{var ee,se;I(!0);try{let le;$==="network"?le={http_proxy:i.http_proxy,https_proxy:i.https_proxy}:$==="memory"?le={memory:{auto_dream_enabled:i.memory.auto_dream_enabled}}:le={subagents:{max_concurrent:i.subagents.max_concurrent}};const Q=await Re.validateBambooConfigPatch(le);if(!Q.valid){const h=((se=(ee=Q.errors)==null?void 0:ee.proxy)==null?void 0:se[0])??Object.values(Q.errors||{}).flat().filter(Boolean)[0];e.error((h==null?void 0:h.message)||a("settings.configTab.invalidConfig"));return}await Re.setBambooConfig(le),e.success(a("settings.configTab.saveConfigSuccess"))}catch(le){console.error("Failed to save config:",le);const Q=le instanceof Error&&le.message.trim()?le.message:a("settings.configTab.saveConfigFailed");e.error(Q)}finally{I(!1)}},ie=async()=>{e.success(a("settings.configTab.backendSaved"))},H=()=>{p(Rn),e.success(a("settings.configTab.backendResetDefault"))},C=($,ee)=>{f(se=>{const le=new Set(se);return ee?le.delete($):le.add($),as([...le])})},k=async()=>{j(!0);try{const $=await Re.getBambooTools();c(as($.tools||[])),e.success(a("settings.configTab.toolsReloadSuccess"))}catch($){console.error("Failed to reload tools:",$),e.error(a("settings.configTab.toolsLoadFailed"))}finally{j(!1)}},M=async()=>{j(!0);try{const $=as(u);await Re.setBambooConfig({tools:{disabled:$}}),f($),y($),e.success(a("settings.configTab.toolsSaveSuccess"))}catch($){console.error("Failed to save tool settings:",$),e.error(a("settings.configTab.toolsSaveFailed"))}finally{j(!1)}},S=JSON.stringify(u)!==JSON.stringify(D),G=new Set(u);return t.jsx(ls,{spinning:d,tip:a("settings.common.loading"),children:t.jsx(Es,{items:[{key:"general",label:a("settings.configTab.tabs.general"),children:t.jsxs(O,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[t.jsx(Er,{httpProxy:i.http_proxy,httpsProxy:i.https_proxy,onHttpProxyChange:x,onHttpsProxyChange:v,onReload:w,onSave:()=>U("network"),isLoading:d}),t.jsx(V,{size:"small",className:"lotus-settings-card",title:t.jsx(Ke,{strong:!0,children:a("settings.configTab.language")}),children:t.jsx(ae,{value:s,style:{width:260},options:[{label:a("settings.configTab.languageEnglish"),value:"en-US"},{label:a("settings.configTab.languageChinese"),value:"zh-CN"},{label:a("settings.configTab.languageTraditionalChinese"),value:"zh-TW"},{label:a("settings.configTab.languageFrench"),value:"fr-FR"},{label:a("settings.configTab.languageJapanese"),value:"ja-JP"},{label:a("settings.configTab.languageHindi"),value:"hi-IN"}],onChange:$=>n($)})}),t.jsx(V,{size:"small",className:"lotus-settings-card",title:t.jsx(Ke,{strong:!0,children:a("settings.configTab.memoryTitle")}),children:t.jsxs(O,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[t.jsx(Ke,{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(Ke,{strong:!0,children:a("settings.configTab.autoDreamEnabled")}),t.jsx("div",{children:t.jsx(Ke,{type:"secondary",style:{fontSize:r.fontSizeSM},children:a("settings.configTab.autoDreamEnabledHint")})})]}),t.jsx(pe,{"data-testid":"auto-dream-toggle",checked:i.memory.auto_dream_enabled,onChange:L})]}),t.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:t.jsx(R,{"data-testid":"save-memory-settings",type:"primary",onClick:()=>U("memory"),loading:d,children:a("settings.configTab.save")})})]})}),t.jsx(V,{size:"small",className:"lotus-settings-card",title:t.jsx(Ke,{strong:!0,children:a("settings.configTab.subagentsTitle")}),children:t.jsxs(O,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[t.jsx(Ke,{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(Ke,{strong:!0,children:a("settings.configTab.subagentMaxConcurrent")}),t.jsx("div",{children:t.jsx(Ke,{type:"secondary",style:{fontSize:r.fontSizeSM},children:a("settings.configTab.subagentMaxConcurrentHint")})})]}),t.jsx(Ee,{"data-testid":"subagent-max-concurrent",style:{width:120},min:1,step:1,precision:0,placeholder:"8",value:i.subagents.max_concurrent??null,onChange:$=>A(typeof $=="number"?$:null)})]}),t.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:t.jsx(R,{"data-testid":"save-subagent-settings",type:"primary",onClick:()=>U("subagents"),loading:d,children:a("settings.configTab.save")})})]})}),t.jsx(V,{size:"small",title:t.jsx(Ke,{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(B,{style:{width:"100%"},value:g,onChange:$=>p($.target.value),placeholder:a("settings.configTab.backendApiPlaceholder")})}),t.jsx(Ke,{type:"secondary",style:{fontSize:r.fontSizeSM},children:a("settings.configTab.backendApiHint")}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:r.marginSM},children:[t.jsx(R,{"data-testid":"reset-to-defaults",onClick:H,children:a("settings.configTab.resetToDefault")}),t.jsx(R,{"data-testid":"save-api-settings",type:"primary",onClick:ie,children:a("settings.configTab.save")})]})]})}),t.jsx(Ir,{msgApi:e})]})},{key:"tools",label:a("settings.configTab.tabs.tools"),children:t.jsx(V,{size:"small",title:t.jsx(Ke,{strong:!0,children:a("settings.configTab.toolsTitle")}),children:t.jsxs(O,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[t.jsx(Ke,{type:"secondary",children:a("settings.configTab.toolsDescription")}),m.length===0?t.jsx(Ie,{type:"info",showIcon:!0,message:a("settings.configTab.toolsEmpty")}):t.jsx(He,{bordered:!0,dataSource:m,renderItem:$=>t.jsx(He.Item,{actions:[t.jsx(pe,{checked:!G.has($),onChange:ee=>C($,ee)},`${$}-switch`)],children:t.jsx(Ke,{code:!0,children:$})})}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:r.marginSM},children:[t.jsx(R,{onClick:k,loading:E,children:a("settings.configTab.reloadTools")}),t.jsx(R,{type:"primary",onClick:M,loading:E,disabled:!S,children:a("settings.configTab.save")})]})]})})}]})})},{Title:zr,Text:Ks}=ue,{useToken:Lr}=Se,Or=()=>{const{t:e}=re(),{token:s}=Lr(),n=La(),a=Oa(),r=Na(),[i]=b.useForm(),l=Sn.useRef(n);Sn.useEffect(()=>{l.current!==n&&(i.setFieldsValue(n),l.current=n)},[n,i]);const g=m=>{l.current={...l.current,...m},a(m)},p=()=>{r(),i.resetFields()};return t.jsxs("div",{style:{padding:"24px",maxWidth:"1200px",margin:"0 auto"},children:[t.jsx(zr,{level:3,style:{marginBottom:"8px"},children:e("settings.mermaidTab.title")}),t.jsx(Ks,{type:"secondary",style:{display:"block",marginBottom:"24px"},children:e("settings.mermaidTab.description")}),t.jsxs(b,{form:i,layout:"vertical",initialValues:n,onValuesChange:g,children:[t.jsxs(V,{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(we,{title:e("settings.mermaidTab.themeTooltip"),children:t.jsx(We,{style:{color:s.colorTextSecondary}})})]}),children:t.jsxs(ae,{children:[t.jsx(ae.Option,{value:"default",children:e("settings.mermaidTab.themeOptions.default")}),t.jsx(ae.Option,{value:"neutral",children:e("settings.mermaidTab.themeOptions.neutral")}),t.jsx(ae.Option,{value:"dark",children:e("settings.mermaidTab.themeOptions.dark")}),t.jsx(ae.Option,{value:"forest",children:e("settings.mermaidTab.themeOptions.forest")}),t.jsx(ae.Option,{value:"base",children:e("settings.mermaidTab.themeOptions.base")})]})})})}),t.jsxs(Ks,{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(V,{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(we,{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(we,{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(we,{title:e("settings.mermaidTab.responsiveWidthTooltip"),children:t.jsx(We,{style:{color:s.colorTextSecondary}})})]}),valuePropName:"checked",children:t.jsx(pe,{})})]}),t.jsx(V,{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(we,{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(we,{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(we,{title:e("settings.mermaidTab.flowchartCurveTypeTooltip"),children:t.jsx(We,{style:{color:s.colorTextSecondary}})})]}),children:t.jsxs(ae,{children:[t.jsx(ae.Option,{value:"basis",children:e("settings.mermaidTab.flowchartCurveOptions.basis")}),t.jsx(ae.Option,{value:"linear",children:e("settings.mermaidTab.flowchartCurveOptions.linear")}),t.jsx(ae.Option,{value:"cardinal",children:e("settings.mermaidTab.flowchartCurveOptions.cardinal")})]})})})]})}),t.jsx(V,{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(we,{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(we,{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(we,{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(we,{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(V,{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(we,{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(we,{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(tr,{}),onClick:p,children:e("settings.mermaidTab.resetToDefaults")})}),t.jsx(Pe,{}),t.jsx(V,{title:e("settings.mermaidTab.previewTitle"),styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsx(Ks,{type:"secondary",children:e("settings.mermaidTab.previewDescription")})})]})]})},Nr=o.lazy(()=>gn(()=>Promise.resolve().then(()=>Vl),void 0,import.meta.url)),{Text:wt}=ue,{useToken:Vr}=Se,$r=({promptEnhancement:e,onPromptEnhancementChange:s,mermaidEnhancementEnabled:n,taskEnhancementEnabled:a,showCopilotConclusionWithOptionsEnhancement:r,copilotConclusionWithOptionsEnhancementEnabled:i,onMermaidToggle:l,onTaskToggle:g,onCopilotConclusionWithOptionsToggle:p,onSaveEnhancement:m})=>{const{t:c}=re(),{token:u}=Vr(),f=u.marginLG;return t.jsxs(W,{vertical:!0,gap:f,children:[t.jsx(V,{size:"small",className:"lotus-settings-card",children:t.jsx(o.Suspense,{fallback:t.jsx(ls,{size:"small"}),children:t.jsx(Nr,{})})}),t.jsx(V,{size:"small",className:"lotus-settings-card",children:t.jsxs(O,{direction:"vertical",size:u.marginXS,style:{width:"100%"},children:[t.jsx(wt,{strong:!0,children:c("settings.promptsTab.title")}),t.jsxs(W,{align:"center",gap:u.marginSM,children:[t.jsx(wt,{strong:!0,children:c("settings.promptsTab.mermaidEnhancement")}),t.jsx(pe,{checked:n,onChange:l})]}),t.jsxs(W,{align:"center",gap:u.marginSM,children:[t.jsx(wt,{strong:!0,children:c("settings.promptsTab.taskListRules")}),t.jsx(pe,{checked:a,onChange:g})]}),r&&t.jsxs(O,{direction:"vertical",size:u.marginXXS,style:{width:"100%"},children:[t.jsxs(W,{align:"center",gap:u.marginSM,children:[t.jsx(wt,{strong:!0,children:c("settings.promptsTab.copilotConclusionWithOptionsBeforeFinish")}),t.jsx(pe,{checked:i,onChange:p})]}),t.jsx(wt,{type:"secondary",style:{fontSize:u.fontSizeSM},children:c("settings.promptsTab.copilotConclusionWithOptionsBeforeFinishDescription",{defaultValue:Va()})})]}),t.jsx(B.TextArea,{rows:6,placeholder:c("settings.promptsTab.enhancementPlaceholder"),value:e,onChange:D=>s(D.target.value)}),t.jsx(W,{justify:"flex-end",children:t.jsx(R,{type:"primary",onClick:m,children:c("settings.promptsTab.saveEnhancement")})}),t.jsx(wt,{type:"secondary",style:{fontSize:u.fontSizeSM},children:c("settings.promptsTab.description")})]})}),n&&t.jsx(Fs,{size:"small",items:[{key:"mermaid",label:t.jsx(wt,{strong:!0,children:c("settings.mermaidTab.title")}),children:t.jsx(Or,{})}]})]})},{Text:ft}=ue,{useToken:Br}=Se,qr=({themeMode:e,onThemeModeChange:s,vdiSafeMode:n,onVdiSafeModeToggle:a,onClearLocalStorage:r,onResetApp:i,isResetting:l,darkModeKey:g})=>{const{t:p}=re(),{token:m}=Br();return t.jsx(V,{size:"small",className:"lotus-settings-card",children:t.jsxs(O,{direction:"vertical",size:m.marginSM,style:{width:"100%"},children:[t.jsxs(W,{align:"center",justify:"space-between",gap:m.marginSM,children:[t.jsx(ft,{strong:!0,children:p("settings.appTab.runningVersion","Running version")}),t.jsxs(ft,{code:!0,"data-testid":"settings-app-version",children:["v",ma]})]}),t.jsx(ft,{type:"secondary",style:{fontSize:m.fontSizeSM},children:p("settings.appTab.runningVersionDesc","This is the currently running Lotus frontend version.")}),t.jsxs(W,{align:"center",gap:m.marginSM,children:[t.jsx(ft,{strong:!0,children:p("settings.appTab.darkMode")}),t.jsx(pe,{"data-testid":"dark-mode-toggle",checked:e==="dark",onChange:c=>{const u=c?"dark":"light";s(u),localStorage.setItem(g,u)}})]}),t.jsxs(W,{align:"center",gap:m.marginSM,children:[t.jsx(ft,{strong:!0,children:p("settings.appTab.vdiSafeMode","Graphics compatibility mode")}),t.jsx(pe,{"data-testid":"vdi-safe-mode-toggle",checked:n,onChange:a})]}),t.jsx(ft,{type:"secondary",style:{fontSize:m.fontSizeSM},children:p("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(sr,{}),onClick:()=>{vr(),window.location.reload()},children:p("settings.appTab.resetStepReplayGuide")}),t.jsx(Tt,{title:p("settings.appTab.clearLocalStorageTitle"),description:p("settings.appTab.clearLocalStorageDescription"),onConfirm:r,okText:p("settings.appTab.confirmClear"),cancelText:p("settings.appTab.cancel"),placement:"top",children:t.jsx(R,{danger:!0,block:!0,icon:t.jsx(kt,{}),children:p("settings.appTab.clearLocalStorageButton")})}),t.jsx(Pe,{style:{margin:`${m.marginSM}px 0`}}),t.jsxs(W,{align:"center",gap:m.marginSM,children:[t.jsx(nr,{style:{color:m.colorError}}),t.jsx(ft,{strong:!0,style:{color:m.colorError},children:p("settings.appTab.dangerZone")})]}),t.jsx(ft,{type:"secondary",style:{fontSize:m.fontSizeSM},children:p("settings.appTab.dangerDescription")}),t.jsx(Tt,{title:p("settings.appTab.resetApplicationTitle"),description:t.jsxs("div",{children:[t.jsx("p",{children:p("settings.appTab.resetApplicationIntro")}),t.jsxs("ul",{style:{margin:0,paddingLeft:16},children:[t.jsx("li",{children:p("settings.appTab.resetStepDeleteAllSessions")}),t.jsx("li",{children:p("settings.appTab.resetStepClearStorage")}),t.jsx("li",{children:p("settings.appTab.resetStepResetConfig")}),t.jsx("li",{children:p("settings.appTab.resetStepSetupFlow")}),t.jsx("li",{children:p("settings.appTab.resetStepReload")})]})]}),onConfirm:i,okText:p("settings.appTab.resetConfirm"),cancelText:p("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(ar,{}),loading:l,children:p("settings.appTab.resetButton")})})]})})},{Text:Ct}=ue,{useToken:Ur}=Se,zn=[{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,}"}],Hr=(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:de.t("settings.keywordMaskingTab.invalidRegexPattern")}}},Kr=()=>{const{t:e}=re(),{message:s}=rt.useApp(),{token:n}=Ur(),[a,r]=o.useState([]),[i,l]=o.useState(!1),[g,p]=o.useState(null),[m,c]=o.useState(""),[u,f]=o.useState("exact"),[D,y]=o.useState(!0),[d,I]=o.useState(),[E,j]=o.useState("My token is sk-123"),w=o.useCallback(async()=>{try{l(!0);const M=await lt.getInstance().getKeywordMaskingConfig();r(M.entries)}catch(k){s.error(e("settings.keywordMaskingTab.loadFailed")),console.error(k)}finally{l(!1)}},[s,e]);o.useEffect(()=>{w()},[w]);const x=async k=>{try{const M=lt.getInstance(),S=await M.validateKeywordEntries(k);if(!S.valid&&S.errors){const $=S.errors.map(ee=>`Entry ${ee.index+1}: ${ee.message}`).join("; ");return s.error(`${e("settings.keywordMaskingTab.validationFailedPrefix")}: ${$}`),!1}const G=await M.updateKeywordMaskingConfig(k);return r(G.entries),s.success(e("settings.keywordMaskingTab.saveSuccess")),!0}catch(M){return s.error(M instanceof Error?M.message:e("settings.keywordMaskingTab.saveFailed")),!1}},v=async()=>{const k={pattern:"",match_type:"exact",enabled:!0},M=[...a,k];r(M),p(M.length-1),c(""),f("exact"),y(!0),I(void 0)},L=k=>{const M=a[k];p(k),c(M.pattern),f(M.match_type),y(M.enabled),I(void 0)},A=async()=>{if(g===null)return;if(!m.trim()){s.error(e("settings.keywordMaskingTab.patternRequired"));return}const k=[...a];k[g]={pattern:m.trim(),match_type:u,enabled:D},await x(k)&&p(null)},U=()=>{var k;g!==null&&!((k=a[g])!=null&&k.pattern)&&r(a.filter((M,S)=>S!==g)),p(null)},ie=async k=>{const M=a.filter((S,G)=>G!==k);await x(M)},H=async(k,M)=>{const S=[...a];S[k]={...S[k],enabled:M},await x(S)},C=Hr(E,m,u);return t.jsx(V,{className:"lotus-settings-card",title:e("settings.keywordMaskingTab.title"),extra:t.jsx(R,{"data-testid":"add-keyword",type:"primary",icon:t.jsx(at,{}),onClick:v,loading:i,children:e("settings.keywordMaskingTab.addKeyword")}),children:t.jsxs(O,{direction:"vertical",style:{width:"100%"},size:"large",children:[t.jsx(Ct,{type:"secondary",children:e("settings.keywordMaskingTab.description")}),t.jsx(He,{loading:i,dataSource:a,locale:{emptyText:e("settings.keywordMaskingTab.empty")},renderItem:(k,M)=>t.jsx(He.Item,{style:{backgroundColor:n.colorFillAlter,marginBottom:8,borderRadius:n.borderRadius,padding:12},actions:g===M?[t.jsx(R,{"data-testid":"save-keyword",type:"primary",icon:t.jsx(As,{}),onClick:A,"aria-label":e("settings.keywordMaskingTab.save")},"save"),t.jsx(R,{onClick:U,children:e("settings.keywordMaskingTab.cancel")},"cancel")]:[t.jsx(R,{icon:t.jsx(Vt,{}),onClick:()=>L(M),"aria-label":e("settings.keywordMaskingTab.edit")},"edit"),t.jsx(R,{"data-testid":`delete-keyword-${M}`,danger:!0,icon:t.jsx(kt,{}),onClick:()=>ie(M),"aria-label":e("settings.keywordMaskingTab.delete")},"delete")],children:t.jsx(W,{vertical:!0,style:{width:"100%"},gap:8,children:g===M?t.jsxs(t.Fragment,{children:[t.jsx(B,{"data-testid":"keyword-pattern-input",placeholder:e("settings.keywordMaskingTab.patternPlaceholder"),value:m,onChange:S=>c(S.target.value),autoFocus:!0}),t.jsxs(W,{gap:8,align:"center",wrap:"wrap",children:[t.jsx(ae,{"data-testid":"keyword-examples-select","aria-label":e("settings.keywordMaskingTab.examples"),placeholder:e("settings.keywordMaskingTab.examples"),value:d,onChange:S=>{I(S);const G=zn.find($=>$.value===S);G&&(c(G.pattern),f(G.match_type))},options:zn.map(S=>({value:S.value,label:e(S.labelKey)})),style:{minWidth:220}}),t.jsx(ae,{value:u,onChange:f,options:[{value:"exact",label:e("settings.keywordMaskingTab.exactMatch")},{value:"regex",label:e("settings.keywordMaskingTab.regexPattern")}],style:{width:150}}),t.jsx(pe,{checked:D,onChange:y})]}),t.jsxs(W,{vertical:!0,gap:6,children:[t.jsx(Ct,{type:"secondary",children:e("settings.keywordMaskingTab.sampleText")}),t.jsx(B,{placeholder:e("settings.keywordMaskingTab.sampleTextPlaceholder"),value:E,onChange:S=>j(S.target.value)}),t.jsx(Ct,{type:"secondary",children:e("settings.keywordMaskingTab.maskedPreview")}),t.jsx(B,{readOnly:!0,value:C.masked,status:C.error?"error":void 0}),C.error&&t.jsx(Ct,{type:"danger",children:C.error})]})]}):t.jsxs(W,{justify:"space-between",align:"center",children:[t.jsxs(W,{vertical:!0,gap:4,children:[t.jsx(Ct,{strong:!0,children:k.pattern||e("settings.keywordMaskingTab.emptyPattern")}),t.jsxs(W,{gap:8,children:[t.jsx(Ct,{type:"secondary",style:{fontSize:12},children:k.match_type==="regex"?e("settings.keywordMaskingTab.regexPattern"):e("settings.keywordMaskingTab.exactMatch")}),!k.enabled&&t.jsx(Ct,{type:"warning",style:{fontSize:12},children:e("settings.keywordMaskingTab.disabled")})]})]}),t.jsx(pe,{checked:k.enabled,onChange:S=>H(M,S),size:"small"})]})})})})]})})},{Text:Ln,Paragraph:Wr}=ue,Gr=["Bash(rm -rf *)","Bash(git push *)","Bash(sudo *)","Write(/etc/**)"],Xr=()=>{const{t:e}=re(),{message:s}=rt.useApp(),[n,a]=o.useState([]),[r,i]=o.useState(""),[l,g]=o.useState(!1),[p,m]=o.useState(!1),c=o.useCallback(async()=>{try{g(!0),a(await me.getPermissionAskRules())}catch(y){s.error(e("settings.permissionsTab.loadFailed")),console.error(y)}finally{g(!1)}},[s,e]);o.useEffect(()=>{c()},[c]);const u=o.useCallback(async y=>{try{m(!0);const d=await me.updatePermissionAskRules(y);return a(d),s.success(e("settings.permissionsTab.saveSuccess")),!0}catch(d){return s.error(d instanceof Error?d.message:e("settings.permissionsTab.saveFailed")),!1}finally{m(!1)}},[s,e]),f=o.useCallback(async y=>{const d=y.trim();if(!d)return;if(n.includes(d)){s.info(e("settings.permissionsTab.duplicate"));return}await u([...n,d])&&i("")},[n,u,s,e]),D=o.useCallback(y=>u(n.filter(d=>d!==y)),[n,u]);return t.jsx(V,{className:"lotus-settings-card",title:e("settings.permissionsTab.title"),extra:t.jsx(R,{type:"primary",icon:t.jsx(at,{}),loading:p,disabled:!r.trim(),onClick:()=>void f(r),children:e("settings.permissionsTab.add")}),children:t.jsxs(O,{direction:"vertical",style:{width:"100%"},size:"large",children:[t.jsx(Wr,{type:"secondary",style:{marginBottom:0},children:e("settings.permissionsTab.description")}),t.jsx(B,{value:r,onChange:y=>i(y.target.value),onPressEnter:()=>void f(r),placeholder:e("settings.permissionsTab.placeholder"),allowClear:!0}),t.jsxs(W,{gap:8,wrap:"wrap",align:"center",children:[t.jsx(Ln,{type:"secondary",style:{fontSize:12},children:e("settings.permissionsTab.examples")}),Gr.map(y=>t.jsx(oe.CheckableTag,{checked:n.includes(y),onChange:()=>{n.includes(y)||f(y)},children:y},y))]}),t.jsx(He,{loading:l,dataSource:n,locale:{emptyText:e("settings.permissionsTab.empty")},renderItem:y=>t.jsx(He.Item,{actions:[t.jsx(R,{danger:!0,size:"small",icon:t.jsx(kt,{}),loading:p,onClick:()=>void D(y),"aria-label":e("settings.permissionsTab.remove")},"delete")],children:t.jsx(Ln,{code:!0,children:y})})})]})})},{Text:Rt,Paragraph:Jr}=ue,Yr=/^[A-Za-z_][A-Za-z0-9_]*$/,Zr=()=>{const{t:e}=re(),{message:s}=rt.useApp(),[n,a]=o.useState([]),[r,i]=o.useState(!1),[l,g]=o.useState(!1),[p,m]=o.useState(null),[c]=b.useForm(),u=o.useCallback(async()=>{i(!0);try{const j=await me.getEnvVars();a(j.entries)}catch{s.error(e("settings.envVars.fetchError","Failed to load environment variables"))}finally{i(!1)}},[s,e]);o.useEffect(()=>{u()},[u]);const f=async j=>{var x;const w={name:j.name.trim(),value:j.value,secret:j.secret??!1,description:((x=j.description)==null?void 0:x.trim())||void 0};try{const v=await me.upsertEnvVar(w);a(v.entries),s.success(p?e("settings.envVars.updated","Variable updated"):e("settings.envVars.created","Variable created")),I()}catch(v){s.error((v instanceof Error?v.message:void 0)||e("settings.envVars.saveError","Failed to save variable"))}},D=async j=>{try{const w=await me.deleteEnvVar(j);a(w.entries),s.success(e("settings.envVars.deleted","Variable deleted"))}catch(w){s.error((w instanceof Error?w.message:void 0)||e("settings.envVars.deleteError","Failed to delete variable"))}},y=()=>{m(null),c.resetFields(),c.setFieldsValue({secret:!1}),g(!0)},d=j=>{m(j.name),c.setFieldsValue({name:j.name,value:"",secret:j.secret,description:j.description??""}),g(!0)},I=()=>{g(!1),m(null),c.resetFields()},E=[{title:e("settings.envVars.name","Name"),dataIndex:"name",key:"name",render:j=>t.jsx(Rt,{code:!0,children:j})},{title:e("settings.envVars.value","Value"),dataIndex:"value",key:"value",render:(j,w)=>w.secret?t.jsxs(Rt,{type:"secondary",children:[t.jsx(Dn,{style:{marginRight:4}}),w.has_value?"••••••••":e("settings.envVars.notSet","(not set)")]}):t.jsx(Rt,{children:j||t.jsx(Rt,{type:"secondary",children:e("settings.envVars.empty","(empty)")})})},{title:e("settings.envVars.type","Type"),key:"secret",width:100,render:(j,w)=>w.secret?t.jsx(oe,{color:"warning",icon:t.jsx(Dn,{}),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:j=>j?t.jsx(Rt,{type:"secondary",children:j}):t.jsx(Rt,{type:"secondary",italic:!0,children:"—"})},{title:e("settings.envVars.actions","Actions"),key:"actions",width:120,render:(j,w)=>t.jsxs(O,{size:"small",children:[t.jsx(R,{type:"text",size:"small",icon:t.jsx(Vt,{}),onClick:()=>d(w),"aria-label":e("settings.envVars.edit","Edit")}),t.jsx(Tt,{title:e("settings.envVars.deleteConfirm","Delete this variable?"),onConfirm:()=>D(w.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(kt,{}),"aria-label":e("settings.envVars.delete","Delete")})})]})}];return t.jsxs("div",{style:{maxWidth:900},children:[t.jsxs(V,{className:"lotus-settings-card",title:e("settings.envVars.title","Environment Variables"),extra:t.jsx(R,{type:"primary",icon:t.jsx(at,{}),onClick:y,children:e("settings.envVars.addButton","Add Variable")}),children:[t.jsx(Jr,{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(et,{dataSource:n,columns:E,rowKey:"name",size:"small",pagination:!1,loading:r,locale:{emptyText:e("settings.envVars.noVars","No environment variables configured")}})]}),t.jsx(Xe,{title:p?e("settings.envVars.editTitle","Edit Variable"):e("settings.envVars.addTitle","Add Environment Variable"),open:l,onCancel:I,onOk:()=>c.submit(),okText:e("settings.envVars.save","Save"),cancelText:e("settings.envVars.cancel","Cancel"),destroyOnClose:!0,children:t.jsxs(b,{form:c,layout:"vertical",onFinish:f,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:Yr,message:e("settings.envVars.nameInvalid","Must start with a letter or underscore, followed by letters, digits, or underscores")}],children:t.jsx(B,{placeholder:"GITHUB_TOKEN",disabled:p!==null,autoFocus:p===null})}),t.jsx(b.Item,{name:"value",label:e("settings.envVars.value","Value"),rules:[{required:p===null,message:e("settings.envVars.valueRequired","Value is required for new variables")}],extra:p?e("settings.envVars.valueEditHint","Leave empty to keep the existing value"):void 0,children:t.jsx(B.Password,{placeholder:p?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(pe,{})}),t.jsx(b.Item,{name:"description",label:e("settings.envVars.descriptionField","Description"),children:t.jsx(B,{placeholder:e("settings.envVars.descriptionPlaceholder","Optional description")})})]})})]})},{Text:Xt,Paragraph:Qr}=ue,Ws="****...****",ei={not_deployed:"default",deploying:"processing",running:"success",unreachable:"warning",stopped:"default",failed:"error"},ti=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`},si=3e4,ni=()=>{const{t:e}=re(),{message:s}=rt.useApp(),[n,a]=o.useState([]),[r,i]=o.useState([]),[l,g]=o.useState(!1),[p,m]=o.useState(!1),[c,u]=o.useState(null),[f]=b.useForm(),[D,y]=o.useState(!1),[d,I]=o.useState(null),[E,j]=o.useState(""),[w,x]=o.useState(!1),v=b.useWatch("placement_type",f),L=b.useWatch("auth_method",f),A=o.useRef(0),U=o.useCallback(async(h=!1)=>{const F=++A.current;h||g(!0);try{const P=await me.listNodes();if(F!==A.current)return;a(P.nodes),i(P.clusters)}catch{h||s.error(e("settings.clusters.fetchError","Failed to load clusters"))}finally{h||g(!1)}},[s,e]);o.useEffect(()=>{U()},[U]),o.useEffect(()=>{const h=()=>{document.visibilityState==="visible"&&!p&&!D&&U(!0)},F=window.setInterval(h,si);return document.addEventListener("visibilitychange",h),()=>{window.clearInterval(F),document.removeEventListener("visibilitychange",h)}},[U,p,D]);const ie=o.useMemo(()=>{const h=new Map;for(const F of r)for(const P of F.node_ids)h.has(P)||h.set(P,F.name);return h},[r]),H=()=>{u(null),f.resetFields(),f.setFieldsValue({placement_type:"ssh",port:22,auth_method:"password",enabled:!0}),m(!0)},C=h=>{var X,te,ge;u(h.id);const P=h.placement.type==="ssh"?h.placement:void 0;f.setFieldsValue({label:h.label,placement_type:h.placement.type,host:P==null?void 0:P.host,port:(P==null?void 0:P.port)??22,username:P==null?void 0:P.username,auth_method:(P==null?void 0:P.auth.method)??"password",password:"",private_key:"",private_key_path:(P==null?void 0:P.auth.method)==="private_key"?P.auth.private_key_path:void 0,passphrase:"",artifact_path:(X=h.deploy)==null?void 0:X.artifact_path,default_role:(te=h.deploy)==null?void 0:te.default_role,auto_recover:((ge=h.deploy)==null?void 0:ge.auto_recover)??!1,cluster_name:(()=>{const ve=ie.get(h.id);return ve?[ve]:[]})(),enabled:h.enabled}),m(!0)},k=()=>{m(!1),u(null),f.resetFields()},M=h=>{var ge,ve;if(h.placement_type==="local")return{type:"local"};const F=c?n.find(_e=>_e.id===c):void 0,P=(F==null?void 0:F.placement.type)==="ssh"?F.placement.auth:void 0,X=(_e,Oe)=>!!_e&&!Oe;let te;if(h.auth_method==="system_ssh_config")te={method:"system_ssh_config"};else if(h.auth_method==="private_key"){const _e=(P==null?void 0:P.method)==="private_key"?P.private_key:void 0,Oe=(P==null?void 0:P.method)==="private_key"?P.passphrase:void 0;te={method:"private_key",private_key:X(_e,h.private_key)?Ws:h.private_key||void 0,private_key_path:h.private_key_path||void 0,passphrase:X(Oe,h.passphrase)?Ws:h.passphrase||void 0}}else{const _e=(P==null?void 0:P.method)==="password"?P.password:void 0;te={method:"password",password:X(_e,h.password)?Ws:h.password}}return{type:"ssh",host:((ge=h.host)==null?void 0:ge.trim())??"",port:h.port??22,username:((ve=h.username)==null?void 0:ve.trim())??"",auth:te}},S=async h=>{var P,X;const F={label:h.label.trim(),placement:M(h),enabled:h.enabled??!0,deploy:{artifact_path:((P=h.artifact_path)==null?void 0:P.trim())||void 0,default_role:((X=h.default_role)==null?void 0:X.trim())||void 0,auto_recover:h.auto_recover??!1}};try{const te=c?await me.updateNode(c,F):await me.createNode(F),ge=Array.isArray(h.cluster_name)?h.cluster_name[0]:h.cluster_name;try{await G(te.id,ge)}catch(ve){s.warning((ve instanceof Error?ve.message:void 0)||e("settings.clusters.membershipError","Node saved, but updating cluster membership failed")),k(),U();return}s.success(c?e("settings.clusters.updated","Node updated"):e("settings.clusters.created","Node created")),k(),U()}catch(te){s.error((te instanceof Error?te.message:void 0)||e("settings.clusters.saveError","Failed to save node"))}},G=async(h,F)=>{const P=F==null?void 0:F.trim();for(const te of r){const ge=te.name===P,ve=te.node_ids.includes(h);!ge&&ve&&await me.updateCluster(te.name,{name:te.name,description:te.description,node_ids:te.node_ids.filter(_e=>_e!==h)})}if(!P)return;const X=r.find(te=>te.name===P);X?X.node_ids.includes(h)||await me.updateCluster(P,{name:P,description:X.description,node_ids:[...X.node_ids,h]}):await me.createCluster({name:P,node_ids:[h]})},$=async h=>{try{await me.deleteNode(h),s.success(e("settings.clusters.deleted","Node deleted")),U()}catch(F){s.error((F instanceof Error?F.message:void 0)||e("settings.clusters.deleteError","Failed to delete node"))}},ee=async(h,F)=>{try{const P=await me.nodeAction(h,F),X=F==="test"&&P&&typeof P=="object"&&"preflight"in P?String(P.preflight??""):"";s.success(X?e("settings.clusters.testOk","Reachable: {{info}}",{info:X}):e("settings.clusters.actionOk","Action triggered")),U()}catch(P){s.error((P instanceof Error?P.message:void 0)||e("settings.clusters.actionFailed","Action failed"))}},se=async h=>{I(h),y(!0),x(!0),j("");try{const F=await me.nodeLogs(h.id,200);j(F.logs||e("settings.clusters.logsEmpty","(no log output yet)"))}catch(F){j((F instanceof Error?F.message:void 0)||e("settings.clusters.logsError","Failed to read logs"))}finally{x(!1)}},le=[{title:e("settings.clusters.label","Label"),dataIndex:"label",key:"label",render:(h,F)=>t.jsxs(O,{children:[t.jsx(rr,{}),t.jsx(Xt,{strong:!0,children:h}),!F.enabled&&t.jsx(oe,{children:e("settings.clusters.disabled","disabled")})]})},{title:e("settings.clusters.target","Target"),key:"target",render:(h,F)=>F.placement.type==="ssh"?t.jsxs(Xt,{code:!0,children:[F.placement.username,"@",F.placement.host,":",F.placement.port]}):t.jsx(oe,{color:"blue",children:e("settings.clusters.local","local")})},{title:e("settings.clusters.cluster","Cluster"),key:"cluster",render:(h,F)=>{const P=ie.get(F.id);return P?t.jsx(oe,{children:P}):t.jsx(Xt,{type:"secondary",children:"—"})}},{title:e("settings.clusters.status","Status"),key:"status",render:(h,F)=>{var ve,_e,Oe;const P=((ve=F.state)==null?void 0:ve.status)??"not_deployed",X=(_e=F.state)==null?void 0:_e.last_error,te=ti((Oe=F.state)==null?void 0:Oe.last_health),ge=t.jsx(oe,{color:ei[P],children:P.replace(/_/g," ")});return t.jsxs(O,{direction:"vertical",size:0,children:[X&&(P==="unreachable"||P==="failed")?t.jsx(we,{title:X,children:ge}):ge,te&&t.jsx(Xt,{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:(h,F)=>t.jsxs(O,{size:"small",wrap:!0,children:[t.jsx(R,{size:"small",onClick:()=>ee(F.id,"test"),children:e("settings.clusters.test","Test")}),t.jsx(R,{size:"small",type:"primary",ghost:!0,onClick:()=>ee(F.id,"deploy"),children:e("settings.clusters.deploy","Deploy")}),t.jsx(R,{size:"small",onClick:()=>ee(F.id,"stop"),children:e("settings.clusters.stop","Stop")}),t.jsx(R,{size:"small",onClick:()=>se(F),children:e("settings.clusters.logs","Logs")}),t.jsx(R,{type:"text",size:"small",icon:t.jsx(Vt,{}),onClick:()=>C(F),"aria-label":e("settings.clusters.edit","Edit")}),t.jsx(Tt,{title:e("settings.clusters.deleteConfirm","Delete this node?"),onConfirm:()=>$(F.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(kt,{}),"aria-label":e("settings.clusters.delete","Delete")})})]})}],Q=v!=="local",ye=c?n.find(h=>h.id===c):void 0;return t.jsxs("div",{style:{maxWidth:1e3},children:[t.jsxs(V,{className:"lotus-settings-card",title:e("settings.clusters.title","Remote Clusters"),extra:t.jsx(R,{type:"primary",icon:t.jsx(at,{}),onClick:H,children:e("settings.clusters.addButton","Add Node")}),children:[t.jsx(Qr,{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(et,{dataSource:n,columns:le,rowKey:"id",size:"small",pagination:!1,loading:l,locale:{emptyText:e("settings.clusters.noNodes","No nodes registered")}})]}),t.jsx(Xe,{title:c?e("settings.clusters.editTitle","Edit Node"):e("settings.clusters.addTitle","Add Node"),open:p,onCancel:k,onOk:()=>f.submit(),okText:e("settings.clusters.save","Save"),cancelText:e("settings.clusters.cancel","Cancel"),width:560,destroyOnClose:!0,children:t.jsxs(b,{form:f,layout:"vertical",onFinish:S,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(B,{placeholder:"gpu-1",autoFocus:!0})}),t.jsx(b.Item,{name:"placement_type",label:e("settings.clusters.placement","Placement"),children:t.jsx(ae,{options:[{value:"ssh",label:e("settings.clusters.ssh","SSH (remote)")},{value:"local",label:e("settings.clusters.localhost","Local (this host)")}]})}),Q&&t.jsxs(t.Fragment,{children:[t.jsxs(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(B,{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(B,{placeholder:"deploy"})}),t.jsx(b.Item,{name:"auth_method",label:e("settings.clusters.authMethod","Auth method"),children:t.jsx(ae,{options:[{value:"password",label:e("settings.clusters.password","Password")},{value:"private_key",label:e("settings.clusters.privateKey","Private key")},{value:"system_ssh_config",label:e("settings.clusters.systemSsh","Use host's SSH config")}]})}),L==="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(B.Password,{visibilityToggle:!0,placeholder:ye?e("settings.clusters.keepSecret","Enter new password or leave empty"):void 0})}),L==="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(B,{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 X,te;const h=(X=f.getFieldValue("private_key_path"))==null?void 0:X.trim(),F=(te=f.getFieldValue("private_key"))==null?void 0:te.trim();if(h||F)return;const P=(ye==null?void 0:ye.placement.type)==="ssh"?ye.placement.auth:void 0;if(!((P==null?void 0:P.method)==="private_key"&&(P.private_key||P.private_key_path)))throw new Error(e("settings.clusters.privateKeyRequired","Provide a key file path or paste a private key"))}}],children:t.jsx(B.TextArea,{rows:3,placeholder:"-----BEGIN OPENSSH PRIVATE KEY-----"})}),t.jsx(b.Item,{name:"passphrase",label:e("settings.clusters.passphrase","Passphrase"),children:t.jsx(B.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(B,{placeholder:"/path/to/bamboo-linux-x64"})}),t.jsx(b.Item,{name:"default_role",label:e("settings.clusters.role","Default role"),children:t.jsx(B,{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(pe,{})}),t.jsx(b.Item,{name:"cluster_name",label:e("settings.clusters.cluster","Cluster"),children:t.jsx(ae,{allowClear:!0,showSearch:!0,mode:"tags",maxCount:1,placeholder:e("settings.clusters.clusterPlaceholder","Pick or type a cluster name"),options:r.map(h=>({value:h.name,label:h.name}))})}),t.jsx(b.Item,{name:"enabled",label:e("settings.clusters.enabled","Enabled"),valuePropName:"checked",children:t.jsx(pe,{})})]})}),t.jsx(Xe,{title:e("settings.clusters.logsTitle","Logs — {{label}}",{label:(d==null?void 0:d.label)??""}),open:D,onCancel:()=>y(!1),onOk:()=>d&&se(d),okText:e("settings.clusters.refresh","Refresh"),cancelText:e("settings.clusters.close","Close"),width:760,destroyOnClose:!0,children:w?t.jsx(Xt,{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:E})})]})},It=class It{constructor(){}static getInstance(){return It.instance||(It.instance=new It),It.instance}async listWorkflows(){try{ut("[WorkflowManager]","[WorkflowManagerService] Listing workflows");const s=await _n.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 _n.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),hs(n)&&n.status===404?new Error("Workflow '"+s+"' not found"):n instanceof Error&&n.message.includes("404")?new Error("Workflow '"+s+"' not found"):n}}};kn(It,"instance");let pn=It;const{Text:Gs}=ue,{TextArea:ai}=B,{useToken:ri}=Se,ii=e=>!(!e||e.includes("/")||e.includes("\\")||e.includes("..")),oi=()=>{const{t:e}=re(),{token:s}=ri(),[n,a]=At.useMessage(),[r,i]=o.useState([]),[l,g]=o.useState(!1),[p,m]=o.useState(!1),[c,u]=o.useState(!1),[f,D]=o.useState(null),[y,d]=o.useState(""),[I,E]=o.useState(""),[j,w]=o.useState(!1),x=o.useMemo(()=>pn.getInstance(),[]),v=o.useCallback(async()=>{g(!0);try{const H=await x.listWorkflows();return i(H),H}catch{return n.error(e("settings.workflowsTab.loadFailed")),[]}finally{g(!1)}},[n,e,x]);o.useEffect(()=>{v()},[v]);const L=o.useCallback(async H=>{D(H),d(H.name),w(!1),m(!0);try{const C=await x.getWorkflow(H.name);E(C.content??"")}catch{n.error(e("settings.workflowsTab.loadContentFailed")),E("")}finally{m(!1)}},[n,e,x]),A=()=>{D(null),d(""),E(""),w(!1)},U=o.useCallback(async()=>{if(!ii(y)){n.error(e("settings.workflowsTab.invalidName"));return}const H=r.some(C=>C.name===y);if(!f&&H){n.error(e("settings.workflowsTab.nameAlreadyExists"));return}u(!0);try{await lt.getInstance().saveWorkflow(y,I),n.success(e("settings.workflowsTab.saved")),w(!1);const M=(await v()).find(S=>S.name===y);M&&D(M)}catch(C){n.error(C instanceof Error?C.message:e("settings.workflowsTab.saveFailed"))}finally{u(!1)}},[I,y,v,n,f,e,r]),ie=o.useCallback(async H=>{try{await lt.getInstance().deleteWorkflow(H.name),n.success(e("settings.workflowsTab.deleted")),(f==null?void 0:f.name)===H.name&&A(),await v()}catch(C){n.error(C instanceof Error?C.message:e("settings.workflowsTab.deleteFailed"))}},[v,n,f,e]);return t.jsxs("div",{style:{padding:"24px"},children:[a,t.jsxs(V,{title:e("settings.workflowsTab.title"),extra:t.jsxs(O,{children:[t.jsx(R,{icon:t.jsx($t,{}),onClick:v,loading:l,children:e("settings.workflowsTab.refresh")}),t.jsx(R,{"data-testid":"create-workflow",icon:t.jsx(at,{}),onClick:A,children:e("settings.workflowsTab.newWorkflow")}),t.jsx(R,{"data-testid":"save-workflow",type:"primary",icon:t.jsx(As,{}),onClick:U,loading:c,disabled:!j,children:e("settings.workflowsTab.save")})]}),children:[t.jsx(Gs,{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(He,{loading:l,dataSource:r,locale:{emptyText:e("settings.workflowsTab.empty")},renderItem:H=>t.jsx(He.Item,{style:{cursor:"pointer",backgroundColor:(f==null?void 0:f.name)===H.name?s.colorFillSecondary:"transparent",borderRadius:s.borderRadius,padding:s.paddingSM},onClick:()=>L(H),actions:[t.jsx(R,{"data-testid":`delete-workflow-${H.name}`,type:"text",danger:!0,size:"small",icon:t.jsx(kt,{}),onClick:C=>{C.stopPropagation(),ie(H)},"aria-label":e("settings.workflowsTab.delete")},"delete")],children:t.jsxs(O,{direction:"vertical",size:0,children:[t.jsxs(Gs,{strong:!0,children:["/",H.name]}),t.jsx(Gs,{type:"secondary",style:{fontSize:12},children:H.filename})]})})})}),t.jsx("div",{style:{flex:1},children:t.jsxs(O,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(B,{"data-testid":"workflow-name",placeholder:e("settings.workflowsTab.namePlaceholder"),value:y,onChange:H=>{d(H.target.value),w(!0)},disabled:!!f,prefix:t.jsx(Vt,{})}),t.jsx(ai,{"data-testid":"workflow-content",placeholder:e("settings.workflowsTab.contentPlaceholder"),value:I,onChange:H=>{E(H.target.value),w(!0)},autoSize:{minRows:12},disabled:p})]})})]})]})]})};var Y=(e=>(e.Connecting="connecting",e.Ready="ready",e.Degraded="degraded",e.Stopped="stopped",e.Error="error",e))(Y||{});const ys=6e4,fs=3e4,cs=2e4,Ds=1e4,Rs=e=>({id:e,enabled:!0,transport:{type:"stdio",command:"",args:[],env:{},startup_timeout_ms:cs},request_timeout_ms:ys,healthcheck_interval_ms:fs,allowed_tools:[],denied_tools:[]}),li=()=>({status:"stopped",tool_count:0,restart_count:0}),ci=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},di=(e,s)=>{if(!e||typeof e!="object")return s;const n=e;if(n.type==="sse"){const i=Array.isArray(n.headers)?n.headers.map(l=>{if(!l||typeof l!="object")return null;const g=l;return typeof g.name!="string"||typeof g.value!="string"?null:{name:g.name,value:g.value}}).filter(l=>!!l):[];return{type:"sse",url:typeof n.url=="string"?n.url:"",headers:i,connect_timeout_ms:ct(n.connect_timeout_ms,Ds)}}const a=Array.isArray(n.args)?n.args.filter(i=>typeof i=="string"):[],r=n.env&&typeof n.env=="object"?Object.entries(n.env):[];return{type:"stdio",command:typeof n.command=="string"?n.command:"",args:a,cwd:typeof n.cwd=="string"?n.cwd:void 0,env:r.reduce((i,[l,g])=>(typeof g=="string"&&(i[l]=g),i),{}),startup_timeout_ms:ct(n.startup_timeout_ms,cs)}},ui=(e,s)=>{const n=Rs(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,ys),healthcheck_interval_ms:ct(a.healthcheck_interval_ms,fs),allowed_tools:Array.isArray(a.allowed_tools)?a.allowed_tools.filter(i=>typeof i=="string"):[],denied_tools:Array.isArray(a.denied_tools)?a.denied_tools.filter(i=>typeof i=="string"):[],reconnect:a.reconnect&&typeof a.reconnect=="object"?{enabled:typeof a.reconnect.enabled=="boolean"?a.reconnect.enabled:!0,initial_backoff_ms: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:di(a.transport,n.transport)}},gi=e=>{const s=li(),a=e.runtime??{},r=a.status??e.status;return{status:ci(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}},pi=e=>{const s=ui(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:gi(e)}},mi=(e,s)=>`mcp__${e}__${s}`,hi=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}},yi=(e,s,n=0)=>{if(!e||typeof e!="object")return null;const a=e,r=typeof a.alias=="string"?a.alias:typeof a.name=="string"&&a.name.startsWith("mcp__")?a.name:void 0,i=r&&typeof r=="string"?hi(r):null,l=(typeof a.server_id=="string"?a.server_id:void 0)??(typeof a.serverId=="string"?a.serverId:void 0)??(i==null?void 0:i.server_id)??s??"",g=(typeof a.original_name=="string"?a.original_name:void 0)??(typeof a.originalName=="string"?a.originalName:void 0)??(i==null?void 0:i.original_name)??(typeof a.name=="string"?a.name:void 0)??"",p=r??(l&&g?mi(l,g):""),m=typeof a.description=="string"?a.description:"",c=a,u="parameters"in c?c.parameters:"inputSchema"in c?c.inputSchema:"input_schema"in c?c.input_schema:void 0,f=p||g||`mcp_tool_${n}`;return{alias:f,server_id:l||"unknown",original_name:g||f,description:m,parameters:u}};class fi{async getServers(){const s=await $e.get("mcp/servers");return Array.isArray(s.servers)?s.servers.map(pi):[]}async addServer(s){return $e.post("mcp/servers",s)}async updateServer(s,n){const a={...n,id:s};return $e.put(`mcp/servers/${s}`,a)}async deleteServer(s){return $e.delete(`mcp/servers/${s}`)}async connectServer(s){return $e.post(`mcp/servers/${s}/connect`)}async disconnectServer(s){return $e.post(`mcp/servers/${s}/disconnect`)}async refreshTools(s){return $e.post(`mcp/servers/${s}/refresh`)}async getTools(s){const n=s?`mcp/servers/${s}/tools`:"mcp/tools",a=await $e.get(n);return(Array.isArray(a.tools)?a.tools:[]).map((i,l)=>yi(i,s,l)).filter(i=>!!i)}async importServers(s){return $e.post("mcp/servers/import",s)}}const va=new fi,bi=5e3,it=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,On=(e,s)=>`${e}:${s}`,xi=(e={})=>{const{service:s=va,autoRefreshMs:n=bi,autoRefreshEnabled:a=!0}=e,[r,i]=o.useState([]),[l,g]=o.useState(null),[p,m]=o.useState({}),[c,u]=o.useState({}),[f,D]=o.useState({}),[y,d]=o.useState(!1),[I,E]=o.useState(!1),[j,w]=o.useState(!1),[x,v]=o.useState(null),L=o.useRef({}),A=o.useCallback(h=>{const F=new Set(h.map(X=>X.id)),P=h.map(X=>{const ge=L.current[X.id]??X.config,ve={...ge,id:X.id,name:ge.name??X.name};return L.current[X.id]=ve,{...X,name:X.name||ve.name||X.id,enabled:X.enabled??ve.enabled,config:ve}});return Object.keys(L.current).forEach(X=>{F.has(X)||delete L.current[X]}),P},[]),U=o.useCallback(async({silent:h=!1}={})=>{h||d(!0);try{const F=await s.getServers(),P=A(F);i(P),g(X=>{var te;return X&&P.some(ge=>ge.id===X)?X:((te=P[0])==null?void 0:te.id)??null}),v(null)}catch(F){throw v(it(F,"Failed to load MCP servers")),F}finally{h||d(!1)}},[A,s]),ie=o.useCallback(async(h,F=!1)=>{if(!h)return[];if(!F&&p[h])return p[h];u(P=>({...P,[h]:!0}));try{const P=await s.getTools(h);return m(X=>({...X,[h]:P})),v(null),P}catch(P){throw v(it(P,"Failed to load MCP tools")),P}finally{u(P=>({...P,[h]:!1}))}},[s,p]),H=o.useCallback((h,F,P)=>{const X=On(h,F);D(te=>({...te,[X]:P}))},[]),C=o.useCallback(async h=>{E(!0);try{await s.addServer(h),L.current[h.id]=h,await U()}catch(F){throw v(it(F,"Failed to add MCP server")),F}finally{E(!1)}},[U,s]),k=o.useCallback(async(h,F)=>{E(!0);try{const P={...F,id:h};await s.updateServer(h,P),L.current[h]=P,await U()}catch(P){throw v(it(P,"Failed to update MCP server")),P}finally{E(!1)}},[U,s]),M=o.useCallback(async h=>{H(h,"delete",!0);try{await s.deleteServer(h),m(F=>{const P={...F};return delete P[h],P}),delete L.current[h],await U()}catch(F){throw v(it(F,"Failed to delete MCP server")),F}finally{H(h,"delete",!1)}},[U,s,H]),S=o.useCallback(async h=>{H(h,"connect",!0);try{await s.connectServer(h),await U({silent:!0})}catch(F){throw v(it(F,"Failed to connect MCP server")),F}finally{H(h,"connect",!1)}},[U,s,H]),G=o.useCallback(async h=>{H(h,"disconnect",!0);try{await s.disconnectServer(h),await U({silent:!0})}catch(F){throw v(it(F,"Failed to disconnect MCP server")),F}finally{H(h,"disconnect",!1)}},[U,s,H]),$=o.useCallback(async h=>{H(h,"refresh",!0);try{await s.refreshTools(h),await ie(h,!0),await U({silent:!0})}catch(F){throw v(it(F,"Failed to refresh MCP tools")),F}finally{H(h,"refresh",!1)}},[ie,U,s,H]),ee=o.useCallback(async()=>{w(!0);try{const h=r.map(F=>F.id);await Promise.all(h.map(async F=>{try{await s.refreshTools(F)}catch{}})),await U(),l&&await ie(l,!0)}catch(h){throw v(it(h,"Failed to refresh MCP status")),h}finally{w(!1)}},[ie,U,l,r,s]),se=o.useCallback(h=>{g(h)},[]),le=o.useCallback((h,F)=>!!f[On(h,F)],[f]),Q=o.useMemo(()=>l?p[l]??[]:[],[l,p]),ye=o.useMemo(()=>l?!!c[l]:!1,[l,c]);return o.useEffect(()=>{U().catch(()=>{})},[U]),o.useEffect(()=>{if(!a||n<=0)return;const h=window.setInterval(()=>{U({silent:!0}).catch(()=>{})},n);return()=>{window.clearInterval(h)}},[a,n,U]),o.useEffect(()=>{l&&ie(l).catch(()=>{})},[ie,l]),{servers:r,selectedServerId:l,selectedServerTools:Q,isLoadingServers:y,isMutatingConfig:I,isRefreshingAll:j,isSelectedServerToolsLoading:ye,error:x,setSelectedServerId:se,refreshServers:U,addServer:C,updateServer:k,deleteServer:M,connectServer:S,disconnectServer:G,refreshServerTools:$,refreshAll:ee,isServerActionLoading:le}},vi={[Y.Connecting]:"blue",[Y.Ready]:"green",[Y.Degraded]:"orange",[Y.Stopped]:"default",[Y.Error]:"red"},ji=e=>e===Y.Connecting||e===Y.Ready||e===Y.Degraded,Ti=e=>{if(!e)return;const s=e.replace(/\s+/g," ").trim();if(s)return s.length>180?`${s.slice(0,180)}...`:s},ki=({servers:e,loading:s=!1,selectedServerId:n,onSelectServer:a,onEditServer:r,onDeleteServer:i,onConnectServer:l,onDisconnectServer:g,onRefreshTools:p,isServerActionLoading:m})=>{const{t:c}=re(),{token:u}=Se.useToken(),f=o.useMemo(()=>({[Y.Connecting]:c("settings.mcpTab.statusHelp.connecting"),[Y.Ready]:c("settings.mcpTab.statusHelp.ready"),[Y.Degraded]:c("settings.mcpTab.statusHelp.degraded"),[Y.Stopped]:c("settings.mcpTab.statusHelp.stopped"),[Y.Error]:c("settings.mcpTab.statusHelp.error")}),[c]),D=o.useMemo(()=>[{key:"name",title:c("settings.mcpServerTable.columns.name"),render:(y,d)=>d.name||d.id},{key:"transport",title:c("settings.mcpServerTable.columns.transportType"),render:(y,d)=>d.config.transport.type==="sse"?c("settings.mcpServerTable.transportOptions.sse"):c("settings.mcpServerTable.transportOptions.stdio"),width:140},{key:"status",title:c("settings.mcpServerTable.columns.status"),render:(y,d)=>{var x,v;const I=((x=d.runtime)==null?void 0:x.status)??Y.Stopped,E=Ti((v=d.runtime)==null?void 0:v.last_error),j=f[I],w={[Y.Connecting]:c("settings.mcpTab.status.connecting"),[Y.Ready]:c("settings.mcpTab.status.ready"),[Y.Degraded]:c("settings.mcpTab.status.degraded"),[Y.Stopped]:c("settings.mcpTab.status.stopped"),[Y.Error]:c("settings.mcpTab.status.error")};return t.jsx(we,{title:E?`${j} ${c("settings.mcpTab.statusLastError",{error:E})}`:j,children:t.jsx(oe,{color:I===Y.Stopped?void 0:vi[I],style:{marginInlineEnd:0,cursor:"help",...I===Y.Stopped?{background:u.colorFillSecondary,borderColor:u.colorBorderSecondary,color:u.colorTextSecondary}:void 0},children:w[I]})})},width:120},{key:"toolCount",title:c("settings.mcpServerTable.columns.toolCount"),render:(y,d)=>{var I;return((I=d.runtime)==null?void 0:I.tool_count)??0},width:100},{key:"actions",title:c("settings.mcpServerTable.columns.actions"),width:360,render:(y,d)=>{var j;const I=((j=d.runtime)==null?void 0:j.status)??Y.Stopped,E=ji(I);return t.jsxs(O,{size:u.marginXS,children:[t.jsx(R,{size:"small",onClick:w=>{w.stopPropagation(),r==null||r(d)},children:c("settings.mcpServerTable.actions.edit")}),t.jsx(Tt,{title:c("settings.mcpServerTable.deleteTitle"),description:c("settings.mcpServerTable.deleteDescription",{name:d.name||d.id}),onConfirm:()=>i==null?void 0:i(d),okText:c("settings.mcpServerTable.actions.delete"),okButtonProps:{danger:!0,loading:m==null?void 0:m(d.id,"delete")},children:t.jsx(R,{size:"small",danger:!0,loading:m==null?void 0:m(d.id,"delete"),onClick:w=>w.stopPropagation(),children:c("settings.mcpServerTable.actions.delete")})}),E?t.jsx(R,{size:"small",onClick:w=>{w.stopPropagation(),g==null||g(d)},loading:m==null?void 0:m(d.id,"disconnect"),children:c("settings.mcpServerTable.actions.disconnect")}):t.jsx(R,{size:"small",type:"primary",ghost:!0,onClick:w=>{w.stopPropagation(),l==null||l(d)},loading:m==null?void 0:m(d.id,"connect"),children:c("settings.mcpServerTable.actions.connect")}),t.jsx(R,{size:"small",onClick:w=>{w.stopPropagation(),p==null||p(d)},loading:m==null?void 0:m(d.id,"refresh"),children:c("settings.mcpServerTable.actions.refreshTools")})]})}}],[m,l,i,g,r,p,f,c,u.colorBorderSecondary,u.colorFillSecondary,u.colorTextSecondary,u.marginXS]);return t.jsx(et,{rowKey:"id",columns:D,dataSource:e,loading:s,pagination:!1,locale:{emptyText:c("settings.mcpServerTable.empty")},onRow:y=>({onClick:()=>a==null?void 0:a(y.id),style:{cursor:a?"pointer":"default",backgroundColor:n===y.id?u.colorFillSecondary:void 0}})})},{Text:Nn}=ue,{TextArea:Si}=B,Vn=e=>{const s=e??Rs(""),n=s.transport,a=n.type==="stdio"?Object.entries(n.env??{}).map(([i,l])=>({key:i,value:l})):[],r=n.type==="sse"?n.headers.map(i=>({name:i.name,value:i.value})):[];return{id:s.id,name:s.name,enabled:s.enabled,transportType:n.type,command:n.type==="stdio"?n.command:void 0,args:n.type==="stdio"?n.args:[],envEntries:a,url:n.type==="sse"?n.url:void 0,headerEntries:r,requestTimeoutMs:s.request_timeout_ms||ys,healthcheckIntervalMs:s.healthcheck_interval_ms||fs,allowedTools:s.allowed_tools||[],deniedTools:s.denied_tools||[]}},_i=e=>e.reduce((s,n)=>{var r;const a=(r=n.key)==null?void 0:r.trim();return a&&(s[a]=n.value??""),s},{}),wi=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??""}}),$n=(e,s,n)=>{var c,u,f;const a=s==="edit"&&(n==null?void 0:n.id)||e.id,r=(c=e.name)==null?void 0:c.trim(),i=typeof e.requestTimeoutMs=="number"?e.requestTimeoutMs:(n==null?void 0:n.request_timeout_ms)??ys,l=typeof e.healthcheckIntervalMs=="number"?e.healthcheckIntervalMs:(n==null?void 0:n.healthcheck_interval_ms)??fs,g=Array.isArray(e.allowedTools)?e.allowedTools:(n==null?void 0:n.allowed_tools)??[],p=Array.isArray(e.deniedTools)?e.deniedTools:(n==null?void 0:n.denied_tools)??[],m=e.transportType==="sse"?{type:"sse",url:((u=e.url)==null?void 0:u.trim())||"",headers:wi(e.headerEntries||[]),connect_timeout_ms:(n==null?void 0:n.transport.type)==="sse"?n.transport.connect_timeout_ms??Ds:Ds}:{type:"stdio",command:((f=e.command)==null?void 0:f.trim())||"",args:e.args||[],env:_i(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:m,request_timeout_ms:i,healthcheck_interval_ms:l,allowed_tools:g,denied_tools:p,reconnect:n==null?void 0:n.reconnect}},Bn=e=>JSON.stringify(e||Rs(""),null,2),Xs=(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 u=a;return!u.transport||typeof u.transport!="object"?{valid:!1,error:s("settings.mcpServerForm.missingTransportField")}:{valid:!0,config:u}}const i=typeof a.enabled=="boolean"?a.enabled:typeof a.disabled=="boolean"?!a.disabled:!0,l=typeof a.request_timeout_ms=="number"?a.request_timeout_ms:ys,g=typeof a.healthcheck_interval_ms=="number"?a.healthcheck_interval_ms:fs,p=Array.isArray(a.allowed_tools)?a.allowed_tools.filter(u=>typeof u=="string"):[],m=Array.isArray(a.denied_tools)?a.denied_tools.filter(u=>typeof u=="string"):[],c=typeof a.name=="string"?a.name:void 0;if(typeof a.url=="string"){const u=a.headers,f=Array.isArray(u)?u.map(y=>{if(!y||typeof y!="object")return null;const d=y,I=typeof d.name=="string"?d.name:"",E=typeof d.value=="string"?d.value:"";return I.trim()?{name:I,value:E}:null}).filter(y=>!!y):u&&typeof u=="object"?Object.entries(u).filter(([y])=>y.trim()).map(([y,d])=>({name:y,value:typeof d=="string"?d:""})):[],D=typeof a.connect_timeout_ms=="number"?a.connect_timeout_ms:Ds;return{valid:!0,config:{id:r,name:c,enabled:i,transport:{type:"sse",url:a.url,headers:f,connect_timeout_ms:D},request_timeout_ms:l,healthcheck_interval_ms:g,allowed_tools:p,denied_tools:m,reconnect:void 0}}}if(typeof a.command=="string"){const u=Array.isArray(a.args)?a.args.filter(d=>typeof d=="string"):[],f=a.env,D=f&&typeof f=="object"?Object.entries(f).reduce((d,[I,E])=>(typeof E=="string"&&(d[I]=E),d),{}):{},y=typeof a.startup_timeout_ms=="number"?a.startup_timeout_ms:cs;return{valid:!0,config:{id:r,name:c,enabled:i,transport:{type:"stdio",command:a.command,args:u,cwd:typeof a.cwd=="string"?a.cwd:void 0,env:D,startup_timeout_ms:y},request_timeout_ms:l,healthcheck_interval_ms:g,allowed_tools:p,denied_tools:m,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")})}}},Ci=({open:e,mode:s,initialConfig:n,confirmLoading:a=!1,onCancel:r,onSubmit:i})=>{const{t:l}=re(),[g]=b.useForm(),[p,m]=o.useState("form"),[c,u]=o.useState(""),[f,D]=o.useState(null),y=o.useMemo(()=>Vn(n),[n]),d=b.useWatch("transportType",g)??"stdio";o.useEffect(()=>{e&&(g.setFieldsValue(y),u(Bn(n)),D(null),m("form"))},[g,y,n,e]);const I=()=>{g.resetFields(),u(""),D(null),r()},E=async()=>{if(p==="json"){const x=Xs(c,l);if(!x.valid){D(x.error);return}D(null);try{await i(x.config),u("")}catch(v){console.error("MCP server JSON submission error:",v)}return}try{const x=await g.validateFields(),v=$n(x,s,n);await i(v),g.resetFields()}catch(x){console.error("MCP server form submission error:",x)}},j=x=>{u(x),f&&Xs(x,l).valid&&D(null)},w=x=>{if(x==="json")try{const v=g.getFieldsValue(),L=$n(v,s,n);u(JSON.stringify(L,null,2))}catch{u(Bn(n))}else{const v=Xs(c,l);v.valid&&g.setFieldsValue(Vn(v.config))}m(x),D(null)};return t.jsxs(Xe,{title:l(s==="edit"?"settings.mcpServerForm.editTitle":"settings.mcpServerForm.addTitle"),open:e,onCancel:I,onOk:()=>{E()},okText:l("settings.mcpServerForm.save"),destroyOnClose:!0,forceRender:!0,confirmLoading:a,width:720,children:[t.jsx("div",{style:{marginBottom:16},children:t.jsxs(Ot.Group,{value:p,onChange:x=>w(x.target.value),optionType:"button",buttonStyle:"solid",children:[t.jsxs(Ot.Button,{value:"form",children:[t.jsx(ir,{})," ",l("settings.mcpServerForm.modeForm")]}),t.jsxs(Ot.Button,{value:"json",children:[t.jsx(or,{})," ",l("settings.mcpServerForm.modeJson")]})]})}),p==="json"&&f&&t.jsx(Ie,{type:"error",message:l("settings.mcpServerForm.jsonError"),description:f,showIcon:!0,style:{marginBottom:16},closable:!0,onClose:()=>D(null)}),p==="json"?t.jsx(Si,{value:c,onChange:x=>j(x.target.value),rows:20,style:{fontFamily:"monospace",fontSize:13},placeholder:JSON.stringify(Rs("example-server"),null,2)}):t.jsxs(b,{layout:"vertical",form:g,preserve:!0,initialValues:y,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(B,{placeholder:"filesystem",disabled:s==="edit",autoComplete:"off"})}),t.jsx(b.Item,{name:"name",label:l("settings.mcpServerForm.displayName"),children:t.jsx(B,{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(pe,{})}),t.jsx(b.Item,{name:"transportType",label:l("settings.mcpServerForm.transportType"),rules:[{required:!0,message:l("settings.mcpServerForm.transportTypeRequired")}],children:t.jsx(ae,{options:[{label:l("settings.mcpServerForm.transportOptions.stdio"),value:"stdio"},{label:l("settings.mcpServerForm.transportOptions.sse"),value:"sse"}]})}),d==="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(B,{placeholder:"npx",autoComplete:"off"})}),t.jsx(b.Item,{name:"args",label:l("settings.mcpServerForm.arguments"),children:t.jsx(ae,{mode:"tags",tokenSeparators:[","],placeholder:l("settings.mcpServerForm.argumentsPlaceholder"),open:!1})}),t.jsx(b.List,{name:"envEntries",children:(x,{add:v,remove:L})=>t.jsxs(O,{direction:"vertical",style:{width:"100%"},children:[t.jsxs(O,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[t.jsx(Nn,{strong:!0,children:l("settings.mcpServerForm.envVars")}),t.jsx(R,{icon:t.jsx(at,{}),onClick:()=>v({key:"",value:""}),type:"dashed",children:l("settings.mcpServerForm.addEnv")})]}),x.map(A=>t.jsxs(O,{align:"baseline",style:{display:"flex"},children:[t.jsx(b.Item,{...A,name:[A.name,"key"],rules:[{required:!0,message:l("settings.mcpServerForm.keyRequired")}],children:t.jsx(B,{placeholder:"MCP_ROOT",autoComplete:"off"})}),t.jsx(b.Item,{...A,name:[A.name,"value"],children:t.jsx(B,{placeholder:"/Users/me/workspace",autoComplete:"off"})}),t.jsx(R,{danger:!0,type:"text",icon:t.jsx(In,{}),onClick:()=>L(A.name),"aria-label":l("settings.mcpServerForm.removeEnv","Remove environment variable")})]},A.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(x,v)=>{if(v)try{new URL(v)}catch{throw new Error(l("settings.mcpServerForm.validUrlRequired"))}}}],children:t.jsx(B,{placeholder:"http://localhost:4000/sse",autoComplete:"off"})}),t.jsx(b.List,{name:"headerEntries",children:(x,{add:v,remove:L})=>t.jsxs(O,{direction:"vertical",style:{width:"100%"},children:[t.jsxs(O,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[t.jsx(Nn,{strong:!0,children:l("settings.mcpServerForm.headers")}),t.jsx(R,{icon:t.jsx(at,{}),onClick:()=>v({name:"",value:""}),type:"dashed",children:l("settings.mcpServerForm.addHeader")})]}),x.map(A=>t.jsxs(O,{align:"baseline",style:{display:"flex"},children:[t.jsx(b.Item,{...A,name:[A.name,"name"],rules:[{required:!0,message:l("settings.mcpServerForm.headerNameRequired")}],children:t.jsx(B,{placeholder:"Authorization",autoComplete:"off"})}),t.jsx(b.Item,{...A,name:[A.name,"value"],children:t.jsx(B,{placeholder:"Bearer token",autoComplete:"off"})}),t.jsx(R,{danger:!0,type:"text",icon:t.jsx(In,{}),onClick:()=>L(A.name),"aria-label":l("settings.mcpServerForm.removeHeader","Remove header")})]},A.key))]})})]})]})]})},Cs=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Mt=(e,s)=>{const n=e[s];return typeof n=="string"?n:void 0},qn=(e,s)=>{const n=e[s];return typeof n=="boolean"?n:void 0},Mi=(e,s)=>{const n=e[s];return Array.isArray(n)?n:void 0},rs=e=>{if(!Cs(e))return"any";const s=e.type;if(typeof s=="string"){if(s==="array"){const i=e.items;return`array<${rs(i)}>`}return s==="object"?"object":s}if(Array.isArray(s)){const i=s.filter(l=>typeof l=="string").map(l=>l==="array"?"array<any>":l);return i.length>0?i.join(" | "):"any"}const n=Array.isArray(e.oneOf)?e.oneOf:null;if(n)return n.map(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"},Ei=e=>{if(!Cs(e))return null;const s=e.properties;if(!Cs(s))return{schemaUri:Mt(e,"$schema"),title:Mt(e,"title"),description:Mt(e,"description"),additionalProperties:qn(e,"additionalProperties"),fields:[]};const n=new Set((Mi(e,"required")??[]).filter(r=>typeof r=="string").map(r=>r)),a=Object.entries(s).map(([r,i])=>{const l=Cs(i)?i:void 0;return{name:r,type:rs(i),required:n.has(r),description:l?Mt(l,"description"):void 0,defaultValue:l?l.default:void 0,enumValues:l&&Array.isArray(l.enum)?l.enum:void 0}});return a.sort((r,i)=>r.required!==i.required?r.required?-1:1:r.name.localeCompare(i.name)),{schemaUri:Mt(e,"$schema"),title:Mt(e,"title"),description:Mt(e,"description"),additionalProperties:qn(e,"additionalProperties"),fields:a}},{Text:st}=ue,Pi=e=>e===void 0?"":e===null?"null":typeof e=="string"?e:ha(e,0),Di=({schema:e})=>{const{token:s}=Se.useToken(),{t:n}=re(),a=o.useMemo(()=>Ei(e),[e]);if(!a)return t.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:ha(e,2)});const r=[{title:n("components.jsonSchema.field"),dataIndex:"name",key:"name",width:180,render:l=>t.jsx(st,{code:!0,children:l})},{title:n("components.jsonSchema.type"),dataIndex:"type",key:"type",width:140,render:l=>t.jsx(st,{children:l})},{title:n("components.jsonSchema.required"),dataIndex:"required",key:"required",width:110,render:l=>l?t.jsx(st,{strong:!0,style:{color:s.colorError},children:n("components.jsonSchema.yes")}):t.jsx(st,{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(st,{type:"secondary",children:"-"}):t.jsx(st,{children:Pi(l)})},{title:n("components.jsonSchema.description"),dataIndex:"description",key:"description",render:l=>l?t.jsx(st,{style:{whiteSpace:"pre-wrap"},children:l}):t.jsx(st,{type:"secondary",children:"-"})}],i=(a.fields??[]).map(l=>({...l,key:l.name}));return t.jsxs("div",{style:{width:"100%"},children:[t.jsx(Ue,{size:"small",column:1,items:[a.schemaUri?{key:"schema",label:"$schema",children:t.jsx(st,{code:!0,children:a.schemaUri})}:null,typeof a.additionalProperties=="boolean"?{key:"additionalProperties",label:"additionalProperties",children:t.jsx(st,{children:a.additionalProperties?"true":"false"})}:null].filter(Boolean)}),t.jsx(et,{size:"small",pagination:!1,columns:r,dataSource:i,locale:{emptyText:n("components.jsonSchema.noProperties")},style:{marginTop:s.marginSM}})]})},{Text:Jt}=ue,Ii=(e,s)=>`mcp__${e}__${s}`,Fi=({server:e,tools:s,loading:n=!1})=>{const{t:a}=re();return t.jsx(V,{title:a("settings.mcpToolList.title"),size:"small",children:e?t.jsx(He,{loading:n,dataSource:s,locale:{emptyText:a("settings.mcpToolList.empty")},renderItem:r=>{const i=Ii(r.server_id,r.original_name);return t.jsx(He.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:i})]}),r.parameters!==void 0&&t.jsx(Fs,{size:"small",items:[{key:"schema",label:a("settings.mcpToolList.parametersSchema"),children:t.jsx(Di,{schema:r.parameters})}]})]})})}}):t.jsx(Be,{image:Be.PRESENTED_IMAGE_SIMPLE,description:a("settings.mcpToolList.selectServerHint")})})},{Text:Yt}=ue,{useToken:Ai}=Se,{TextArea:Ri}=B,Un={[Y.Connecting]:"processing",[Y.Ready]:"success",[Y.Degraded]:"warning",[Y.Stopped]:"default",[Y.Error]:"error"},zi=()=>({[Y.Connecting]:0,[Y.Ready]:0,[Y.Degraded]:0,[Y.Stopped]:0,[Y.Error]:0}),Et=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,Li=e=>{var n,a,r;const s={};for(const i of e){const l=(n=i.id)==null?void 0:n.trim();if(!l)continue;const p=!(i.enabled??i.config.enabled),m=i.config.transport;if(m.type==="sse"){const u={};for(const D of m.headers??[]){const y=(a=D.name)==null?void 0:a.trim();y&&(u[y]=D.value??"")}const f={url:m.url};p&&(f.disabled=!0),Object.keys(u).length&&(f.headers=u),s[l]=f;continue}const c={command:m.command};p&&(c.disabled=!0),(r=m.args)!=null&&r.length&&(c.args=m.args),m.cwd&&(c.cwd=m.cwd),m.env&&Object.keys(m.env).length&&(c.env=m.env),s[l]=c}return{mcpServers:s}},Oi=()=>{const{t:e}=re(),{token:s}=Ai(),[n,a]=At.useMessage(),{servers:r,selectedServerId:i,selectedServerTools:l,isLoadingServers:g,isMutatingConfig:p,isRefreshingAll:m,isSelectedServerToolsLoading:c,error:u,setSelectedServerId:f,addServer:D,updateServer:y,deleteServer:d,connectServer:I,disconnectServer:E,refreshServerTools:j,refreshAll:w,isServerActionLoading:x}=xi(),v=o.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]),L=o.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]),[A,U]=o.useState(!1),[ie,H]=o.useState("create"),[C,k]=o.useState(null),[M,S]=o.useState(!1),[G,$]=o.useState("merge"),[ee,se]=o.useState(""),[le,Q]=o.useState(null),[ye,h]=o.useState(!1),F=o.useMemo(()=>i?r.find(N=>N.id===i)??null:null,[i,r]),P=o.useMemo(()=>{const N=zi();let fe=0;return r.forEach(z=>{var ce,qe;const be=((ce=z.runtime)==null?void 0:ce.status)??Y.Stopped;N[be]+=1,fe+=((qe=z.runtime)==null?void 0:qe.tool_count)??0}),{byStatus:N,totalServers:r.length,totalTools:fe}},[r]),X={background:s.colorFillSecondary,borderColor:s.colorBorderSecondary,color:s.colorTextSecondary},te=async N=>{try{await d(N.id),n.success(e("settings.mcpTab.serverDeleted"))}catch(fe){n.error(Et(fe,e("settings.mcpTab.deleteServerFailed")))}},ge=async N=>{try{await I(N.id),n.success(e("settings.mcpTab.connectedTo",{name:N.name||N.id}))}catch(fe){n.error(Et(fe,e("settings.mcpTab.connectServerFailed")))}},ve=async N=>{try{await E(N.id),n.success(e("settings.mcpTab.disconnected",{name:N.name||N.id}))}catch(fe){n.error(Et(fe,e("settings.mcpTab.disconnectServerFailed")))}},_e=async N=>{try{await j(N.id),n.success(e("settings.mcpTab.toolsRefreshedFor",{name:N.name||N.id}))}catch(fe){n.error(Et(fe,e("settings.mcpTab.refreshToolsFailed")))}},Oe=async()=>{try{await w(),n.success(e("settings.mcpTab.statusRefreshed"))}catch(N){n.error(Et(N,e("settings.mcpTab.refreshStatusFailed")))}},tt=()=>{k(null),H("create"),U(!0)},Ze=N=>{k(N),H("edit"),U(!0)},pt=async N=>{try{if(ie==="edit"){if(!C){n.error(e("settings.mcpTab.noServerForEditing"));return}await y(C.id,N),n.success(e("settings.mcpTab.savedServer",{name:C.name||C.id}))}else await D(N),n.success(e("settings.mcpTab.addedServer",{name:N.name||N.id}));U(!1),k(null)}catch(fe){n.error(Et(fe,e("settings.mcpTab.saveServerFailed")))}},q=()=>{S(!0),Q(null),$("merge"),se("")},Te=async()=>{const N=Li(r),fe=JSON.stringify(N,null,2);try{await bn(fe),n.success(e("settings.mcpTab.copiedConfig"))}catch{S(!0),Q(null),$("merge"),se(fe),n.warning(e("settings.mcpTab.clipboardUnavailable"))}},Ne=async()=>{var be;Q(null);let N;try{N=JSON.parse(ee)}catch(ce){Q(`${e("settings.mcpTab.invalidJsonPrefix")}: ${ce instanceof Error?ce.message:e("settings.mcpTab.unknownError")}`);return}if(!N||typeof N!="object"){Q(e("settings.mcpTab.jsonMustBeObject"));return}const z=N.mcpServers;if(!z||typeof z!="object"){Q(e("settings.mcpTab.missingMcpServers"));return}h(!0);try{const ce=await va.importServers({mcpServers:z,mode:G}),qe=((be=ce.start_errors)==null?void 0:be.length)??0;n.success(e("settings.mcpTab.importSummary",{count:ce.server_ids.length,added:ce.added,updated:ce.updated,removed:ce.removed,failed:qe})),qe&&n.warning(e("settings.mcpTab.importStartFailures")),S(!1),se(""),await Oe()}catch(ce){Q(Et(ce,e("settings.mcpTab.importFailed")))}finally{h(!1)}};return t.jsxs(O,{direction:"vertical",size:s.marginMD,style:{width:"100%"},children:[a,u?t.jsx(Ie,{type:"error",showIcon:!0,message:u}):null,t.jsx(V,{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:X,children:e("settings.mcpTab.totalServers",{count:P.totalServers})}),t.jsx(oe,{style:X,children:e("settings.mcpTab.totalTools",{count:P.totalTools})}),Object.values(Y).map(N=>t.jsx(we,{title:L[N],children:t.jsxs(oe,{color:N===Y.Stopped?void 0:Un[N],style:{cursor:"help",...N===Y.Stopped?X:void 0},children:[v[N],": ",P.byStatus[N]]})},N))]}),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(N=>t.jsxs(Yt,{type:"secondary",children:[t.jsx(oe,{color:N===Y.Stopped?void 0:Un[N],style:{marginInlineEnd:8,...N===Y.Stopped?X:void 0},children:v[N]}),L[N]]},`guide-${N}`))})]})}),t.jsx(V,{size:"small",title:e("settings.mcpTab.serversTitle"),extra:t.jsxs(O,{children:[t.jsx(R,{type:"primary",onClick:tt,children:e("settings.mcpTab.addServer")}),t.jsx(R,{icon:t.jsx($t,{}),loading:m,onClick:()=>{Oe()},children:e("settings.mcpTab.refreshAll")}),t.jsx(R,{icon:t.jsx(ya,{}),onClick:()=>void Te(),children:e("settings.mcpTab.export")}),t.jsx(R,{icon:t.jsx(lr,{}),onClick:q,children:e("settings.mcpTab.import")})]}),children:t.jsx(ki,{servers:r,loading:g,selectedServerId:i,onSelectServer:f,onEditServer:Ze,onDeleteServer:te,onConnectServer:ge,onDisconnectServer:ve,onRefreshTools:_e,isServerActionLoading:x})}),t.jsx(Fi,{server:F,tools:l,loading:c}),t.jsx(Ci,{open:A,mode:ie,initialConfig:(C==null?void 0:C.config)??null,confirmLoading:p,onCancel:()=>{p||(U(!1),k(null))},onSubmit:N=>void pt(N)}),t.jsx(Xe,{open:M,title:e("settings.mcpTab.importModalTitle"),okText:e("settings.mcpTab.import"),onOk:()=>void Ne(),okButtonProps:{loading:ye},onCancel:()=>{ye||(S(!1),Q(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(Ot.Group,{value:G,onChange:N=>$(N.target.value),optionType:"button",buttonStyle:"solid",children:[t.jsx(Ot.Button,{value:"merge",children:e("settings.mcpTab.importModeMerge")}),t.jsx(Ot.Button,{value:"replace",children:e("settings.mcpTab.importModeReplace")})]}),G==="replace"?t.jsx(Ie,{type:"warning",showIcon:!0,message:e("settings.mcpTab.replaceWarning")}):null,le?t.jsx(Ie,{type:"error",showIcon:!0,message:le}):null,t.jsx(Ri,{value:ee,onChange:N=>se(N.target.value),rows:14,placeholder:'{"mcpServers": { "filesystem": { "command": "...", "args": [], "env": {} } }}',spellCheck:!1})]})})]})},js=e=>{if(!Array.isArray(e))return;const s=e.filter(n=>typeof n=="string");return s.length>0?s:void 0},Ni=e=>{if(!e||typeof e!="object")return;const s=e,n={},a=js(s.mcp_server_ids);a&&(n.mcp_server_ids=a);const r=js(s.preset_ids);r&&(n.preset_ids=r);const i=js(s.skill_dirs);i&&(n.skill_dirs=i);const l=js(s.workflow_filenames);return l&&(n.workflow_filenames=l),Object.keys(n).length>0?n:void 0},Vi=e=>{if(!e||typeof e!="object")return{type:"local_dir",path:""};const s=e,n=typeof s.path=="string"?s.path:"";switch(s.type){case"local_archive":return{type:"local_archive",path:n};case"url":return{type:"url",url:typeof s.url=="string"?s.url:"",sha256:typeof s.sha256=="string"?s.sha256:void 0};case"local_dir":default:return{type:"local_dir",path:n}}},$i=e=>e==="installing"?"installing":"installed",Js=(e,s=0)=>{if(!e||typeof e!="object")return null;const n=e;return{id:typeof n.id=="string"&&n.id.trim()?n.id:`plugin_${s}`,name:typeof n.name=="string"?n.name:void 0,version:typeof n.version=="string"?n.version:"",source:Vi(n.source),status:$i(n.status),registered:Ni(n.registered)}};class Bi{async getPlugins(){const s=await $e.get("plugins");return(Array.isArray(s==null?void 0:s.plugins)?s.plugins:[]).map((a,r)=>Js(a,r)).filter(a=>!!a)}async installPlugin(s){const n=await $e.post("plugins/install",{source:s});return Js(n)}async updatePlugin(s,n){const a=await $e.post(`plugins/${encodeURIComponent(s)}/update`,{source:n});return Js(a)}async deletePlugin(s){await $e.delete(`plugins/${encodeURIComponent(s)}`)}}const Ms=new Bi,qi=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,Ui=(e={})=>{const{service:s=Ms}=e,[n,a]=o.useState([]),[r,i]=o.useState(!1),[l,g]=o.useState(null),p=o.useRef(!0);o.useEffect(()=>()=>{p.current=!1},[]);const m=o.useCallback(async({silent:c=!1}={})=>{!c&&p.current&&i(!0);try{const u=await s.getPlugins();p.current&&(a(u),g(null))}catch(u){throw p.current&&g(qi(u,"Failed to load plugins")),u}finally{!c&&p.current&&i(!1)}},[s]);return o.useEffect(()=>{m().catch(()=>{})},[m]),{plugins:n,isLoading:r,loadError:l,refresh:m}},{Text:Hn}=ue,Hi={installing:"warning",installed:"success"},Ki=e=>{switch(e.type){case"url":return`url: ${e.url}`;case"local_archive":return`local_archive: ${e.path}`;case"local_dir":default:return`local_dir: ${e.path}`}},Wi=({plugins:e,loading:s=!1,onUpdate:n,onRemove:a,isRemoving:r})=>{const{t:i}=re(),{token:l}=Se.useToken(),g=o.useMemo(()=>({installing:i("settings.pluginsTab.status.installing"),installed:i("settings.pluginsTab.status.installed")}),[i]),p=o.useMemo(()=>c=>{var f,D,y,d;const u=[];return(f=c==null?void 0:c.mcp_server_ids)!=null&&f.length&&u.push(t.jsx(oe,{children:i("settings.pluginsTab.registered.mcpServers",{count:c.mcp_server_ids.length})},"mcp")),(D=c==null?void 0:c.preset_ids)!=null&&D.length&&u.push(t.jsx(oe,{children:i("settings.pluginsTab.registered.prompts",{count:c.preset_ids.length})},"presets")),(y=c==null?void 0:c.skill_dirs)!=null&&y.length&&u.push(t.jsx(oe,{children:i("settings.pluginsTab.registered.skills",{count:c.skill_dirs.length})},"skills")),(d=c==null?void 0:c.workflow_filenames)!=null&&d.length&&u.push(t.jsx(oe,{children:i("settings.pluginsTab.registered.workflows",{count:c.workflow_filenames.length})},"workflows")),u.length===0?t.jsx(Hn,{type:"secondary",children:"—"}):t.jsx(O,{size:4,wrap:!0,children:u})},[i]),m=o.useMemo(()=>[{key:"id",title:i("settings.pluginsTab.columns.id"),dataIndex:"id",width:160},{key:"name",title:i("settings.pluginsTab.columns.name"),render:(c,u)=>u.name||u.id},{key:"version",title:i("settings.pluginsTab.columns.version"),dataIndex:"version",width:110},{key:"status",title:i("settings.pluginsTab.columns.status"),width:130,render:(c,u)=>{const f=t.jsx(oe,{color:Hi[u.status],children:g[u.status]});return u.status==="installing"?t.jsx(we,{title:i("settings.pluginsTab.status.installingHint"),children:t.jsx("span",{children:f})}):f}},{key:"registered",title:i("settings.pluginsTab.columns.registered"),render:(c,u)=>p(u.registered)},{key:"source",title:i("settings.pluginsTab.columns.source"),render:(c,u)=>t.jsx(Hn,{code:!0,children:Ki(u.source)})},{key:"actions",title:i("settings.pluginsTab.columns.actions"),width:200,render:(c,u)=>t.jsxs(O,{size:l.marginXS,children:[t.jsx(R,{size:"small",onClick:()=>n==null?void 0:n(u),children:i("settings.pluginsTab.actions.update")}),t.jsx(Tt,{title:i("settings.pluginsTab.remove.confirmTitle"),description:i("settings.pluginsTab.remove.confirmDescription",{name:u.name||u.id}),onConfirm:()=>a==null?void 0:a(u),okText:i("settings.pluginsTab.actions.remove"),okButtonProps:{danger:!0,loading:r==null?void 0:r(u.id)},children:t.jsx(R,{size:"small",danger:!0,loading:r==null?void 0:r(u.id),children:i("settings.pluginsTab.actions.remove")})})]})}],[r,a,n,p,g,i,l.marginXS]);return t.jsx(et,{rowKey:"id",columns:m,dataSource:e,loading:s,pagination:!1,locale:{emptyText:t.jsx(Be,{description:i("settings.pluginsTab.empty"),image:Be.PRESENTED_IMAGE_SIMPLE})}})},Kn={sourceType:"url",path:"",url:"",sha256:""},Gi=e=>{var s,n,a;return e.sourceType==="url"?{type:"url",url:((s=e.url)==null?void 0:s.trim())||"",sha256:((n=e.sha256)==null?void 0:n.trim())||void 0}:{type:e.sourceType,path:((a=e.path)==null?void 0:a.trim())||""}},Xi=e=>e.type==="url"?{sourceType:"url",url:e.url,sha256:e.sha256??"",path:""}:{sourceType:e.type,path:e.path,url:"",sha256:""},Ji=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,Wn=({open:e,mode:s,pluginLabel:n,initialSource:a,onCancel:r,onSubmit:i})=>{const{t:l}=re(),[g]=b.useForm(),[p,m]=o.useState(!1),[c,u]=o.useState(null),f=b.useWatch("sourceType",g)??"url";o.useEffect(()=>{e&&(g.setFieldsValue(s==="update"&&a?Xi(a):Kn),u(null),m(!1))},[e,s,a,g]);const D=()=>{p||(g.resetFields(),u(null),r())},y=async()=>{let d;try{d=await g.validateFields()}catch{return}const I=Gi(d);m(!0),u(null);try{await i(I),g.resetFields()}catch(E){const j=l(s==="install"?"settings.pluginsTab.install.genericError":"settings.pluginsTab.update.genericError");let w=Ji(E,j);hs(E)&&(E.status===404?w=l("settings.pluginsTab.errors.notFound"):E.status===422?w=l("settings.pluginsTab.errors.unsupportedPlatform"):s==="install"&&E.status===409&&(w=`${w} ${l("settings.pluginsTab.errors.conflictHint")}`)),u(w)}finally{m(!1)}};return t.jsx(Xe,{title:s==="install"?l("settings.pluginsTab.install.title"):l("settings.pluginsTab.update.title",{name:n??""}),open:e,onCancel:D,onOk:()=>void y(),okText:l(s==="install"?"settings.pluginsTab.install.confirm":"settings.pluginsTab.update.confirm"),confirmLoading:p,destroyOnClose:!0,forceRender:!0,width:560,children:t.jsxs(O,{direction:"vertical",style:{width:"100%"},size:"middle",children:[t.jsx(Ie,{type:"warning",showIcon:!0,message:l("settings.pluginsTab.install.warningTitle"),description:l("settings.pluginsTab.install.warningDescription")}),c?t.jsx(Ie,{type:"error",showIcon:!0,message:c,closable:!0,onClose:()=>u(null)}):null,t.jsxs(b,{layout:"vertical",form:g,initialValues:Kn,preserve:!0,children:[t.jsx(b.Item,{name:"sourceType",label:l("settings.pluginsTab.install.sourceType"),children:t.jsx(cr,{options:[{label:l("settings.pluginsTab.install.sourceTypeOptions.url"),value:"url"},{label:l("settings.pluginsTab.install.sourceTypeOptions.localDir"),value:"local_dir"},{label:l("settings.pluginsTab.install.sourceTypeOptions.localArchive"),value:"local_archive"}]})}),f==="url"?t.jsxs(t.Fragment,{children:[t.jsx(b.Item,{name:"url",label:l("settings.pluginsTab.install.url"),rules:[{required:!0,message:l("settings.pluginsTab.install.urlRequired")},{validator:async(d,I)=>{if(I)try{new URL(I)}catch{throw new Error(l("settings.pluginsTab.install.urlInvalid"))}}}],children:t.jsx(B,{placeholder:"https://example.com/plugin.zip",autoComplete:"off"})}),t.jsx(b.Item,{name:"sha256",label:l("settings.pluginsTab.install.sha256"),extra:l("settings.pluginsTab.install.sha256Help"),children:t.jsx(B,{placeholder:"e3b0c44298fc1c149afbf4c8996fb92427ae41e4",autoComplete:"off"})})]}):t.jsx(b.Item,{name:"path",label:l(f==="local_archive"?"settings.pluginsTab.install.archivePath":"settings.pluginsTab.install.dirPath"),rules:[{required:!0,message:l("settings.pluginsTab.install.pathRequired")}],children:t.jsx(B,{placeholder:f==="local_archive"?"/path/to/plugin.zip":"/path/to/plugin-dir",autoComplete:"off"})})]})]})})},{Text:Yi}=ue,{useToken:Zi}=Se,Qi=(e,s)=>hs(e)&&e.message.trim()||e instanceof Error&&e.message.trim()?e.message:s,eo=()=>{const{t:e}=re(),{token:s}=Zi(),[n,a]=At.useMessage(),{plugins:r,isLoading:i,loadError:l,refresh:g}=Ui(),[p,m]=o.useState(!1),[c,u]=o.useState(null),[f,D]=o.useState({}),y=async E=>{const j=await Ms.installPlugin(E);m(!1),j&&n.success(e("settings.pluginsTab.install.success",{name:j.name||j.id})),await g()},d=async E=>{if(!c)return;const j=await Ms.updatePlugin(c.id,E);u(null),j&&n.success(e("settings.pluginsTab.update.success",{name:j.name||j.id})),await g()},I=async E=>{D(j=>({...j,[E.id]:!0}));try{await Ms.deletePlugin(E.id),n.success(e("settings.pluginsTab.remove.success",{name:E.name||E.id})),await g()}catch(j){hs(j)&&j.status===404?n.error(e("settings.pluginsTab.errors.notFound")):n.error(Qi(j,e("settings.pluginsTab.remove.genericError")))}finally{D(j=>({...j,[E.id]:!1}))}};return t.jsxs(O,{direction:"vertical",size:s.marginMD,style:{width:"100%"},children:[a,t.jsx(V,{size:"small",title:e("settings.pluginsTab.title"),extra:t.jsx(R,{type:"primary",onClick:()=>m(!0),children:e("settings.pluginsTab.install.button")}),children:t.jsxs(O,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(Yi,{type:"secondary",children:e("settings.pluginsTab.description")}),l?t.jsx(Ie,{type:"error",showIcon:!0,message:l,action:t.jsx(R,{size:"small",onClick:()=>void g(),children:e("settings.pluginsTab.retry")})}):null,t.jsx(Wi,{plugins:r,loading:i,onUpdate:E=>u(E),onRemove:E=>I(E),isRemoving:E=>!!f[E]})]})}),t.jsx(Wn,{open:p,mode:"install",onCancel:()=>m(!1),onSubmit:y}),t.jsx(Wn,{open:!!c,mode:"update",pluginLabel:c?c.name||c.id:void 0,initialSource:(c==null?void 0:c.source)??null,onCancel:()=>u(null),onSubmit:d})]})},ja=1,to=365,Ta=e=>Number.isFinite(e)?Math.min(to,Math.max(ja,Math.floor(e??30))):30,Ys=e=>{if(!e)return null;const s=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!s)return null;const n=Number(s[1]),a=Number(s[2]),r=Number(s[3]),i=new Date(Date.UTC(n,a-1,r));return i.getUTCFullYear()!==n||i.getUTCMonth()!==a-1||i.getUTCDate()!==r?null:i},Zt=e=>e.toISOString().slice(0,10),so=(e,s)=>{const n=new Date(e.getTime());return n.setUTCDate(n.getUTCDate()+s),n},no=(e,s)=>{const n=s.getTime()-e.getTime(),a=Math.floor(n/864e5)+1;return Ta(a)},jn=(e,s=new Date)=>{const n=Ta(e.days),a=Zt(s),r=Ys(e.endDate)??Ys(a);if(!r)return{startDate:a,endDate:a,days:ja};const i=Ys(e.startDate);if(i){const g=r<i?i:r;return{startDate:Zt(i),endDate:Zt(g),days:no(i,g)}}const l=so(r,-(n-1));return{startDate:Zt(l),endDate:Zt(r),days:n}},ao=3e4,ro=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,io=(e={})=>{const{filters:s,autoRefreshMs:n=ao,enabled:a=!0}=e,r=o.useMemo(()=>({startDate:s==null?void 0:s.startDate,endDate:s==null?void 0:s.endDate,days:(s==null?void 0:s.days)??30,endpoint:s==null?void 0:s.endpoint,model:s==null?void 0:s.model,limit:(s==null?void 0:s.limit)??100}),[s==null?void 0:s.startDate,s==null?void 0:s.endDate,s==null?void 0:s.days,s==null?void 0:s.endpoint,s==null?void 0:s.model,s==null?void 0:s.limit]),i=o.useMemo(()=>jn({startDate:r.startDate,endDate:r.endDate,days:r.days}),[r.days,r.endDate,r.startDate]),[l,g]=o.useState(null),[p,m]=o.useState([]),[c,u]=o.useState([]),[f,D]=o.useState(!1),[y,d]=o.useState(!1),[I,E]=o.useState(null),j=o.useCallback(async x=>{x?D(!0):d(!0);try{const v={startDate:i.startDate,endDate:i.endDate,endpoint:r.endpoint,model:r.model},[L,A,U]=await Promise.all([is.getForwardSummary(v),is.getForwardByEndpoint(v),is.getForwardRequests({...v,limit:r.limit})]);g(L),m(A),u(U),E(null)}catch(v){E(ro(v,"Failed to load forward metrics"))}finally{x?D(!1):d(!1)}},[r.endpoint,r.model,r.limit,i.endDate,i.startDate]),w=o.useCallback(async()=>{await j(!1)},[j]);return o.useEffect(()=>{a&&j(!0)},[a,j]),o.useEffect(()=>{if(!a||n<=0)return;const x=window.setInterval(()=>{j(!1)},n);return()=>{window.clearInterval(x)}},[a,n,j]),{summary:l,endpointMetrics:p,requests:c,isLoading:f,isRefreshing:y,error:I,refresh:w}},oo=3e4,Gn=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,lo=(e={})=>{const{filters:s,autoRefreshMs:n=oo,service:a=is,enabled:r=!0}=e,i=o.useMemo(()=>({startDate:s==null?void 0:s.startDate,endDate:s==null?void 0:s.endDate,model:s==null?void 0:s.model,days:(s==null?void 0:s.days)??30,granularity:(s==null?void 0:s.granularity)??"daily",sessionLimit:(s==null?void 0:s.sessionLimit)??200}),[s==null?void 0:s.startDate,s==null?void 0:s.endDate,s==null?void 0:s.model,s==null?void 0:s.days,s==null?void 0:s.granularity,s==null?void 0:s.sessionLimit]),l=o.useMemo(()=>jn({startDate:i.startDate,endDate:i.endDate,days:i.days}),[i.days,i.endDate,i.startDate]),[g,p]=o.useState(null),[m,c]=o.useState([]),[u,f]=o.useState([]),[D,y]=o.useState([]),[d,I]=o.useState(null),[E,j]=o.useState([]),[w,x]=o.useState(null),[v,L]=o.useState(!1),[A,U]=o.useState(!1),[ie,H]=o.useState(!1),[C,k]=o.useState(null),M=o.useCallback(async ee=>{ee?U(!0):H(!0);try{const se=a.getMemorySummary?a.getMemorySummary({days:l.days,endDate:l.endDate}).catch(()=>null):Promise.resolve(null),le=a.getMemoryTimeline?a.getMemoryTimeline({days:l.days,endDate:l.endDate,granularity:i.granularity}).catch(()=>[]):Promise.resolve([]),[Q,ye,h,F,P,X]=await Promise.all([a.getSummary({startDate:l.startDate,endDate:l.endDate}),a.getByModel({startDate:l.startDate,endDate:l.endDate}),a.getSessions({startDate:l.startDate,endDate:l.endDate,model:i.model,limit:i.sessionLimit}),a.getDaily({days:l.days,endDate:l.endDate,granularity:i.granularity}),se,le]);p(Q),c(ye),f(h),y(F),I(P),j(X),k(null)}catch(se){k(Gn(se,"Failed to load metrics"))}finally{ee?U(!1):H(!1)}},[i.granularity,i.model,i.sessionLimit,l.days,l.endDate,l.startDate,a]),S=o.useCallback(async()=>{await M(!1)},[M]),G=o.useCallback(async ee=>{L(!0);try{const se=await a.getSessionDetail(ee);x(se)}catch(se){k(Gn(se,"Failed to load session detail"))}finally{L(!1)}},[a]),$=o.useCallback(()=>{x(null)},[]);return o.useEffect(()=>{r&&M(!0)},[r,M]),o.useEffect(()=>{if(!r||n<=0)return;const ee=window.setInterval(()=>{M(!1)},n);return()=>{window.clearInterval(ee)}},[r,n,M]),{summary:g,modelMetrics:m,sessions:u,timeline:D,memorySummary:d,memoryTimeline:E,sessionDetail:w,isLoading:A,isRefreshing:ie,isSessionDetailLoading:v,error:C,refresh:S,loadSessionDetail:G,clearSessionDetail:$}},co=3e4,uo=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,go=(e={})=>{const{filters:s,autoRefreshMs:n=co,enabled:a=!0}=e,r=o.useMemo(()=>({startDate:s==null?void 0:s.startDate,endDate:s==null?void 0:s.endDate,days:(s==null?void 0:s.days)??30,model:s==null?void 0:s.model}),[s==null?void 0:s.days,s==null?void 0:s.endDate,s==null?void 0:s.model,s==null?void 0:s.startDate]),i=o.useMemo(()=>jn({startDate:r.startDate,endDate:r.endDate,days:r.days}),[r.days,r.endDate,r.startDate]),[l,g]=o.useState(null),[p,m]=o.useState(!1),[c,u]=o.useState(!1),[f,D]=o.useState(null),y=o.useCallback(async I=>{I?m(!0):u(!0);try{const E=await is.getUsageBreakdown({startDate:i.startDate,endDate:i.endDate,model:r.model});g(E),D(null)}catch(E){D(uo(E,"Failed to load usage breakdown"))}finally{I?m(!1):u(!1)}},[r.model,i.endDate,i.startDate]),d=o.useCallback(async()=>{await y(!1)},[y]);return o.useEffect(()=>{a&&y(!0)},[a,y]),o.useEffect(()=>{if(!a||n<=0)return;const I=window.setInterval(()=>{y(!1)},n);return()=>{window.clearInterval(I)}},[a,n,y]),{data:l,isLoading:p,isRefreshing:c,error:f,refresh:d}},{useToken:po}=Se,mo=({data:e,loading:s})=>{const{t:n}=re(),{token:a}=po();if(s)return t.jsx(V,{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(V,{size:"small",className:"lotus-metric-card",title:n("settings.charts.endpointDistribution"),children:t.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:240,color:a.colorTextSecondary},children:n("settings.charts.noForwardMetrics")})});const r=e.map(i=>({endpoint:i.endpoint.split(".").pop()||i.endpoint,requests:i.requests,successful:i.successful,failed:i.failed}));return t.jsx(V,{size:"small",className:"lotus-metric-card",title:n("settings.charts.endpointDistribution"),children:t.jsx("div",{style:{width:"100%",height:240},children:t.jsx(Bt,{children:t.jsxs(xn,{data:r,children:[t.jsx(gs,{strokeDasharray:"3 3"}),t.jsx(ps,{dataKey:"endpoint"}),t.jsx(ms,{}),t.jsx(qt,{formatter:(i,l)=>[`${i}`,l.charAt(0).toUpperCase()+l.slice(1)]}),t.jsx(vn,{}),t.jsx(Ps,{dataKey:"successful",fill:"var(--lotus-chart-secondary)",name:n("settings.common.successful"),fillOpacity:.9,radius:[4,4,0,0]}),t.jsx(Ps,{dataKey:"failed",fill:"var(--lotus-chart-danger)",name:n("settings.common.failed"),fillOpacity:.9,radius:[4,4,0,0]})]})})})})},Zs=e=>e.replace(/\.0$/,""),ka=e=>e.toLocaleString(),Sa=e=>Number.isFinite(e)?e.toLocaleString(void 0,{maximumFractionDigits:20}):String(e),Tn=e=>{if(!Number.isFinite(e))return String(e);const s=Math.abs(e);if(s>=1e9){const n=s>=1e10?0:1;return`${Zs((e/1e9).toFixed(n))}B`}if(s>=1e6){const n=s>=1e7?0:1;return`${Zs((e/1e6).toFixed(n))}M`}if(s>=1e3){const n=s>=1e4?0:1;return`${Zs((e/1e3).toFixed(n))}K`}return ka(e)},ho=e=>Number.isFinite(e)&&Math.abs(e)>=1e3,_a=e=>Sa(e),ds=e=>{if(!Number.isFinite(e))return String(e);const s=Tn(e);return ho(e)?t.jsx(we,{title:t.jsx("div",{children:Sa(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:yo}=Se,fo=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),n=Math.floor(s/60),a=s%60;if(n>=60){const r=Math.floor(n/60),i=n%60;return`${r}h ${i}m`}return n>0?`${n}m ${a}s`:`${a}s`},Xn=({summary:e,loading:s})=>{const{t:n}=re(),{token:a}=yo();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(V,{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(V,{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(V,{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(V,{size:"small",className:"lotus-metric-card",children:t.jsx(De,{title:n("settings.forwardMetricsCards.avgResponseTime"),value:fo(e==null?void 0:e.avg_duration_ms),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:Pt}=ue,bo=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`},xo=e=>new Date(e).toLocaleString(),vo=({requests:e,loading:s})=>{const{t:n}=re(),a=[{title:n("settings.metricsTable.forward.columns.id"),dataIndex:"forward_id",key:"forward_id",width:120,render:r=>t.jsxs(Pt,{style:{fontSize:12},copyable:!0,children:[r.slice(0,8),"..."]})},{title:n("settings.metricsTable.forward.columns.endpoint"),dataIndex:"endpoint",key:"endpoint",width:150,render:r=>t.jsx(oe,{color:"processing",children:r.split(".").pop()||r})},{title:n("settings.metricsTable.forward.columns.model"),dataIndex:"model",key:"model",width:120},{title:n("settings.metricsTable.forward.columns.type"),dataIndex:"is_stream",key:"is_stream",width:80,render:r=>t.jsx(oe,{color:r?"purple":"processing",children:n(r?"settings.metricsTable.forward.typeStream":"settings.metricsTable.forward.typeSync")})},{title:n("settings.metricsTable.forward.columns.status"),key:"status",width:100,render:(r,i)=>{const l=i.status==="success"?"success":i.status==="error"?"error":"default";return t.jsx(dr,{status:l,text:i.status_code?t.jsxs("span",{children:[i.status,t.jsxs(Pt,{type:"secondary",style:{marginLeft:4},children:["(",i.status_code,")"]})]}):i.status||"-"})}},{title:n("settings.metricsTable.forward.columns.tokens"),key:"tokens",width:100,render:(r,i)=>i.token_usage?t.jsx(Pt,{children:ds(i.token_usage.total_tokens)}):t.jsx(Pt,{type:"secondary",children:"-"})},{title:n("settings.metricsTable.forward.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",width:100,render:r=>bo(r)},{title:n("settings.metricsTable.forward.columns.started"),dataIndex:"started_at",key:"started_at",width:160,render:r=>t.jsx(Pt,{type:"secondary",style:{fontSize:12},children:xo(r)})},{title:n("settings.metricsTable.forward.columns.error"),dataIndex:"error",key:"error",width:200,render:r=>r?t.jsx(Pt,{type:"danger",ellipsis:!0,style:{maxWidth:180},children:r}):t.jsx(Pt,{type:"secondary",children:"-"})}];return t.jsx(et,{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:jo}=Se,To=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString()},Jn=({summary:e,loading:s})=>{const{t:n}=re(),{token:a}=jo();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(V,{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(V,{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(V,{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(V,{size:"small",className:"lotus-metric-card",children:t.jsx(De,{title:n("settings.unifiedMetricsCards.lastReindex"),value:To(e==null?void 0:e.last_reindex_at),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:ko}=ue,So=({data:e,loading:s})=>{const{t:n}=re();return s?t.jsx(V,{size:"small",className:"lotus-metric-card",title:n("settings.charts.memoryTrendTitle"),children:t.jsx(gt,{active:!0,paragraph:{rows:5}})}):t.jsx(V,{size:"small",className:"lotus-metric-card",title:n("settings.charts.memoryTrendTitle"),children:e.length===0?t.jsx(Be,{image:Be.PRESENTED_IMAGE_SIMPLE,description:n("settings.charts.noMemoryTrend")}):t.jsxs(t.Fragment,{children:[t.jsx(ko,{type:"secondary",children:n("settings.charts.memoryTrendDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(Bt,{children:t.jsxs(ba,{data:e,children:[t.jsx(gs,{strokeDasharray:"3 3"}),t.jsx(ps,{dataKey:"label",minTickGap:24}),t.jsx(ms,{allowDecimals:!1}),t.jsx(qt,{}),t.jsx(vn,{}),t.jsx(Nt,{type:"monotone",dataKey:"total_memories",name:n("settings.charts.totalMemories"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),t.jsx(Nt,{type:"monotone",dataKey:"created_memories",name:n("settings.charts.createdMemories"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),t.jsx(Nt,{type:"monotone",dataKey:"updated_memories",name:n("settings.charts.updatedMemories"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{useToken:_o}=Se,wo=e=>{const s=Math.floor(e/1e3),n=Math.floor(s/60),a=s%60;return n>0?`${n}m ${a}s`:`${a}s`},Co=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)},Yn=({summary:e,sessions:s,loading:n})=>{const{t:a}=re(),{token:r}=_o();if(n)return t.jsx(gt,{active:!0,paragraph:{rows:1}});const i=Co(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(V,{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(V,{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(V,{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(V,{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(V,{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(V,{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(V,{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(V,{size:"small",className:"lotus-metric-card",children:t.jsx(De,{title:a("settings.metricsCards.avgSessionDuration"),value:i>0?wo(i):"-",valueStyle:{color:"var(--lotus-chart-accent)"}})})})]})},{Text:Mo}=ue,Zn=["var(--lotus-chart-primary)","var(--lotus-chart-secondary)","var(--lotus-chart-accent)","var(--lotus-chart-purple)","var(--lotus-chart-cyan)"],Eo=({data:e,loading:s})=>{const{t:n}=re();if(s)return t.jsx(V,{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(V,{size:"small",className:"lotus-metric-card",title:n("settings.charts.modelDistribution"),children:a.length===0?t.jsx(Be,{image:Be.PRESENTED_IMAGE_SIMPLE,description:n("settings.charts.noModelMetrics")}):t.jsxs(t.Fragment,{children:[t.jsx(Mo,{type:"secondary",children:n("settings.charts.modelDistributionDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(Bt,{children:t.jsxs(jr,{children:[t.jsx(Tr,{data:a,cx:"50%",cy:"50%",outerRadius:90,fill:"var(--lotus-chart-primary)",dataKey:"value",nameKey:"name",label:!0,children:a.map((r,i)=>t.jsx(kr,{fill:Zn[i%Zn.length]},`${r.name}-${i}`))}),t.jsx(qt,{formatter:r=>_a(r)})]})})})]})})},Po=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?"-":s.toLocaleString()},Do=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),n=Math.floor(s/60),a=s%60;if(n>=60){const r=Math.floor(n/60),i=n%60;return`${r}h ${i}m`}return n>0?`${n}m ${a}s`:`${a}s`},Io=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"}},Fo=(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}},Ao=({sessions:e,loading:s,onSelectSession:n})=>{const{t:a}=re(),r=[{title:a("settings.metricsTable.session.columns.session"),dataIndex:"session_id",key:"session_id",render:i=>t.jsx(we,{title:i,children:t.jsxs("span",{children:[i.slice(0,8),"..."]})}),width:120},{title:a("settings.metricsTable.session.columns.model"),dataIndex:"model",key:"model",width:160},{title:a("settings.metricsTable.session.columns.status"),dataIndex:"status",key:"status",width:120,render:i=>t.jsx(oe,{color:Io(i),children:Fo(i,a)})},{title:a("settings.metricsTable.session.columns.started"),dataIndex:"started_at",key:"started_at",render:i=>Po(i),width:200,sorter:(i,l)=>new Date(i.started_at).getTime()-new Date(l.started_at).getTime(),defaultSortOrder:"descend"},{title:a("settings.metricsTable.session.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",render:i=>Do(i),width:120},{title:a("settings.metricsTable.session.columns.tokens"),key:"tokens",render:(i,l)=>ds(l.total_token_usage.total_tokens),width:120,sorter:(i,l)=>i.total_token_usage.total_tokens-l.total_token_usage.total_tokens},{title:a("settings.metricsTable.session.columns.toolCalls"),dataIndex:"tool_call_count",key:"tool_call_count",width:120,sorter:(i,l)=>i.tool_call_count-l.tool_call_count},{title:a("settings.metricsTable.session.columns.messages"),dataIndex:"message_count",key:"message_count",width:120,sorter:(i,l)=>i.message_count-l.message_count},{title:a("settings.metricsTable.session.columns.action"),key:"action",fixed:"right",width:120,render:(i,l)=>t.jsx(R,{type:"link",onClick:()=>{n(l.session_id)},children:a("settings.metricsTable.session.view")})}];return t.jsx(et,{rowKey:"session_id",size:"small",className:"lotus-metric-table",columns:r,loading:s,dataSource:e,pagination:{pageSize:10,showSizeChanger:!1},scroll:{x:1100}})},{Text:Ro}=ue,Qn={message_count:"Message Count",last_message_id:"Last Message",pending_question:"Pending Question"},zo=e=>Qn[e]?Qn[e]:e.split("_").map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "),Lo=({breakdown:e,loading:s})=>{const{t:n}=re();if(s)return t.jsx(V,{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,i])=>({reason:r,label:n(`settings.syncMismatchReasons.${r}`,{defaultValue:zo(r)}),count:i})).sort((r,i)=>i.count-r.count);return t.jsx(V,{size:"small",className:"lotus-metric-card",title:n("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),extra:t.jsx(Ro,{type:"secondary",children:n("settings.metricsDashboard.syncMismatchBreakdownSubtitle",{defaultValue:"Grouped by execute sync mismatch reason"})}),children:a.length===0?t.jsx(Be,{image:Be.PRESENTED_IMAGE_SIMPLE,description:n("settings.metricsDashboard.noSyncMismatchBreakdown",{defaultValue:"No sync mismatches recorded for the selected range"})}):t.jsx("div",{style:{width:"100%",minWidth:0,height:280,minHeight:280},children:t.jsx(Bt,{children:t.jsxs(xn,{data:a,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[t.jsx(gs,{strokeDasharray:"3 3"}),t.jsx(ps,{type:"number",allowDecimals:!1}),t.jsx(ms,{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(Ps,{dataKey:"count",fill:"var(--lotus-chart-danger)",radius:[0,6,6,0],name:n("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})})]})})})})},{Text:Oo}=ue,No=({data:e,loading:s})=>{const{t:n}=re();return s?t.jsx(V,{size:"small",className:"lotus-metric-card",title:n("settings.charts.tokenUsageOverTime"),children:t.jsx(gt,{active:!0,paragraph:{rows:5}})}):t.jsx(V,{size:"small",className:"lotus-metric-card",title:n("settings.charts.tokenUsageOverTime"),children:e.length===0?t.jsx(Be,{image:Be.PRESENTED_IMAGE_SIMPLE,description:n("settings.charts.noTokenUsage")}):t.jsxs(t.Fragment,{children:[t.jsx(Oo,{type:"secondary",children:n("settings.charts.tokenUsageDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(Bt,{children:t.jsxs(ba,{data:e,children:[t.jsx(gs,{strokeDasharray:"3 3"}),t.jsx(ps,{dataKey:"label",minTickGap:24}),t.jsx(ms,{allowDecimals:!1,tickFormatter:Tn}),t.jsx(qt,{formatter:a=>_a(a)}),t.jsx(vn,{}),t.jsx(Nt,{type:"monotone",dataKey:"totalTokens",name:n("settings.charts.total"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),t.jsx(Nt,{type:"monotone",dataKey:"promptTokens",name:n("settings.charts.prompt"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),t.jsx(Nt,{type:"monotone",dataKey:"completionTokens",name:n("settings.charts.completion"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{Text:Vo}=ue,Qt=({title:e,subtitle:s,emptyText:n,color:a="var(--lotus-chart-primary)",data:r,loading:i,countLabel:l})=>{const{t:g}=re();return i?t.jsx(V,{size:"small",className:"lotus-metric-card",title:e,children:t.jsx(gt,{active:!0,paragraph:{rows:5}})}):t.jsx(V,{size:"small",className:"lotus-metric-card",title:e,children:r.length===0?t.jsx(Be,{image:Be.PRESENTED_IMAGE_SIMPLE,description:n}):t.jsxs(t.Fragment,{children:[s?t.jsx(Vo,{type:"secondary",children:s}):null,t.jsx("div",{style:{width:"100%",minWidth:0,height:280,marginTop:s?12:0},children:t.jsx(Bt,{children:t.jsxs(xn,{data:r,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[t.jsx(gs,{strokeDasharray:"3 3"}),t.jsx(ps,{type:"number",allowDecimals:!1}),t.jsx(ms,{dataKey:"label",type:"category",width:110}),t.jsx(qt,{formatter:p=>[p.toLocaleString(),l??g("settings.metricsDashboard.calls",{defaultValue:"Calls"})],labelFormatter:(p,m)=>{var u,f;const c=(f=(u=m==null?void 0:m[0])==null?void 0:u.payload)==null?void 0:f.meta;return c?`${p} · ${c}`:String(p)}}),t.jsx(Ps,{dataKey:"count",fill:a,radius:[0,6,6,0],name:l??g("settings.metricsDashboard.calls",{defaultValue:"Calls"})})]})})})]})})},{useToken:$o}=Se,ea=({summary:e,loading:s})=>{const{t:n}=re(),{token:a}=$o();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(i=>i.value>0);return r.length===0?null:t.jsx(Ye,{gutter:[a.marginSM,a.marginSM],children:r.map(i=>t.jsx(he,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(V,{size:"small",className:"lotus-metric-card",children:t.jsx(De,{title:i.title,value:i.value,precision:0,formatter:dt,valueStyle:{color:i.color}})})},i.key))})},{Text:Dt}=ue,{useToken:Bo}=Se,ta=e=>"date"in e?e.date:e.label,qo=(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)"},Ts=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),n=Math.floor(s/60),a=s%60;if(n>=60){const r=Math.floor(n/60),i=n%60;return`${r}h ${i}m`}return n>0?`${n}m ${a}s`:`${a}s`},sa=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString()},Qs=e=>{const s=Object.entries(e??{}).sort((n,a)=>a[1]-n[1]);return s.length===0?"-":s.slice(0,6).map(([n,a])=>`${n}: ${ka(a)}`).join(" • ")},en=(e,s=320)=>({width:"100%",display:"grid",gridTemplateColumns:`repeat(auto-fit, minmax(${s}px, 1fr))`,gap:e}),Uo=()=>{const e=o.useRef(null),[s,n]=o.useState(!0);return o.useEffect(()=>{const a=e.current;if(!a||typeof IntersectionObserver>"u")return;let r=!0,i=typeof document>"u"||document.visibilityState==="visible";const l=()=>n(r&&i),g=new IntersectionObserver(m=>{r=m.some(c=>c.isIntersecting),l()});g.observe(a);const p=()=>{i=document.visibilityState==="visible",l()};return document.addEventListener("visibilitychange",p),l(),()=>{g.disconnect(),document.removeEventListener("visibilitychange",p)}},[]),{ref:e,active:s}},Ho=()=>{const{t:e}=re(),{token:s}=Bo(),n=$a(z=>z.themeMode)==="dark",[a,r]=o.useState(void 0),[i,l]=o.useState(void 0),[g,p]=o.useState(void 0),[m,c]=o.useState(30),[u,f]=o.useState("daily"),{ref:D,active:y}=Uo(),{summary:d,modelMetrics:I,sessions:E,timeline:j,memorySummary:w,memoryTimeline:x,sessionDetail:v,isLoading:L,isRefreshing:A,isSessionDetailLoading:U,error:ie,refresh:H,loadSessionDetail:C,clearSessionDetail:k}=lo({enabled:y,filters:{startDate:a,endDate:i,model:g,days:m,granularity:u}}),{summary:M,endpointMetrics:S,requests:G,isLoading:$,isRefreshing:ee,error:se,refresh:le}=io({enabled:y,filters:{startDate:a,endDate:i,days:m,model:g}}),{data:Q,isLoading:ye,isRefreshing:h,error:F,refresh:P}=go({enabled:y,filters:{startDate:a,endDate:i,days:m,model:g}}),X=o.useMemo(()=>j.map(z=>({label:ta(z),promptTokens:z.total_token_usage.prompt_tokens,completionTokens:z.total_token_usage.completion_tokens,totalTokens:z.total_token_usage.total_tokens})),[j]),te=o.useMemo(()=>I.map(z=>({label:z.model,value:z.model})),[I]),ge=o.useMemo(()=>{const z=j.map(ce=>({label:ta(ce),sessions:ce.total_sessions,tokens:ce.total_token_usage.total_tokens})),be=z.reduce((ce,qe)=>Math.max(ce,qe.sessions),0);return{points:z,maxSessions:be}},[j]),ve=o.useMemo(()=>{const z=G.map(ce=>ce.duration_ms).filter(ce=>typeof ce=="number"&&ce>0).sort((ce,qe)=>ce-qe);if(z.length===0)return null;const be=Math.ceil(z.length*.95)-1;return z[Math.max(0,Math.min(be,z.length-1))]},[G]),_e=o.useMemo(()=>[{title:e("settings.metricsDashboard.roundColumns.round"),dataIndex:"round_id",key:"round_id",render:z=>`${z.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:z=>Ts(z)},{title:e("settings.metricsDashboard.roundColumns.tokens"),key:"tokens",render:(z,be)=>ds(be.token_usage.total_tokens)},{title:e("settings.metricsDashboard.roundColumns.toolCalls"),key:"tool_calls",render:(z,be)=>be.tool_calls.length}],[e]),Oe=o.useMemo(()=>{const z=(d==null?void 0:d.total_sessions)??0,be=(d==null?void 0:d.total_tokens.total_tokens)??0,ce=(d==null?void 0:d.total_tool_calls)??0,qe=(d==null?void 0:d.active_sessions)??0,mt=E.reduce((Ht,T)=>Ht+T.total_rounds,0),ht=(d==null?void 0:d.total_tokens_saved)??0,bs=(d==null?void 0:d.tool_context_tokens_saved)??0,zs=(d==null?void 0:d.non_tool_compression_tokens_saved)??0,Ls=(d==null?void 0:d.prompt_cached_tool_outputs)??0,Ut=(d==null?void 0:d.total_compression_events)??0,yt=(M==null?void 0:M.total_requests)??0,Os=(M==null?void 0:M.total_tokens.total_tokens)??0,Ns=(M==null?void 0:M.failed_requests)??0,Vs=G.filter(Ht=>Ht.is_stream).length,xs=z>0?qe/z*100:0,$s=yt>0?Ns/yt*100:0,Bs=G.length>0?Vs/G.length*100:0,St=be>0?Number((ht/be*100).toFixed(1)):0,qs=ht>0?Number((bs/ht*100).toFixed(1)):0;return[{title:e("settings.metricsDashboard.compactStats.avgTokensPerSession"),value:z>0?Math.round(be/z):0},{title:e("settings.metricsDashboard.compactStats.savedTokens",{defaultValue:"Saved Tokens"}),value:ht},{title:e("settings.metricsDashboard.compactStats.toolContextSavedTokens",{defaultValue:"Tool Context Saved Tokens"}),value:bs},{title:e("settings.metricsDashboard.compactStats.nonToolCompressionSavedTokens",{defaultValue:"Non-Tool Compression Saved Tokens"}),value:zs},{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:qs,suffix:"%"},{title:e("settings.metricsDashboard.compactStats.promptCachedToolOutputs",{defaultValue:"Prompt-Cached Tool Outputs"}),value:Ls},{title:e("settings.metricsDashboard.compactStats.compressionEvents",{defaultValue:"Compression Events"}),value:Ut},{title:e("settings.metricsDashboard.compactStats.avgRoundsPerSession"),value:z>0?Number((mt/z).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.toolCallsPerSession"),value:z>0?Number((ce/z).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.activeSessionRate"),value:Number(xs.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.avgTokensPerForward"),value:yt>0?Math.round(Os/yt):0},{title:e("settings.metricsDashboard.compactStats.forwardErrorRate"),value:Number($s.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.streamingRatio"),value:Number(Bs.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.p95ForwardLatency"),value:Ts(ve)},{title:e("settings.metricsDashboard.compactStats.modelCoverage"),value:I.length},{title:e("settings.metricsDashboard.compactStats.endpointCoverage"),value:S.length}]},[S.length,G,M,I.length,ve,E,d,e]),tt=o.useMemo(()=>{const z=(M==null?void 0:M.total_requests)??0,be=(M==null?void 0:M.failed_requests)??0,ce=G.filter(ht=>ht.is_stream).length,qe=G.length>0?ce/G.length*100:0,mt=z>0?be/z*100:0;return[{title:e("settings.metricsDashboard.forward.performance.p95Latency",{defaultValue:"P95 Latency"}),value:Ts(ve)},{title:e("settings.metricsDashboard.forward.performance.errorRate",{defaultValue:"Error Rate"}),value:Number(mt.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.streamingRatio",{defaultValue:"Streaming Ratio"}),value:Number(qe.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.endpointCoverage",{defaultValue:"Endpoint Coverage"}),value:S.length}]},[S.length,G,M,ve,e]),Ze=o.useMemo(()=>Q?[{label:e("settings.metricsDashboard.skillsAndMcp.mix.coreTools",{defaultValue:"Core Tools"}),count:Q.core_tool_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.skillLoads",{defaultValue:"Skill Loads"}),count:Q.skill_load_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.mcpCalls",{defaultValue:"MCP Calls"}),count:Q.mcp_calls}].filter(z=>z.count>0):[],[e,Q]),pt=o.useMemo(()=>((Q==null?void 0:Q.top_skills)??[]).map(z=>({label:z.skill_id,count:z.count})),[Q]),q=o.useMemo(()=>((Q==null?void 0:Q.top_mcp_servers)??[]).map(z=>({label:z.server_id,count:z.count,meta:e("settings.metricsDashboard.skillsAndMcp.meta.uniqueTools",{defaultValue:"{{count}} tools",count:z.unique_tools})})),[e,Q]),Te=o.useMemo(()=>((Q==null?void 0:Q.top_mcp_tools)??[]).map(z=>({label:z.tool_name,count:z.count,meta:z.server_id})),[Q]),Ne=o.useMemo(()=>((Q==null?void 0:Q.top_core_tools)??[]).map(z=>({label:z.name,count:z.count})),[Q]),N=v==null?void 0:v.session,fe=A||ee||h;return t.jsx("div",{ref:D,style:{width:"100%"},children:t.jsxs(O,{direction:"vertical",size:s.marginMD,style:{width:"100%"},children:[ie?t.jsx(Ie,{type:"error",showIcon:!0,message:ie}):null,se?t.jsx(Ie,{type:"error",showIcon:!0,message:se}):null,F?t.jsx(Ie,{type:"error",showIcon:!0,message:F}):null,t.jsx(V,{size:"small",title:e("settings.metricsDashboard.filtersTitle"),extra:t.jsx(R,{icon:t.jsx($t,{}),loading:fe,onClick:()=>{H(),le(),P()},children:e("settings.metricsDashboard.refresh")}),children:t.jsxs(O,{wrap:!0,children:[t.jsx(Fn,{placeholder:e("settings.metricsDashboard.startDate"),onChange:z=>{r(z?z.format("YYYY-MM-DD"):void 0)}}),t.jsx(Fn,{placeholder:e("settings.metricsDashboard.endDate"),onChange:z=>{l(z?z.format("YYYY-MM-DD"):void 0)}}),t.jsx(ae,{allowClear:!0,style:{minWidth:180},placeholder:e("settings.metricsDashboard.model"),value:g,options:te,onChange:z=>{p(z)}}),t.jsx(ae,{style:{width:120},value:m,options:[7,14,30,90].map(z=>({label:e("settings.metricsDashboard.daysOption",{value:z}),value:z})),onChange:z=>{c(z)}}),t.jsx(ae,{style:{width:140},value:u,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:z=>{f(z)}})]})}),t.jsx(V,{size:"small",title:e("settings.metricsDashboard.dashboardTitle"),children:t.jsx(Es,{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(V,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.overviewSections.scaleTitle",{defaultValue:"Scale & Activity"}),extra:t.jsx(Dt,{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(Yn,{summary:d,sessions:E,loading:L}),t.jsx(Xn,{summary:M,loading:$}),t.jsx(ea,{summary:Q,loading:ye}),t.jsx(Jn,{summary:w,loading:L})]})}),t.jsxs(V,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.overviewSections.efficiencyTitle",{defaultValue:"Compression & Efficiency Advantage"}),extra:t.jsx(Dt,{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:Oe.map(z=>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:z.title,value:z.value,suffix:z.suffix,formatter:typeof z.value=="number"?dt:void 0,valueStyle:{fontSize:s.fontSizeHeading4}})})},z.title))}),t.jsx(Dt,{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(Yn,{summary:d,sessions:E,loading:L}),t.jsxs("div",{style:en(s.marginSM,360),children:[t.jsx(No,{data:X,loading:L}),t.jsx(Eo,{data:I,loading:L})]}),t.jsxs("div",{style:en(s.marginSM,360),children:[t.jsx(Lo,{breakdown:d==null?void 0:d.sync_mismatch_breakdown,loading:L}),t.jsx(V,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.activityHeatmapTitle"),children:ge.points.length===0?t.jsx(Dt,{type:"secondary",children:e("settings.metricsDashboard.noActivity")}):t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(72px, 1fr))",gap:s.marginXS},children:ge.points.map(z=>t.jsxs("div",{style:{borderRadius:s.borderRadiusSM,padding:s.paddingXS,background:qo(z.sessions,ge.maxSessions),minHeight:64,color:z.sessions>0?"var(--lotus-metric-text-strong)":s.colorTextSecondary},children:[t.jsx("div",{style:{fontSize:12,lineHeight:1.2},children:z.label}),t.jsx("div",{style:{fontWeight:600,marginTop:4},children:e("settings.metricsDashboard.sessionsCount",{count:z.sessions})}),t.jsx("div",{style:{fontSize:12},children:e("settings.metricsDashboard.tokensAmount",{value:Tn(z.tokens)})})]},z.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(ea,{summary:Q,loading:ye}),t.jsxs("div",{style:en(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:Ze,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:pt,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:q,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:Te,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:Ne,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(Xn,{summary:M,loading:$}),t.jsx(V,{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:tt.map(z=>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:z.title,value:z.value,suffix:z.suffix,valueStyle:{fontSize:s.fontSizeHeading4}})})},z.title))})}),t.jsx(mo,{data:S,loading:$})]})},{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(Jn,{summary:w,loading:L}),t.jsx(So,{data:x,loading:L}),t.jsx(V,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.memory.breakdownTitle",{defaultValue:"Memory Breakdown"}),children:t.jsxs(Ue,{size:"small",bordered:!0,column:1,children:[t.jsx(Ue.Item,{label:e("settings.metricsDashboard.memory.byType",{defaultValue:"By Type"}),children:Qs(w==null?void 0:w.by_type)}),t.jsx(Ue.Item,{label:e("settings.metricsDashboard.memory.byStatus",{defaultValue:"By Status"}),children:Qs(w==null?void 0:w.by_status)}),t.jsx(Ue.Item,{label:e("settings.metricsDashboard.memory.byScope",{defaultValue:"By Scope"}),children:Qs(w==null?void 0:w.by_scope)}),t.jsx(Ue.Item,{label:e("settings.metricsDashboard.memory.lastDream",{defaultValue:"Last Dream"}),children:sa(w==null?void 0:w.last_dream_at)}),t.jsx(Ue.Item,{label:e("settings.metricsDashboard.memory.lastReindex",{defaultValue:"Last Reindex"}),children:sa(w==null?void 0:w.last_reindex_at)})]})})]})},{key:"records",label:e("settings.metricsDashboard.tabs.records"),children:t.jsx(Es,{size:"small",destroyInactiveTabPane:!0,items:[{key:"sessions",label:e("settings.metricsDashboard.sessionsTabLabel",{count:E.length}),children:t.jsx(V,{size:"small",extra:t.jsx(Dt,{type:"secondary",children:e("settings.metricsDashboard.sessionsHint")}),children:t.jsx(Ao,{sessions:E,loading:L,onSelectSession:z=>{C(z)}})})},{key:"forward-requests",label:e("settings.metricsDashboard.forwardTabLabel",{count:G.length}),children:t.jsx(V,{size:"small",children:t.jsx(vo,{requests:G,loading:$})})}]})}]})}),t.jsx(Xe,{title:e("settings.metricsDashboard.sessionMetricsTitle"),open:!!v,onCancel:k,onOk:k,width:960,destroyOnClose:!0,children:U?t.jsx(Dt,{children:e("settings.metricsDashboard.loadingSessionDetails")}):N?t.jsxs(O,{direction:"vertical",style:{width:"100%"},size:s.marginMD,children:[t.jsxs(Ue,{size:"small",bordered:!0,column:2,children:[t.jsx(Ue.Item,{label:e("settings.metricsDashboard.sessionDetail.sessionId"),span:2,children:N.session_id}),t.jsx(Ue.Item,{label:e("settings.metricsDashboard.sessionDetail.model"),children:N.model}),t.jsx(Ue.Item,{label:e("settings.metricsDashboard.sessionDetail.status"),children:N.status}),t.jsx(Ue.Item,{label:e("settings.metricsDashboard.sessionDetail.duration"),children:Ts(N.duration_ms)}),t.jsx(Ue.Item,{label:e("settings.metricsDashboard.sessionDetail.messages"),children:N.message_count}),t.jsx(Ue.Item,{label:e("settings.metricsDashboard.sessionDetail.totalTokens"),children:ds(N.total_token_usage.total_tokens)}),t.jsx(Ue.Item,{label:e("settings.metricsDashboard.sessionDetail.toolCalls"),children:N.tool_call_count})]}),t.jsx(et,{rowKey:"round_id",size:"small",columns:_e,dataSource:v.rounds,pagination:{pageSize:6,showSizeChanger:!1}})]}):t.jsx(Dt,{type:"secondary",children:e("settings.metricsDashboard.noDetail")})})]})})},{Text:ks}=ue,{useToken:Ko}=Se,Wo=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"},Go=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},Xo=()=>{const{t:e}=re(),{token:s}=Ko(),[n,a]=At.useMessage(),[r,i]=o.useState(!1),[l,g]=o.useState(!0),[p,m]=o.useState("placeholder"),c=o.useMemo(()=>[{label:e("settings.hooksTab.mode.placeholder"),value:"placeholder"},{label:e("settings.hooksTab.mode.error"),value:"error"},{label:e("settings.hooksTab.mode.ocr"),value:"ocr"},{label:e("settings.hooksTab.mode.vision"),value:"vision"}],[e]),u=o.useCallback(async()=>{i(!0);try{const d=await Re.getBambooConfig();g(Go(d)),m(Wo(d))}catch(d){n.error(d instanceof Error?d.message:e("settings.hooksTab.loadFailed"))}finally{i(!1)}},[n,e]),f=o.useCallback(async(d,I)=>{await Re.setBambooConfig({hooks:{image_fallback:{enabled:d,mode:I}}})},[]),D=o.useCallback(async d=>{i(!0);try{await f(d,p),n.success(e(d?"settings.hooksTab.enabled":"settings.hooksTab.disabled")),await u()}catch(I){n.error(I instanceof Error?I.message:e("settings.hooksTab.updateFailed"))}finally{i(!1)}},[u,p,n,f,e]),y=o.useCallback(async d=>{var I;i(!0);try{await f(l,d),n.success(e("settings.hooksTab.modeUpdated",{mode:((I=c.find(E=>E.value===d))==null?void 0:I.label)??d})),await u()}catch(E){n.error(E instanceof Error?E.message:e("settings.hooksTab.modeUpdateFailed"))}finally{i(!1)}},[l,u,c,n,f,e]);return o.useEffect(()=>{u()},[u]),t.jsxs(W,{vertical:!0,gap:s.marginLG,children:[a,t.jsx(V,{size:"small",loading:r,children:t.jsxs(W,{vertical:!0,gap:s.marginXS,children:[t.jsx(ks,{strong:!0,children:e("settings.hooksTab.title")}),t.jsxs(W,{align:"center",justify:"space-between",children:[t.jsx(ks,{children:e("settings.hooksTab.enableImagePreflight")}),t.jsx(pe,{checked:l,onChange:D})]}),t.jsxs(W,{align:"center",justify:"space-between",children:[t.jsx(ks,{children:e("settings.hooksTab.modeLabel")}),t.jsx(ae,{style:{width:180},value:p,options:c,onChange:y,disabled:!l})]}),t.jsx(ks,{type:"secondary",style:{fontSize:s.fontSizeSM},children:e("settings.hooksTab.description")})]})})]})};function Ae(e){return String(e??"").trim()||void 0}function wa(e){return{type:"interval",every_seconds:e}}function Jo(e){const s=Ae(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 na(e){switch(e.trigger_type){case"interval":{const s=Number(e.interval_seconds||0);return s<=0?{errorKey:"settings.schedulesTab.validation.intervalRequired"}:{trigger:wa(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}=Jo(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=Ae(e.cron_expr);return s?{trigger:{type:"cron",expr:s}}:{errorKey:"settings.schedulesTab.validation.cronRequired"}}default:return{errorKey:"settings.schedulesTab.validation.triggerRequired"}}}function aa(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}=ue,ot=fn.getInstance();function Yo(e){switch(e){case"success":return"success";case"failed":case"cancelled":return"error";case"running":return"processing";case"queued":return"gold";case"missed":case"skipped":default:return"default"}}const Zo=[{label:de.t("settings.schedulesTab.weekdays.mon"),value:"mon"},{label:de.t("settings.schedulesTab.weekdays.tue"),value:"tue"},{label:de.t("settings.schedulesTab.weekdays.wed"),value:"wed"},{label:de.t("settings.schedulesTab.weekdays.thu"),value:"thu"},{label:de.t("settings.schedulesTab.weekdays.fri"),value:"fri"},{label:de.t("settings.schedulesTab.weekdays.sat"),value:"sat"},{label:de.t("settings.schedulesTab.weekdays.sun"),value:"sun"}];function Qo(e){return(e==null?void 0:e.type)==="interval"?e.every_seconds:null}function el(e){switch(e.type){case"interval":return de.t("settings.schedulesTab.triggerLabels.interval",{type:de.t("settings.schedulesTab.triggerTypes.interval"),seconds:e.every_seconds});case"daily":return de.t("settings.schedulesTab.triggerLabels.daily",{type:de.t("settings.schedulesTab.triggerTypes.daily"),time:`${String(e.hour).padStart(2,"0")}:${String(e.minute).padStart(2,"0")}`});case"weekly":return de.t("settings.schedulesTab.triggerLabels.weekly",{type:de.t("settings.schedulesTab.triggerTypes.weekly"),weekdays:e.weekdays.join(", ")});case"monthly":return de.t("settings.schedulesTab.triggerLabels.monthly",{type:de.t("settings.schedulesTab.triggerTypes.monthly"),days:e.days.join(", ")});case"cron":return de.t("settings.schedulesTab.triggerLabels.cron",{type:de.t("settings.schedulesTab.triggerTypes.cron"),expr:e.expr})}}function tl(e){switch(e==null?void 0:e.type){case"skip":return de.t("settings.schedulesTab.misfirePolicyOptions.skip");case"catch_up_all":return de.t("settings.schedulesTab.misfirePolicyOptions.catchUpAll");case"catch_up_window":return de.t("settings.schedulesTab.misfirePolicyOptions.catchUpWindow");case"run_once":default:return de.t("settings.schedulesTab.misfirePolicyOptions.runOnce")}}function sl(e){switch(e){case"allow":return de.t("settings.schedulesTab.overlapPolicyOptions.allow");case"skip":return de.t("settings.schedulesTab.overlapPolicyOptions.skip");case"queue_one":default:return de.t("settings.schedulesTab.overlapPolicyOptions.queueOne")}}function nl(e){var s;return(s=e.state)!=null&&s.next_fire_at?String(e.state.next_fire_at):"-"}function al(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 rl(e){var s,n,a,r;return((s=e.state)==null?void 0:s.running_run_count)>0?{color:"processing",label:de.t("settings.schedulesTab.statusLabels.running"),detail:de.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:de.t("settings.schedulesTab.statusLabels.queued"),detail:de.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:de.t("settings.schedulesTab.statusLabels.failing"),detail:de.t("settings.schedulesTab.statusDetails.consecutiveFailures",{count:e.state.consecutive_failures})}:e.enabled?(r=e.state)!=null&&r.last_success_at?{color:"success",label:de.t("settings.schedulesTab.statusLabels.healthy"),detail:de.t("settings.schedulesTab.statusDetails.lastRunSucceeded")}:{color:"default",label:de.t("settings.schedulesTab.statusLabels.idle")}:{color:"default",label:de.t("settings.schedulesTab.statusLabels.disabled")}}function il(e){var n,a,r,i,l,g,p,m;const s={name:e.name,enabled:e.enabled,trigger_type:e.trigger.type,timezone:e.timezone||"",start_at:e.start_at||"",end_at:e.end_at||"",misfire_policy:((n=e.misfire_policy)==null?void 0:n.type)||"run_once",overlap_policy:e.overlap_policy||"queue_one",system_prompt:((a=e.run_config)==null?void 0:a.system_prompt)||"",task_message:((r=e.run_config)==null?void 0:r.task_message)||"",model:((i=e.run_config)==null?void 0:i.model)||"",workspace_path:((l=e.run_config)==null?void 0:l.workspace_path)||"",enhance_prompt:((g=e.run_config)==null?void 0:g.enhance_prompt)||"",auto_execute:!!((p=e.run_config)!=null&&p.auto_execute)};switch(((m=e.misfire_policy)==null?void 0:m.type)==="catch_up_window"&&(s.catch_up_window_max_runs=e.misfire_policy.max_catch_up_runs,s.catch_up_window_max_lateness_seconds=e.misfire_policy.max_lateness_seconds),e.trigger.type){case"interval":s.interval_seconds=e.trigger.every_seconds;break;case"daily":s.daily_hour=e.trigger.hour,s.daily_minute=e.trigger.minute;break;case"weekly":s.weekly_weekdays=e.trigger.weekdays,s.weekly_hour=e.trigger.hour,s.weekly_minute=e.trigger.minute;break;case"monthly":s.monthly_days=e.trigger.days.join(", "),s.monthly_hour=e.trigger.hour,s.monthly_minute=e.trigger.minute;break;case"cron":s.cron_expr=e.trigger.expr;break}return s}function tn({hourName:e,minuteName:s}){const{t:n}=re();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 ol(){const{t:e}=re(),[s,n]=At.useMessage(),[a,r]=o.useState(!1),[i,l]=o.useState([]),[g,p]=o.useState({open:!1,scheduleId:null,sessions:[],loading:!1}),[m,c]=o.useState({open:!1,scheduleId:null,runs:[],loading:!1}),[u,f]=o.useState({open:!1,schedule:null,saving:!1}),D=dn(C=>C.close),[y]=b.useForm(),[d]=b.useForm(),I=b.useWatch("trigger_type",y),E=b.useWatch("misfire_policy",y),j=b.useWatch("trigger_type",d),w=b.useWatch("misfire_policy",d),x=o.useCallback(async()=>{r(!0);try{const C=await ot.listSchedules();l(C.schedules||[])}catch(C){console.error("[Schedules] Failed to load schedules:",C),s.error(e("settings.schedulesTab.loadFailed"))}finally{r(!1)}},[s,e]),v=o.useCallback(async(C,k,M)=>{try{await M()}catch(S){console.error(`[Schedules] ${C}:`,S),s.error(e(k))}},[s,e]);o.useEffect(()=>{x()},[x]);const L=[{value:"interval",label:e("settings.schedulesTab.triggerTypes.interval")},{value:"daily",label:e("settings.schedulesTab.triggerTypes.daily")},{value:"weekly",label:e("settings.schedulesTab.triggerTypes.weekly")},{value:"monthly",label:e("settings.schedulesTab.triggerTypes.monthly")},{value:"cron",label:e("settings.schedulesTab.triggerTypes.cron")}],A=[{value:"run_once",label:e("settings.schedulesTab.misfirePolicyOptions.runOnce")},{value:"skip",label:e("settings.schedulesTab.misfirePolicyOptions.skip")},{value:"catch_up_all",label:e("settings.schedulesTab.misfirePolicyOptions.catchUpAll")},{value:"catch_up_window",label:e("settings.schedulesTab.misfirePolicyOptions.catchUpWindow")}],U=[{value:"queue_one",label:e("settings.schedulesTab.overlapPolicyOptions.queueOne")},{value:"skip",label:e("settings.schedulesTab.overlapPolicyOptions.skip")},{value:"allow",label:e("settings.schedulesTab.overlapPolicyOptions.allow")}],ie=(C,k)=>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(B,{})}),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(ae,{options:L})}),t.jsx(b.Item,{label:e("settings.schedulesTab.form.enabled"),name:"enabled",valuePropName:"checked",style:{width:120},children:t.jsx(pe,{})})]}),C==="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,C==="daily"?t.jsx(tn,{hourName:"daily_hour",minuteName:"daily_minute"}):null,C==="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(ae,{mode:"multiple",options:Zo})}),t.jsx(tn,{hourName:"weekly_hour",minuteName:"weekly_minute"})]}):null,C==="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(B,{placeholder:e("settings.schedulesTab.form.monthlyDaysPlaceholder")})}),t.jsx(tn,{hourName:"monthly_hour",minuteName:"monthly_minute"})]}):null,C==="cron"?t.jsx(b.Item,{label:e("settings.schedulesTab.form.cronExpr"),name:"cron_expr",children:t.jsx(B,{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(B,{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(B,{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(B,{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(ae,{options:A})}),t.jsx(b.Item,{label:e("settings.schedulesTab.form.overlapPolicy"),name:"overlap_policy",style:{flex:"1 1 240px"},children:t.jsx(ae,{options:U})})]}),k==="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(B.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(B.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(B,{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(B,{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(pe,{})})]}),t.jsx(b.Item,{label:e("settings.schedulesTab.form.enhancePrompt"),name:"enhance_prompt",children:t.jsx(B.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})})]}),H=o.useMemo(()=>[{title:e("settings.schedulesTab.columns.name"),key:"name",render:(C,k)=>t.jsxs(W,{vertical:!0,gap:6,children:[t.jsx(ze,{strong:!0,children:k.name}),t.jsxs(W,{gap:6,wrap:"wrap",children:[t.jsx(oe,{children:el(k.trigger)}),k.timezone?t.jsx(oe,{color:"blue",children:k.timezone}):null,t.jsx(oe,{children:tl(k.misfire_policy)}),t.jsx(oe,{children:sl(k.overlap_policy)})]})]})},{title:e("settings.schedulesTab.columns.status"),key:"status",render:(C,k)=>{const M=rl(k);return t.jsxs(W,{vertical:!0,gap:4,children:[t.jsx(oe,{color:M.color,children:M.label}),M.detail?t.jsx(ze,{type:"secondary",children:M.detail}):null]})}},{title:e("settings.schedulesTab.columns.activity"),key:"activity",render:(C,k)=>{var M,S,G,$;return t.jsxs(W,{vertical:!0,gap:2,children:[t.jsx(ze,{type:"secondary",children:e("settings.schedulesTab.activityLabels.queued",{count:((M=k.state)==null?void 0:M.queued_run_count)??0})}),t.jsx(ze,{type:"secondary",children:e("settings.schedulesTab.activityLabels.running",{count:((S=k.state)==null?void 0:S.running_run_count)??0})}),t.jsx(ze,{type:"secondary",children:e("settings.schedulesTab.activityLabels.ok",{count:((G=k.state)==null?void 0:G.total_success_count)??0})}),t.jsx(ze,{type:"secondary",children:e("settings.schedulesTab.activityLabels.fail",{count:(($=k.state)==null?void 0:$.total_failure_count)??0})})]})}},{title:e("settings.schedulesTab.columns.nextRun"),key:"next_run_at",render:(C,k)=>t.jsx(ze,{type:"secondary",children:nl(k)})},{title:e("settings.schedulesTab.columns.lastRun"),key:"last_run_at",render:(C,k)=>t.jsx(ze,{type:"secondary",children:al(k)})},{title:e("settings.schedulesTab.columns.autoExecute"),key:"auto_execute",render:(C,k)=>{var M,S;return t.jsx(ze,{type:(M=k.run_config)!=null&&M.auto_execute?void 0:"secondary",children:(S=k.run_config)!=null&&S.auto_execute?e("settings.schedulesTab.yes"):e("settings.schedulesTab.no")})}},{title:e("settings.schedulesTab.columns.model"),key:"model",render:(C,k)=>{var M;return t.jsx(ze,{type:"secondary",children:(M=k.run_config)!=null&&M.model?String(k.run_config.model):"-"})}},{title:e("settings.schedulesTab.columns.enabled"),key:"enabled",render:(C,k)=>t.jsx(pe,{checked:k.enabled,onChange:async M=>{await v("Failed to toggle","settings.schedulesTab.updateFailed",async()=>{await ot.patchSchedule(k.id,{enabled:M}),await x()})}})},{title:e("settings.schedulesTab.columns.actions"),key:"actions",render:(C,k)=>{const M=t.jsx(Ee,{min:1,value:Qo(k.trigger)??void 0,disabled:k.trigger.type!=="interval",onChange:async S=>{const G=typeof S=="number"?S:null;!G||G<=0||await v("Failed to patch interval","settings.schedulesTab.updateFailed",async()=>{await ot.patchSchedule(k.id,{trigger:wa(G)}),await x()})}});return t.jsxs(W,{vertical:!0,gap:8,children:[t.jsxs(W,{gap:8,wrap:"wrap",children:[t.jsx(R,{size:"small",onClick:()=>{f({open:!0,schedule:k,saving:!1}),d.setFieldsValue(il(k))},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(k.id),s.success(e("settings.schedulesTab.enqueuedRun")),await x()})},children:e("settings.schedulesTab.actions.runNow")}),t.jsx(R,{size:"small",onClick:async()=>{p(S=>({...S,open:!0,scheduleId:k.id,loading:!0,sessions:[]}));try{const S=await ot.listScheduleSessions(k.id);p(G=>({...G,open:!0,scheduleId:k.id,loading:!1,sessions:(S.sessions||[]).map($=>({id:$.id,title:$.title,updated_at:$.updated_at}))}))}catch(S){console.error("[Schedules] Failed to list sessions:",S),s.error(e("settings.schedulesTab.loadSessionsFailed")),p(G=>({...G,loading:!1}))}},children:e("settings.schedulesTab.actions.sessions")}),t.jsx(R,{size:"small",onClick:async()=>{c(S=>({...S,open:!0,scheduleId:k.id,loading:!0,runs:[]}));try{const S=await ot.listScheduleRuns(k.id);c(G=>({...G,open:!0,scheduleId:k.id,loading:!1,runs:S.runs||[]}))}catch(S){console.error("[Schedules] Failed to list runs:",S),s.error(e("settings.schedulesTab.loadRunsFailed")),c(G=>({...G,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(k.id),s.success(e("settings.schedulesTab.deleted")),await x()})},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")}),k.trigger.type==="interval"?M:t.jsx(we,{title:e("settings.schedulesTab.nonIntervalReadOnly"),children:t.jsx("span",{children:M})})]})]})}}],[d,s,x,v,e]);return t.jsxs(W,{vertical:!0,gap:16,children:[n,t.jsx(V,{title:e("settings.schedulesTab.createTitle"),className:"lotus-settings-card",children:t.jsxs(b,{form:y,layout:"vertical",initialValues:{name:e("settings.schedulesTab.defaultName"),trigger_type:"interval",interval_seconds:3600,daily_hour:9,daily_minute:0,weekly_weekdays:["mon"],weekly_hour:9,weekly_minute:0,monthly_days:"1",monthly_hour:9,monthly_minute:0,cron_expr:"",timezone:"",start_at:"",end_at:"",enabled:!1,task_message:"",model:"",auto_execute:!0,misfire_policy:"run_once",overlap_policy:"queue_one",catch_up_window_max_runs:1,catch_up_window_max_lateness_seconds:60},onFinish:async C=>{try{const k=!!C.auto_execute,M=Ae(C.task_message),S=Ae(C.model);if(k&&!M){s.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:G,errorKey:$}=na(C);if(!G){s.error(e($||"settings.schedulesTab.validation.triggerRequired"));return}await ot.createSchedule({name:String(C.name||"").trim(),trigger:G,timezone:Ae(C.timezone),start_at:Ae(C.start_at),end_at:Ae(C.end_at),misfire_policy:aa(C),overlap_policy:C.overlap_policy,enabled:!!C.enabled,run_config:{system_prompt:Ae(C.system_prompt),task_message:M,model:S,workspace_path:Ae(C.workspace_path),enhance_prompt:Ae(C.enhance_prompt),auto_execute:k}}),s.success(e("settings.schedulesTab.created")),y.resetFields(),await x()}catch(k){console.error("[Schedules] Failed to create schedule:",k),s.error(e("settings.schedulesTab.createFailed"))}},children:[ie(I,E),t.jsx(R,{type:"primary",htmlType:"submit",children:e("settings.schedulesTab.actions.create")})]})}),t.jsx(V,{title:e("settings.schedulesTab.listTitle"),className:"lotus-settings-card",extra:t.jsx(R,{onClick:()=>void x(),loading:a,children:e("settings.schedulesTab.actions.refresh")}),children:t.jsx(et,{rowKey:"id",columns:H,dataSource:i,loading:a,pagination:{pageSize:10},scroll:{x:1500}})}),t.jsx(Xe,{title:e("settings.schedulesTab.scheduleSessionsTitle"),open:g.open,onCancel:()=>p(C=>({...C,open:!1,scheduleId:null})),footer:null,children:g.loading?t.jsx(ze,{type:"secondary",children:e("settings.schedulesTab.loading")}):t.jsx(W,{vertical:!0,gap:8,children:g.sessions.length===0?t.jsx(ze,{type:"secondary",children:e("settings.schedulesTab.noSessionsYet")}):g.sessions.map(C=>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:C.title}),t.jsxs(ze,{type:"secondary",ellipsis:!0,children:[C.id," • ",C.updated_at]})]}),t.jsx(R,{size:"small",onClick:()=>{Ba(C.id,{forceRefreshIndex:!0,forceLoadHistory:!0,subscribeIfRunning:!0,forceSubscribe:!0}),D()},children:e("settings.schedulesTab.actions.open")})]},C.id))})}),t.jsx(Xe,{title:e("settings.schedulesTab.scheduleRunsTitle"),open:m.open,onCancel:()=>c(C=>({...C,open:!1,scheduleId:null})),footer:null,width:960,children:m.loading?t.jsx(ze,{type:"secondary",children:e("settings.schedulesTab.loading")}):m.runs.length===0?t.jsx(ze,{type:"secondary",children:e("settings.schedulesTab.noRunsYet")}):t.jsx(et,{rowKey:"run_id",pagination:{pageSize:8},dataSource:m.runs,columns:[{title:e("settings.schedulesTab.runHistory.columns.status"),key:"status",render:(C,k)=>t.jsx(oe,{color:Yo(k.status),children:k.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:(C,k)=>k.started_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.completedAt"),key:"completed_at",render:(C,k)=>k.completed_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.session"),key:"session_id",render:(C,k)=>k.session_id||"-"},{title:e("settings.schedulesTab.runHistory.columns.duration"),key:"execution_duration_ms",render:(C,k)=>k.execution_duration_ms!=null?`${k.execution_duration_ms}ms`:"-"},{title:e("settings.schedulesTab.runHistory.columns.outcome"),key:"outcome_reason",render:(C,k)=>k.outcome_reason||(k.was_catch_up?"catch-up":"-")}]})}),t.jsx(Xe,{title:e("settings.schedulesTab.editTitle"),open:u.open,onCancel:()=>f({open:!1,schedule:null,saving:!1}),okText:e("settings.schedulesTab.actions.save"),confirmLoading:u.saving,onOk:()=>d.submit(),forceRender:!0,children:t.jsx(b,{form:d,layout:"vertical",onFinish:async C=>{const k=u.schedule;if(!k)return;const M=!!C.auto_execute,S=Ae(C.task_message),G=Ae(C.model);if(M&&!S){s.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:$,errorKey:ee}=na(C);if(!$){s.error(e(ee||"settings.schedulesTab.validation.triggerRequired"));return}f(se=>({...se,saving:!0}));try{await ot.patchSchedule(k.id,{name:String(C.name||"").trim()||void 0,enabled:!!C.enabled,trigger:$,timezone:Ae(C.timezone),start_at:Ae(C.start_at),end_at:Ae(C.end_at),misfire_policy:aa(C),overlap_policy:C.overlap_policy,run_config:{system_prompt:Ae(C.system_prompt),task_message:S,model:G,workspace_path:Ae(C.workspace_path),enhance_prompt:Ae(C.enhance_prompt),auto_execute:M}}),s.success(e("settings.schedulesTab.updated")),f({open:!1,schedule:null,saving:!1}),await x()}catch(se){console.error("[Schedules] Failed to patch schedule:",se),s.error(e("settings.schedulesTab.updateFailed")),f(le=>({...le,saving:!1}))}},children:ie(j,w)})})]})}const{Text:es}=ue,ts=fn.getInstance();function ll(){const{t:e}=re(),{modal:s,message:n}=rt.useApp(),a=Le(y=>y.chats),r=Le(y=>y.currentSessionId),i=Le(y=>y.refreshChats),l=Le(y=>y.loadChats),g=Le(y=>y.loadChatHistory),[p,m]=o.useState(!0),[c,u]=o.useState(!1),f=o.useMemo(()=>r?a.find(y=>y.id===r)??null:null,[a,r]),D=async y=>{if(!c){u(!0);try{await y()}finally{u(!1)}}};return t.jsxs(W,{vertical:!0,gap:16,children:[t.jsx(V,{size:"small",title:e("settings.sessionsTab.currentSessionTitle"),children:f?t.jsxs(W,{vertical:!0,gap:4,children:[t.jsx(es,{strong:!0,ellipsis:!0,children:f.title}),t.jsxs(es,{type:"secondary",ellipsis:!0,children:[e("settings.sessionsTab.id"),": ",f.id," ","•"," ",e("settings.sessionsTab.kind"),": ",f.kind]}),t.jsx(W,{gap:8,wrap:"wrap",style:{marginTop:8},children:t.jsx(R,{danger:!0,loading:c,onClick:()=>{s.confirm({title:e("settings.sessionsTab.clearMessagesTitle"),content:e("settings.sessionsTab.clearMessagesContent"),okText:e("settings.sessionsTab.clear"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await D(async()=>{await ts.clearSession(f.id),await g(f.id),await i(),n.success(e("settings.sessionsTab.sessionCleared"))})}})},children:e("settings.sessionsTab.clearMessages")})})]}):t.jsx(es,{type:"secondary",children:e("settings.sessionsTab.noActiveSession")})}),t.jsxs(V,{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(pe,{checked:p,onChange:m})]}),t.jsxs(W,{gap:8,wrap:"wrap",children:[t.jsx(R,{danger:!0,loading:c,onClick:()=>{s.confirm({title:e("settings.sessionsTab.deleteAllTitle"),content:e(p?"settings.sessionsTab.deleteAllKeepPinned":"settings.sessionsTab.deleteAllIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await D(async()=>{await ts.cleanupSessions("all",p),await l(),n.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteAll")}),t.jsx(R,{danger:!0,loading:c,onClick:()=>{s.confirm({title:e("settings.sessionsTab.deleteEmptyTitle"),content:e(p?"settings.sessionsTab.deleteEmptyKeepPinned":"settings.sessionsTab.deleteEmptyIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await D(async()=>{await ts.cleanupSessions("empty",p),await l(),n.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteEmpty")}),t.jsx(R,{danger:!0,loading:c,onClick:()=>{s.confirm({title:e("settings.sessionsTab.deleteChildrenTitle"),content:e(p?"settings.sessionsTab.deleteChildrenKeepPinned":"settings.sessionsTab.deleteChildrenIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await D(async()=>{await ts.cleanupSessions("children",p),await l(),n.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteChildren")})]})]}),t.jsxs(V,{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:c,onClick:()=>{s.confirm({title:e("settings.sessionsTab.devResetConfirmTitle"),content:e("settings.sessionsTab.devResetConfirmContent"),okText:e("settings.sessionsTab.reset"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await D(async()=>{await ts.devResetSessions(),await l(),n.success(e("settings.sessionsTab.devResetDone"))})}})},children:e("settings.sessionsTab.devResetAction")})})]})]})}const Ca="notifications/preferences";function Ma(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 cl(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 dl(){const e=await $e.get(Ca);return Ma(e)}async function ul(e){const s=await $e.put(Ca,cl(e));return Ma(s)}const us=e=>typeof e=="string"&&e.trim().length>0&&[...e.trim()].every(s=>s==="*"||s==="."),{Text:Ge}=ue,{useToken:gl}=Se,mn="https://ntfy.sh",hn="https://api.day.app";function sn(e){var n,a,r,i,l,g,p,m,c,u;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)??mn,ntfyTopic:((i=e==null?void 0:e.ntfy)==null?void 0:i.topic)??"",ntfyToken:us((l=e==null?void 0:e.ntfy)==null?void 0:l.token)?"":((g=e==null?void 0:e.ntfy)==null?void 0:g.token)??"",barkEnabled:((p=e==null?void 0:e.bark)==null?void 0:p.enabled)??!1,barkBaseUrl:((m=e==null?void 0:e.bark)==null?void 0:m.base_url)??hn,barkDeviceKey:us((c=e==null?void 0:e.bark)==null?void 0:c.device_key)?"":((u=e==null?void 0:e.bark)==null?void 0:u.device_key)??""}}const pl=()=>{var k,M;const{t:e}=re(),{token:s}=gl(),[n,a]=o.useState(void 0),[r,i]=o.useState(()=>sn(void 0)),[l,g]=o.useState(!0),[p,m]=o.useState(null),[c,u]=o.useState(!1),[f,D]=o.useState(null),[y,d]=o.useState(!1),[I,E]=o.useState(!1),[j,w]=o.useState(null),[x,v]=o.useState(null),L=o.useCallback(async()=>{g(!0),m(null);try{const S=await Re.getBambooConfig();a(S.notifications),i(sn(S.notifications))}catch(S){m(Hs(S))}finally{g(!1)}},[]);o.useEffect(()=>{L()},[L]);const A=S=>i(G=>({...G,...S})),U=us((k=n==null?void 0:n.ntfy)==null?void 0:k.token),ie=us((M=n==null?void 0:n.bark)==null?void 0:M.device_key),H=async()=>{u(!0),D(null),d(!1);try{const S=r.ntfyToken.trim(),G=r.barkDeviceKey.trim(),$={notifications:{desktop:{enabled:r.desktopMode==="auto"?null:r.desktopMode==="on"},ntfy:{enabled:r.ntfyEnabled,base_url:r.ntfyBaseUrl.trim()||mn,topic:r.ntfyTopic.trim(),...S?{token:S}:{}},bark:{enabled:r.barkEnabled,base_url:r.barkBaseUrl.trim()||hn,...G?{device_key:G}:{}}}},ee=await Re.setBambooConfig($);a(ee.notifications),i(sn(ee.notifications)),d(!0),setTimeout(()=>d(!1),2500)}catch(S){D(Hs(S))}finally{u(!1)}},C=async()=>{E(!0),w(null),v(null);try{const S=await $e.post("notifications/test");v(S.attempted)}catch(S){w(Hs(S))}finally{E(!1)}};return t.jsx(V,{size:"small",className:"lotus-settings-card",loading:l,children:t.jsxs(W,{vertical:!0,gap:s.marginMD,children:[t.jsx(Ge,{strong:!0,children:e("settings.notificationsTab.channels.title","Notification Channels")}),t.jsx(Ge,{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.")}),p?t.jsx(Ie,{type:"error",showIcon:!0,message:p,action:t.jsx(R,{size:"small",onClick:()=>void L(),children:e("settings.notificationsTab.channels.retry","Retry")})}):null,!l&&!p&&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(Ge,{children:e("settings.notificationsTab.channels.desktop.title","Desktop")}),t.jsx(ae,{"data-testid":"channel-desktop-mode",value:r.desktopMode,onChange:S=>A({desktopMode:S}),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(Ge,{children:e("settings.notificationsTab.channels.ntfy.title","ntfy")}),t.jsx(pe,{"data-testid":"channel-ntfy-enabled",checked:r.ntfyEnabled,onChange:S=>A({ntfyEnabled:S}),"aria-label":e("settings.notificationsTab.channels.ntfy.enable","Enable ntfy")})]}),t.jsxs("label",{children:[t.jsx(Ge,{type:"secondary",style:{fontSize:s.fontSizeSM},children:e("settings.notificationsTab.channels.ntfy.baseUrl","Base URL")}),t.jsx(B,{"data-testid":"channel-ntfy-base-url",value:r.ntfyBaseUrl,onChange:S=>A({ntfyBaseUrl:S.target.value}),placeholder:mn})]}),t.jsxs("label",{children:[t.jsx(Ge,{type:"secondary",style:{fontSize:s.fontSizeSM},children:e("settings.notificationsTab.channels.ntfy.topic","Topic")}),t.jsx(B,{"data-testid":"channel-ntfy-topic",value:r.ntfyTopic,onChange:S=>A({ntfyTopic:S.target.value}),placeholder:e("settings.notificationsTab.channels.ntfy.topicPlaceholder","my-bamboo-topic")})]}),t.jsxs("label",{children:[t.jsx(Ge,{type:"secondary",style:{fontSize:s.fontSizeSM},children:e("settings.notificationsTab.channels.ntfy.token","Token (optional, for self-hosted instances)")}),t.jsx(B.Password,{"data-testid":"channel-ntfy-token",value:r.ntfyToken,onChange:S=>A({ntfyToken:S.target.value}),placeholder:U?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(Ge,{children:e("settings.notificationsTab.channels.bark.title","Bark")}),t.jsx(pe,{"data-testid":"channel-bark-enabled",checked:r.barkEnabled,onChange:S=>A({barkEnabled:S}),"aria-label":e("settings.notificationsTab.channels.bark.enable","Enable Bark")})]}),t.jsxs("label",{children:[t.jsx(Ge,{type:"secondary",style:{fontSize:s.fontSizeSM},children:e("settings.notificationsTab.channels.bark.baseUrl","Base URL")}),t.jsx(B,{"data-testid":"channel-bark-base-url",value:r.barkBaseUrl,onChange:S=>A({barkBaseUrl:S.target.value}),placeholder:hn})]}),t.jsxs("label",{children:[t.jsx(Ge,{type:"secondary",style:{fontSize:s.fontSizeSM},children:e("settings.notificationsTab.channels.bark.deviceKey","Device Key")}),t.jsx(B.Password,{"data-testid":"channel-bark-device-key",value:r.barkDeviceKey,onChange:S=>A({barkDeviceKey:S.target.value}),placeholder:ie?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")})]})]}),f?t.jsx(Ie,{type:"error",showIcon:!0,message:f}):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 C(),disabled:I,children:I?e("settings.notificationsTab.channels.testing","Sending…"):e("settings.notificationsTab.channels.test","Send test notification")}),x?t.jsx(Ge,{type:"secondary",style:{fontSize:s.fontSizeSM},children:x.length>0?e("settings.notificationsTab.channels.testAttempted",{defaultValue:"Attempted: {{channels}}",channels:x.join(", ")}):e("settings.notificationsTab.channels.testNone","No channels are currently enabled")}):null,j?t.jsx(Ge,{type:"danger",style:{fontSize:s.fontSizeSM},children:j}):null]}),t.jsxs(W,{align:"center",gap:s.marginSM,children:[y?t.jsx(Ge,{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 H(),disabled:c,children:c?e("settings.notificationsTab.channels.saving","Saving…"):e("settings.notificationsTab.channels.save","Save channel settings")})]})]})]})]})})},{Text:Je}=ue,{useToken:ml}=Se,hl={enabled:!0,onClarification:!0,onToolApproval:!0,onContextPressure:!0,onSubAgentComplete:!0,onBackgroundTaskComplete:!0,onRunComplete:!0,onRunFailed:!0},yl=()=>{const{t:e}=re(),{token:s}=ml(),{message:n}=rt.useApp(),[a,r]=o.useState(hl),[i,l]=o.useState(!0),g=qa();o.useEffect(()=>{let u=!1;return(async()=>{try{const f=await dl();u||r(f)}catch{u||n.error(e("settings.notificationsTab.loadError","Failed to load notification preferences"))}finally{u||l(!1)}})(),()=>{u=!0}},[n,e]);const p=(u,f)=>{const D=a,y={...a,[u]:f};r(y),ul(y).then(d=>{r(d)}).catch(()=>{r(D),n.error(e("settings.notificationsTab.saveError","Failed to save notification preferences"))})},m=!g||i,c=t.jsx(V,{size:"small",className:"lotus-settings-card",children:t.jsxs(W,{vertical:!0,gap:s.marginMD,children:[!g&&t.jsx(Ie,{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(ur,{}),t.jsx(Je,{strong:!0,children:e("settings.notificationsTab.title","Desktop Notifications")})]}),t.jsx(Je,{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(Je,{children:e("settings.notificationsTab.enabled","Enable desktop notifications")}),t.jsx(pe,{"data-testid":"notification-enabled-toggle",checked:a.enabled,onChange:u=>p("enabled",u),disabled:m})]}),t.jsx(Pe,{style:{margin:`${s.marginXS}px 0`}}),t.jsx(Je,{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(Je,{children:e("settings.notificationsTab.onClarification","Agent needs clarification")}),t.jsx(pe,{"data-testid":"notification-clarification-toggle",checked:a.onClarification,onChange:u=>p("onClarification",u),disabled:m})]}),t.jsxs(W,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(Je,{children:e("settings.notificationsTab.onToolApproval","Tool execution needs approval")}),t.jsx(pe,{"data-testid":"notification-tool-approval-toggle",checked:a.onToolApproval,onChange:u=>p("onToolApproval",u),disabled:m})]}),t.jsxs(W,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(Je,{children:e("settings.notificationsTab.onContextPressure","Context window is critically full")}),t.jsx(pe,{"data-testid":"notification-context-pressure-toggle",checked:a.onContextPressure,onChange:u=>p("onContextPressure",u),disabled:m})]}),t.jsxs(W,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(Je,{children:e("settings.notificationsTab.onSubAgentComplete","Background task completes")}),t.jsx(pe,{"data-testid":"notification-subagent-complete-toggle",checked:a.onSubAgentComplete,onChange:u=>p("onSubAgentComplete",u),disabled:m})]}),t.jsxs(W,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(Je,{children:e("settings.notificationsTab.onBackgroundTaskComplete","Background command finishes")}),t.jsx(pe,{"data-testid":"notification-background-task-complete-toggle",checked:a.onBackgroundTaskComplete,onChange:u=>p("onBackgroundTaskComplete",u),disabled:m})]}),t.jsxs(W,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(Je,{children:e("settings.notificationsTab.onRunComplete","A run finishes successfully")}),t.jsx(pe,{"data-testid":"notification-run-complete-toggle",checked:a.onRunComplete,onChange:u=>p("onRunComplete",u),disabled:m})]}),t.jsxs(W,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(Je,{children:e("settings.notificationsTab.onRunFailed","A run fails")}),t.jsx(pe,{"data-testid":"notification-run-failed-toggle",checked:a.onRunFailed,onChange:u=>p("onRunFailed",u),disabled:m})]})]}),t.jsx(Pe,{style:{margin:`${s.marginXS}px 0`}}),t.jsxs(W,{align:"center",gap:s.marginSM,children:[t.jsx(gr,{style:{color:s.colorPrimary}}),t.jsx(Je,{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:[c,t.jsx(pl,{})]})},{Text:Ss,Paragraph:fl}=ue,Ea=({open:e,onCancel:s,onComplete:n,onCopyCode:a,completingAuth:r,copiedUserCode:i,deviceCodeInfo:l,timeRemaining:g,token:p})=>{const{t:m}=re();return t.jsx(Xe,{title:m("settings.providerTab.copilotAuthModalTitle"),open:e,onCancel:s,footer:[t.jsx(R,{onClick:s,children:m("settings.providerTab.cancel")},"cancel"),t.jsx(R,{type:"primary",onClick:n,loading:r,children:m("settings.providerTab.completedAuthorization")},"complete")],children:l&&t.jsxs(O,{direction:"vertical",size:"large",style:{width:"100%"},children:[t.jsx(Ie,{message:m("settings.providerTab.browserOpened"),description:t.jsxs("ol",{children:[t.jsx("li",{children:m("settings.providerTab.authStep1")}),t.jsx("li",{children:m("settings.providerTab.authStep2")}),t.jsx("li",{children:m("settings.providerTab.authStep3")})]}),type:"info"}),t.jsx(V,{size:"small",className:"lotus-settings-card",children:t.jsxs(O,{direction:"vertical",style:{width:"100%"},children:[t.jsx(Ss,{type:"secondary",children:m("settings.providerTab.visitUrl")}),t.jsx(O,{children:t.jsx(Ss,{copyable:{text:l.verification_uri},children:l.verification_uri})})]})}),t.jsx(V,{style:{textAlign:"center",background:p.colorFillTertiary,borderColor:p.colorBorderSecondary},children:t.jsxs(O,{direction:"vertical",style:{width:"100%"},children:[t.jsx(Ss,{type:"secondary",children:m("settings.providerTab.enterCode")}),t.jsxs(O,{children:[t.jsx(Ss,{style:{color:p.colorText,fontSize:"32px",fontFamily:"monospace",fontWeight:"bold",letterSpacing:"4px"},children:l.user_code}),t.jsx(R,{icon:i?t.jsx(un,{}):t.jsx(ya,{}),onClick:a,type:i?"default":"primary",children:m(i?"settings.providerTab.copied":"settings.providerTab.copyCode")})]}),t.jsx("div",{style:{marginTop:8},children:t.jsxs(oe,{color:g<60?"error":g<180?"warning":"success",children:[t.jsx(pr,{style:{marginRight:4}}),"Expires in ",Math.floor(g/60),":",(g%60).toString().padStart(2,"0")]})})]})}),t.jsx(fl,{type:"secondary",children:m("settings.providerTab.afterContinueHint")})]})})},bl=new Set(["id","type","provider_type","label","enabled","api_key_encrypted"]),Is=us,ra=e=>e?Object.fromEntries(Object.entries(e).filter(([s,n])=>!bl.has(s)&&!(s==="api_key"&&Is(n)))):{},nn=[{id:"deepseek",label:"DeepSeek",provider_type:"openai",base_url:"https://api.deepseek.com/v1",suggested_models:["deepseek-chat","deepseek-reasoner"]},{id:"deepseek-anthropic",label:"DeepSeek (Anthropic 协议)",provider_type:"anthropic",base_url:"https://api.deepseek.com/anthropic",suggested_models:["deepseek-chat","deepseek-reasoner"],notes:"通过 Anthropic 兼容协议接入 DeepSeek"},{id:"zhipu",label:"智谱 GLM (bigmodel.cn)",provider_type:"openai",base_url:"https://open.bigmodel.cn/api/paas/v4",suggested_models:["glm-5.2"]},{id:"zhipu-anthropic",label:"智谱 GLM (Anthropic 协议)",provider_type:"anthropic",base_url:"https://open.bigmodel.cn/api/anthropic",suggested_models:["glm-5.2"],notes:"通过 Anthropic 兼容协议接入智谱 GLM"},{id:"zai",label:"Z.ai (国际版)",provider_type:"openai",base_url:"https://api.z.ai/api/paas/v4",suggested_models:["glm-5.2"],notes:"智谱 GLM 国际平台"},{id:"minimax-cn",label:"MiniMax (中国大陆)",provider_type:"openai",base_url:"https://api.minimaxi.com/v1",suggested_models:["MiniMax-M3"],notes:"中国大陆平台(minimaxi.com)"},{id:"minimax-intl",label:"MiniMax (国际版)",provider_type:"openai",base_url:"https://api.minimax.io/v1",suggested_models:["MiniMax-M3"],notes:"国际平台(minimax.io)"},{id:"qwen",label:"通义千问 (DashScope)",provider_type:"openai",base_url:"https://dashscope.aliyuncs.com/compatible-mode/v1",suggested_models:["qwen-plus","qwen-max"],notes:"阿里云百炼 OpenAI 兼容模式(北京地域)"},{id:"kimi",label:"Kimi (Moonshot)",provider_type:"openai",base_url:"https://api.moonshot.cn/v1",suggested_models:["kimi-k2.6"]}],{Password:ia}=B,{Text:bt,Paragraph:an}=ue,xl=["low","medium","high","xhigh","max"],ss=(e,s)=>t.jsx(ae,{placeholder:e("settings.providerTab.reasoningEffortDefault"),allowClear:!0,value:s==null?void 0:s.value,onChange:void 0,disabled:s==null?void 0:s.disabled,size:s==null?void 0:s.size,style:s==null?void 0:s.style,children:xl.map(n=>t.jsx(ae.Option,{value:n,children:e(`chat.input.reasoning.${n}`)},n))}),oa=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(ae,{mode:"tags",tokenSeparators:[","," ",`
3
+ `," "],placeholder:e("settings.providerTab.responsesOnlyModelsPlaceholder"),allowClear:!0})}),vl=e=>Array.isArray(e)?e.map(s=>typeof s=="string"?s.trim():"").filter(s=>!!s):[],jl=({type:e,hasStoredApiKey:s})=>{const{t:n}=re();if(!e)return null;const a=i=>s?[]:[{required:!0,message:i}],r=i=>s?n("settings.providerTab.apiKeyKeepPlaceholder","Configured — leave empty to keep"):i;switch(e){case"openai":return t.jsxs(t.Fragment,{children:[t.jsx(b.Item,{name:"api_key",label:n("settings.providerTab.openaiApiKey"),rules:a(n("settings.providerTab.openaiApiKeyRequired")),children:t.jsx(B.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(B,{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)}),oa(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(ia,{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(B,{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(B,{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(ia,{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(B,{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(pe,{})}),t.jsx(b.Item,{name:"reasoning_effort",label:n("settings.providerTab.reasoningEffortOptional"),extra:n("settings.providerTab.reasoningEffortHelp"),children:ss(n)}),oa(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(B.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(B,{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(ae,{placeholder:n("settings.providerTab.targetProviderPlaceholder","openai"),allowClear:!0,children:[t.jsx(ae.Option,{value:"openai",children:"OpenAI"}),t.jsx(ae.Option,{value:"anthropic",children:"Anthropic"}),t.jsx(ae.Option,{value:"gemini",children:"Gemini"})]})}),t.jsx(b.Item,{name:"reasoning_effort",label:n("settings.providerTab.reasoningEffortOptional"),extra:n("settings.providerTab.reasoningEffortHelp"),children:ss(n)})]});default:return null}},Tl=({instances:e,defaultInstanceId:s,onInstancesChanged:n})=>{const{t:a}=re(),{message:r}=rt.useApp(),{token:i}=Se.useToken(),[l]=b.useForm(),[g,p]=o.useState(!1),[m,c]=o.useState(null),[u,f]=o.useState(!1),[D,y]=o.useState(null),[d,I]=o.useState(void 0),[E,j]=o.useState(void 0),[w,x]=o.useState(null),[v,L]=o.useState(!1),[A,U]=o.useState(!1),[ie,H]=o.useState(0),[C,k]=o.useState(!1),[M,S]=o.useState(!1),[G,$]=o.useState("unknown"),[ee,se]=o.useState(!1),le=o.useCallback(q=>({type:q.type,label:q.label,enabled:q.enabled,...ra(q.config)}),[]),Q=o.useCallback(()=>{c(null),I(void 0),j(void 0),p(!0)},[]),ye=o.useCallback(q=>{if(j(q),!q)return;const Te=nn.find(fe=>fe.id===q);if(!Te)return;const Ne={base_url:Te.base_url};m||(Ne.type=Te.provider_type,I(Te.provider_type));const N=l.getFieldValue("label");(typeof N!="string"||!N.trim())&&(Ne.label=Te.label),l.setFieldsValue(Ne)},[m,l]),h=async()=>{try{S(!0);const q=await me.startCopilotAuth();x(q),L(!0),H(q.expires_in)}catch(q){r.error(a("settings.providerTab.startCopilotAuthFailed","Failed to start Copilot authentication")),console.error("Failed to start Copilot authentication:",q)}finally{S(!1)}},F=async()=>{if(w)try{U(!0),await me.completeCopilotAuth({device_code:w.device_code,interval:w.interval||5,expires_in:w.expires_in}),r.success(a("settings.providerTab.copilotAuthSuccess","Copilot authentication successful!")),L(!1),x(null),await X()}catch(q){r.error(a("settings.providerTab.completeAuthFailed","Authentication completion failed")),console.error("Authentication completion failed:",q)}finally{U(!1)}},P=async()=>{if(w)try{await bn(w.user_code),k(!0),r.success(a("settings.providerTab.userCodeCopied","User code copied!")),setTimeout(()=>k(!1),2e3)}catch{r.error(a("settings.providerTab.copyCodeFailed","Failed to copy code"))}},X=o.useCallback(async()=>{try{se(!0);const q=await me.getCopilotAuthStatus();$(q.authenticated?"authenticated":"not_authenticated")}catch(q){console.error("Failed to check Copilot auth status:",q),$("unknown")}finally{se(!1)}},[]);o.useEffect(()=>{g&&d==="copilot"&&X()},[X,g,d]);const te=o.useCallback(q=>{if(!q){l.resetFields();return}if(m){l.setFieldsValue(le(m)),I(m.type);return}l.setFieldsValue({enabled:!0})},[le,m,l]),ge=(q="small")=>t.jsx(V,{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:")}),G==="authenticated"?t.jsx(oe,{color:"success",children:a("settings.providerTab.authenticated","Authenticated")}):G==="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 X(),loading:ee,children:a("settings.providerTab.refreshStatus","Refresh")})]}),t.jsx(an,{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(fa,{}),onClick:()=>void h(),loading:M,size:q,children:a("settings.providerTab.authenticateCopilot","Authenticate Copilot")})]})}),ve=o.useCallback(q=>{c(q),I(q.type),j(void 0),p(!0)},[]),_e=o.useCallback(async()=>{try{const q=await l.validateFields();f(!0);const{type:Te,label:Ne,enabled:N,request_overrides_json:fe,...z}=q,be=ra(z);if("responses_only_models"in be&&(be.responses_only_models=vl(be.responses_only_models)),typeof fe=="string"&&fe.trim()&&(be.request_overrides=JSON.parse(fe)),m&&(typeof be.api_key!="string"||!be.api_key.trim())&&delete be.api_key,m){const ce={label:Ne,enabled:N,config:be};await me.updateProviderInstance(m.id,ce),r.success(a("settings.providerTab.instanceUpdated","Provider instance updated"))}else{const ce={type:Te,label:Ne||vt[Te]||Te,enabled:N??!0,config:be};await me.createProviderInstance(ce),r.success(a("settings.providerTab.instanceCreated","Provider instance created"))}p(!1),await n(),await nt.getState().loadProviderInstances()}catch(q){(ws(q)||q instanceof Error&&!xa(q))&&r.error(q.message)}finally{f(!1)}},[m,l,r,n,a]),Oe=o.useCallback(async q=>{try{y(q),await me.deleteProviderInstance(q),r.success(a("settings.providerTab.instanceDeleted","Provider instance deleted")),await n(),await nt.getState().loadProviderInstances()}catch(Te){r.error(ws(Te)?Te.message:a("settings.providerTab.instanceDeleteFailed","Failed to delete instance"))}finally{y(null)}},[n,r,a]),tt=o.useCallback(async q=>{try{await me.setDefaultProviderInstance(q),r.success(a("settings.providerTab.defaultInstanceSet","Default provider updated")),await n(),await nt.getState().loadProviderInstances()}catch(Te){r.error(ws(Te)?Te.message:a("settings.providerTab.defaultInstanceFailed","Failed to set default"))}},[n,r,a]),Ze=nn.find(q=>q.id===E),pt=o.useCallback(async()=>{await n()},[n]);return o.useEffect(()=>{pt()},[]),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(at,{}),onClick:Q,"data-testid":"add-provider-instance",children:a("settings.providerTab.addInstance","Add Provider")})]}),e.length===0&&t.jsx(an,{type:"secondary",children:a("settings.providerTab.noInstances",'No provider instances configured. Click "Add Provider" to create one.')}),t.jsx(Fs,{ghost:!0,items:e.map(q=>{const Te=q.id===s,Ne=vt[q.type]||q.type;return{key:q.id,label:t.jsxs(O,{size:"small",children:[t.jsx("span",{style:{fontWeight:500},children:q.label||Ne}),t.jsx(oe,{color:"processing",style:{fontSize:11},children:Ne}),Te&&t.jsxs(oe,{color:"gold",style:{fontSize:11},children:[t.jsx(hr,{})," ",a("settings.providerTab.default","Default")]}),!q.enabled&&t.jsx(oe,{color:"default",style:{fontSize:11},children:a("settings.providerTab.disabled","Disabled")})]}),extra:t.jsxs(O,{size:4,onClick:N=>N.stopPropagation(),children:[!Te&&t.jsx(we,{title:a("settings.providerTab.setDefault","Set as default"),children:t.jsx(R,{type:"text",size:"small",icon:t.jsx(mr,{}),onClick:()=>void tt(q.id)})}),t.jsx(R,{type:"text",size:"small",icon:t.jsx(Vt,{}),onClick:()=>ve(q)}),t.jsx(Tt,{title:a("settings.providerTab.confirmDeleteInstance","Delete this provider instance?"),onConfirm:()=>void Oe(q.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(kt,{}),loading:D===q.id})})]}),children:t.jsxs("div",{children:[t.jsxs(an,{type:"secondary",style:{marginBottom:8},children:["ID: ",t.jsx(bt,{code:!0,children:q.id})," · Type: ",t.jsx(bt,{code:!0,children:q.type})]}),q.config&&Object.keys(q.config).length>0&&t.jsx(V,{size:"small",style:{marginBottom:8},children:Object.entries(q.config).map(([N,fe])=>N==="api_key"?t.jsxs("div",{style:{marginBottom:4},children:[t.jsxs(bt,{type:"secondary",children:[N,": "]}),t.jsx(bt,{children:"••••••••"})]},N):t.jsxs("div",{style:{marginBottom:4},children:[t.jsxs(bt,{type:"secondary",children:[N,": "]}),t.jsx(bt,{children:typeof fe=="object"?JSON.stringify(fe):String(fe)})]},N))}),q.type==="copilot"&&ge("small")]})}})}),t.jsx(Xe,{open:g,title:m?a("settings.providerTab.editInstance","Edit Provider Instance"):a("settings.providerTab.createInstance","Create Provider Instance"),onCancel:()=>p(!1),onOk:()=>void _e(),afterOpenChange:te,confirmLoading:u,width:560,forceRender:!0,destroyOnClose:!0,children:t.jsxs(b,{form:l,layout:"vertical",preserve:!1,children:[t.jsx(b.Item,{label:a("settings.providerTab.vendorPreset","Vendor Preset"),tooltip:a("settings.providerTab.vendorPresetTooltip","Prefills the provider type and base URL; the preset itself is not saved."),extra:Ze&&t.jsxs(t.Fragment,{children:[Ze.notes&&t.jsx("div",{children:Ze.notes}),Ze.suggested_models.length>0&&t.jsx("div",{children:a("settings.providerTab.vendorPresetModelsHint",{defaultValue:"Popular models: {{models}}",models:Ze.suggested_models.join(", ")})})]}),children:t.jsx(ae,{allowClear:!0,showSearch:!0,optionFilterProp:"label",placeholder:a("settings.providerTab.vendorPresetPlaceholder","Select a vendor to prefill type and base URL"),value:E,onChange:ye,options:nn.map(q=>({value:q.id,label:q.label})),"data-testid":"vendor-preset-select"})}),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(ae,{disabled:!!m,placeholder:a("settings.providerTab.selectType","Select provider type"),onChange:q=>I(q),children:Object.entries(vt).map(([q,Te])=>t.jsx(ae.Option,{value:q,children:Te},q))})}),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(B,{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(pe,{})}),t.jsx(Pe,{children:a("settings.providerTab.instanceConfig","Configuration")}),t.jsx(b.Item,{noStyle:!0,shouldUpdate:!0,children:()=>{var q;return t.jsx(jl,{form:l,type:d,hasStoredApiKey:!!(m&&Is((q=m.config)==null?void 0:q.api_key))})}}),d==="copilot"&&ge("middle")]})}),t.jsx(Ea,{open:v,onCancel:()=>L(!1),onComplete:()=>void F(),onCopyCode:()=>void P(),completingAuth:A,copiedUserCode:C,deviceCodeInfo:w,timeRemaining:ie,token:i})]})},{Password:la}=B,{Text:Qe,Paragraph:rn}=ue,ns=["openai","anthropic","gemini","copilot","bodhi"],zt=()=>null,on=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()))},kl=(e,s,n)=>{const a=e;a[s]={...a[s]??{},model:n}},ca=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},da=(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},ua=e=>t.jsxs(O,{direction:"vertical",size:4,children:[t.jsxs(Qe,{type:"secondary",children:[e("settings.providerTab.responsesOnlyHelp1")," ",t.jsx(Qe,{code:!0,children:"/responses"}),"."]}),t.jsx(Qe,{type:"secondary",children:e("settings.providerTab.responsesOnlyHelp2")})]}),Sl=["low","medium","high","xhigh","max"],Lt=(e,s)=>t.jsx(ae,{placeholder:e("settings.providerTab.reasoningEffortDefault"),allowClear:!0,value:s==null?void 0:s.value,onChange:s!=null&&s.onChange?n=>{var a;return(a=s.onChange)==null?void 0:a.call(s,n??void 0)}:void 0,disabled:s==null?void 0:s.disabled,size:s==null?void 0:s.size,style:s==null?void 0:s.style,"data-testid":s==null?void 0:s["data-testid"],children:Sl.map(n=>t.jsx(ae.Option,{value:n,children:e(`chat.input.reasoning.${n}`)},n))}),_l=()=>{const{t:e}=re(),{token:s}=Se.useToken(),{message:n}=rt.useApp(),[a]=b.useForm(),[r,i]=o.useState(!1),[l,g]=o.useState(!1),[p,m]=o.useState("copilot"),[c,u]=o.useState(!1),[f,D]=o.useState(new Set),[y,d]=o.useState(null),[I,E]=o.useState(!1),[j,w]=o.useState(!1),[x,v]=o.useState(null),[L,A]=o.useState(!1),[U,ie]=o.useState(!1),[H,C]=o.useState(0),[k,M]=o.useState(!1),[S,G]=o.useState([]),[$,ee]=o.useState(!1),[se,le]=o.useState([]),[Q,ye]=o.useState(null),[h,F]=o.useState(!1),[P,X]=o.useState([]),[te,ge]=o.useState("idle"),[ve,_e]=o.useState(null),Oe=o.useCallback((T,_)=>{const Z=T.instances??[],K=Z.reduce((je,ne)=>{const Me={...ne.config};return Me.request_overrides&&typeof Me.request_overrides=="object"&&(Me.request_overrides_json=JSON.stringify(Me.request_overrides,null,2)),je[ne.id]=Me,je},{});let J=T.defaults?{...T.defaults}:void 0;const ke=T.default_provider_instance_id??null,xe=ke?Z.find(je=>je.id===ke):void 0,Ce=typeof(xe==null?void 0:xe.config.model)=="string"?xe.config.model.trim():void 0;!on(J==null?void 0:J.chat)&&ke&&Ce&&(J={...J||{},chat:{provider:ke,model:Ce}});const Ve=_?ca(_):void 0,Fe=da(J,ke);return Ve&&!(J!=null&&J.memory_background)&&Fe&&(J={...J||{},memory_background:{provider:Fe,model:Ve}}),{defaults:J,features:T.features,providers:K}},[]),tt=o.useCallback((T,_)=>{le(T.instances??[]),ye(T.default_provider_instance_id??null),F(!0),a.setFieldsValue(Oe(T,_)),u(!0)},[Oe,a]),Ze=o.useCallback(T=>{if(!(T!=null&&T.trim()))return;const _=se.find(Z=>Z.id===T);return _?_.label||vt[_.type]:vt[T]||T},[se]),pt=o.useCallback((T,_)=>{const Z=new Set;T!=null&&T.trim()&&Z.add(T);for(const K of ns){const J=_==null?void 0:_[K];J&&Object.keys(J).length>0&&Z.add(K)}return Array.from(Z)},[]);o.useEffect(()=>{if(te!=="success")return;const T=setTimeout(()=>{ge("idle"),_e(null)},2e3);return()=>clearTimeout(T)},[te]),o.useEffect(()=>{if(!L||!x){C(0);return}C(x.expires_in);const T=setInterval(()=>{C(_=>_<=1?(clearInterval(T),0):_-1)},1e3);return()=>clearInterval(T)},[L,x]);const q=o.useCallback(async()=>{var T;try{i(!0);const[_,Z]=await Promise.all([me.getProviderConfig(),lt.getInstance().getBambooConfig().catch(()=>({}))]);let K=_.defaults?{..._.defaults}:void 0;if(!((T=K==null?void 0:K.chat)!=null&&T.model)&&_.provider&&_.providers){const je=_.provider,ne=_.providers[je],Me=ne==null?void 0:ne.model;Me&&(K={...K||{},chat:{provider:je,model:Me}})}const J=ca(Z),ke=da(K,_.provider||null);J&&!(K!=null&&K.memory_background)&&ke&&(K={...K||{},memory_background:{provider:ke,model:J}});const xe=on(K==null?void 0:K.chat)?K:void 0,Ce={provider:_.provider,defaults:xe,providers:_.providers||{},features:_.features};ut("[Provider]","Loaded provider config:",Ce);const Ve={...Ce.providers||{}},Fe=new Set;ns.forEach(je=>{const ne=Ve[je];ne&&(Is(ne.api_key)&&(Fe.add(je),delete ne.api_key),ne.request_overrides&&typeof ne.request_overrides=="object"&&(ne.request_overrides_json=JSON.stringify(ne.request_overrides,null,2)))}),D(Fe),m(Ce.provider),F(!1),X(pt(Ce.provider,Ve)),a.setFieldsValue({...Ce,providers:Ve,defaults:Ce.defaults}),u(!0)}catch(_){n.error(e("settings.providerTab.loadConfigFailed")),console.error("Failed to load provider config:",_)}finally{i(!1)}},[a,pt,n,e]),Te=o.useCallback(async()=>{try{const T=await me.getEnvVars();G(T.entries||[])}catch(T){console.warn("Failed to load env vars for provider overrides:",T)}},[]),Ne=o.useCallback(async()=>{try{const[T,_]=await Promise.all([me.getProviderInstances(),lt.getInstance().getBambooConfig().catch(()=>({}))]);if(!Array.isArray(T.instances))throw new Error("Provider instances API returned an invalid payload");tt(T,_)}catch{}},[tt]),N=o.useCallback(async()=>{try{E(!0);const T=await me.getCopilotAuthStatus();d(T)}catch(T){console.error("Failed to check Copilot auth status:",T),d({authenticated:!1,message:e("settings.providerTab.checkStatusFailed")})}finally{E(!1)}},[e]);o.useEffect(()=>{Te(),nt.getState().loadCatalog(),N(),(async()=>{try{const[T,_]=await Promise.all([me.getProviderInstances(),lt.getInstance().getBambooConfig().catch(()=>({}))]);if(!Array.isArray(T.instances))throw new Error("Provider instances API returned an invalid payload");tt(T,_)}catch{await q()}})()},[q,Te,N,tt]);const fe=async()=>{try{w(!0);const T=await me.startCopilotAuth();v(T),A(!0)}catch(T){n.error(e("settings.providerTab.startCopilotAuthFailed")),console.error("Failed to start Copilot authentication:",T)}finally{w(!1)}},z=async()=>{if(x)try{ie(!0),await me.completeCopilotAuth({device_code:x.device_code,interval:x.interval||5,expires_in:x.expires_in}),n.success(e("settings.providerTab.copilotAuthSuccess")),A(!1),v(null),await N()}catch(T){n.error(e("settings.providerTab.completeAuthFailed")),console.error("Authentication completion failed:",T)}finally{ie(!1)}},be=async()=>{if(x)try{await bn(x.user_code),M(!0),n.success(e("settings.providerTab.userCodeCopied")),setTimeout(()=>M(!1),2e3)}catch{n.error(`${e("settings.providerTab.copyCodeFailedPrefix")} ${x.user_code}`)}},ce=async()=>{try{w(!0),await me.logoutCopilot(),n.success(e("settings.providerTab.logoutSuccess")),await N()}catch(T){n.error(e("settings.providerTab.logoutFailed")),console.error("Failed to logout:",T)}finally{w(!1)}},qe=o.useCallback(async()=>{ee(!0);try{const T=await me.fetchCatalogModels();await nt.getState().loadCatalog();const _=T.fetched.filter(K=>K.models&&K.models.length>0).length;T.fetched.filter(K=>K.error).length>0?n.warning(e("settings.providerTab.fetchModelsPartialSuccess",{success:_,total:T.fetched.length})):n.success(e("settings.providerTab.fetchModelsSuccess",{count:_}))}catch{n.error(e("settings.providerTab.fetchModelsFailed"))}finally{ee(!1)}},[n,e]),mt=T=>ws(T)||T instanceof Error?T.message:e("settings.providerTab.unknownError"),ht=T=>{a.setFields([{name:["provider"],errors:[]},{name:["providers",T,"api_key"],errors:[]},{name:["defaults","chat"],errors:[]}])},bs=T=>{const _=T.trim();return _?_.includes(".")?_.split(".").filter(Boolean):_==="provider"?["provider"]:_==="provider/providers"?["provider"]:null:null},zs=(T,_)=>{if(!T.length)return;const Z=T.map(K=>{const J=bs(K.path);return J?{name:J,errors:[K.message]}:K.message.toLowerCase().includes("api key")?{name:["providers",_,"api_key"],errors:[K.message]}:{name:["provider"],errors:[K.message]}}).filter((K,J,ke)=>ke.findIndex(xe=>JSON.stringify(xe.name)===JSON.stringify(K.name))===J);Z.length&&a.setFields(Z)},Ls=async T=>{var Z;const _=T.provider||p;ht(_);try{const J=await lt.getInstance().validateBambooConfigPatch({provider:T.provider,providers:T.providers||{},defaults:T.defaults,features:{...T.features||{},provider_model_ref:!0}});if(J.valid)return{valid:!0};const ke=((Z=J.errors)==null?void 0:Z.provider)||[];zs(ke,_);const xe=ke[0];return{valid:!1,message:(xe==null?void 0:xe.message)||e("settings.providerTab.invalidConfig")}}catch(K){return console.warn("Config validation failed, falling back to save:",K),{valid:!0}}},Ut=async(T,_)=>{var Z,K;try{i(!0);const J={provider:T.provider,defaults:T.defaults,providers:{...T.providers||{}},features:{...T.features||{},provider_model_ref:!0}},ke=(Z=J.defaults)==null?void 0:Z.chat;if(!on(ke)){const je=e("settings.providerTab.selectModelRequired");if(a.setFields([{name:["defaults","chat"],errors:[je]}]),(_==null?void 0:_.showMessage)!==!1&&n.error(je),_!=null&&_.throwOnError)throw new Error(je);return}const xe=J.providers;for(const je of ns){const ne=xe[je];if(!ne)continue;const Me=ne.request_overrides_json;if(typeof Me!="string")continue;const _t=Me.trim();if(!_t)delete ne.request_overrides;else try{ne.request_overrides=JSON.parse(_t)}catch(Kt){const Wt=e("settings.providerTab.invalidRequestOverridesJson",{provider:je,error:Kt.message});if(a.setFields([{name:["providers",je,"request_overrides_json"],errors:[Wt]}]),(_==null?void 0:_.showMessage)!==!1&&n.error(Wt),_!=null&&_.throwOnError)throw Kt;return}delete ne.request_overrides_json}for(const je of ns){const ne=xe[je];if(!ne||!("api_key"in ne))continue;const Me=ne.api_key;(typeof Me!="string"||!Me.trim()||Is(Me))&&delete ne.api_key}const Ce={...J.providers||{}},Ve=J.provider,Fe=(K=J.defaults)==null?void 0:K.chat;if(Fe!=null&&Fe.model&&Ve&&kl(Ce,Ve,Fe.model),h){const je=lt.getInstance(),ne={defaults:J.defaults,features:{...J.features||{},provider_model_ref:!0}};ut("[Provider]","Saving instance-mode config:",ne),await je.setBambooConfig(ne)}else{const ne={provider:J.provider||p,defaults:J.defaults,providers:Ce,features:J.features},Me=await Ls(J);if(!Me.valid){const _t=Me.message||e("settings.providerTab.invalidConfig");if((_==null?void 0:_.showMessage)!==!1&&n.error(`${e("settings.providerTab.invalidConfigPrefix")}: ${_t}`),_!=null&&_.throwOnError)throw new Error(_t);return}ut("[Provider]","Saving provider config:",ne),await me.saveProviderConfig(ne)}(_==null?void 0:_.showMessage)!==!1&&n.success(e("settings.providerTab.saveConfigSuccess"))}catch(J){const ke=mt(J);if((_==null?void 0:_.showMessage)!==!1&&n.error(ke?`${e("settings.providerTab.saveConfigErrorPrefix")}: ${ke}`:e("settings.providerTab.saveConfigFailed")),console.error("Failed to save configuration:",J),_!=null&&_.throwOnError)throw J}finally{i(!1)}},yt=async T=>{var _,Z,K,J,ke;try{g(!0);const{useProviderStore:xe}=await gn(async()=>{const{useProviderStore:Gt}=await import("./MetricsService-Cncz4Wn7.js").then(Us=>Us.am);return{useProviderStore:Gt}},__vite__mapDeps([0,1,2,3,4,5,6,7]),import.meta.url),{useAppStore:Ce}=await gn(async()=>{const{useAppStore:Gt}=await import("./MetricsService-Cncz4Wn7.js").then(Us=>Us.an);return{useAppStore:Gt}},__vite__mapDeps([0,1,2,3,4,5,6,7]),import.meta.url),Ve=(_=xe.getState().providerConfig.defaults)==null?void 0:_.chat;h?await xe.getState().loadProviderInstances():await xe.getState().loadProviderConfig();const Fe=(Z=xe.getState().providerConfig.defaults)==null?void 0:Z.chat;xe.getState().setSelectedModelRef(null);const je=Ce.getState().currentSessionId,ne=je&&Ce.getState().chats.find(Gt=>Gt.id===je)||null,Me=Ve?`${Ve.provider}/${Ve.model}`:null,_t=Fe?`${Fe.provider}/${Fe.model}`:null,Kt=(K=ne==null?void 0:ne.config)!=null&&K.model_ref?`${ne.config.model_ref.provider}/${ne.config.model_ref.model}`:null,Wt=((ke=(J=ne==null?void 0:ne.config)==null?void 0:J.model)==null?void 0:ke.trim())||null;!!(je&&(ne!=null&&ne.config)&&Fe&&_t!==Me&&(!Kt||Kt===Me)&&(!Wt||Wt===(Ve==null?void 0:Ve.model)))&&je&&(ne!=null&&ne.config)&&Fe&&Ce.getState().updateSession(je,{config:{...ne.config,model:Fe.model,model_ref:Fe}}),(T==null?void 0:T.showMessage)!==!1&&n.success(e("settings.providerTab.applyConfigSuccess"))}catch(xe){const Ce=mt(xe);if((T==null?void 0:T.showMessage)!==!1&&n.error(Ce?`${e("settings.providerTab.applyConfigErrorPrefix")}: ${Ce}`:e("settings.providerTab.applyConfigFailed")),console.error("Failed to apply configuration:",xe),T!=null&&T.throwOnError)throw xe}finally{g(!1)}},Os=async T=>{try{const _=a.getFieldsValue(!0);await Ut(_,{throwOnError:!0}),await yt({throwOnError:!0})}catch{}},Ns=async(T,_)=>{if(!(T==="chat"&&!_)&&te!=="saving"){ge("saving"),_e(null);try{const Z=a.getFieldsValue(!0),K=Z.defaults;if(!(K!=null&&K.chat))throw new Error(e("settings.providerTab.selectModelRequired"));Z.defaults={...K,[T]:_},await Ut(Z,{showMessage:!1,throwOnError:!0}),await yt({showMessage:!1,throwOnError:!0}),ge("success"),n.success(e("settings.providerTab.modelUpdated"))}catch(Z){const K=mt(Z);ge("error"),_e(K),n.error(K?`${e("settings.providerTab.updateModelErrorPrefix")}: ${K}`:e("settings.providerTab.updateModelFailed"))}}},Vs=async(T,_)=>{if(te!=="saving"){ge("saving"),_e(null);try{if(h){const Z=se.find(K=>K.id===T);if(!Z)throw new Error(e("settings.providerTab.providerNotConfigured"));await me.updateProviderInstance(Z.id,{config:{reasoning_effort:_??null}}),await Ne(),await nt.getState().loadProviderInstances()}else{const Z=a.getFieldsValue(!0);await Ut(Z,{showMessage:!1,throwOnError:!0}),await yt({showMessage:!1,throwOnError:!0})}ge("success"),n.success(e("settings.providerTab.reasoningEffortUpdated"))}catch(Z){const K=mt(Z);ge("error"),_e(K),n.error(K?`${e("settings.providerTab.updateReasoningEffortErrorPrefix")}: ${K}`:e("settings.providerTab.updateReasoningEffortFailed"))}}},xs=(T,_)=>{if(!T)return null;const Z=Ze(T)||T,K=a.getFieldValue(["providers",T,"reasoning_effort"]),J=(_==null?void 0:_.emphasis)==="subtle",ke=(_==null?void 0:_.label)||e("settings.providerTab.reasoningEffortOptional"),xe=(_==null?void 0:_.helperText)||e("settings.providerTab.reasoningEffortHelp");return t.jsx("div",{style:{marginTop:(_==null?void 0:_.marginTop)??8,width:"100%"},children:t.jsxs(O,{direction:"vertical",size:J?6:4,style:{width:"100%"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,flexWrap:"wrap"},children:[t.jsx(Qe,{strong:!J,type:J?"secondary":void 0,style:J?{fontSize:s.fontSizeSM,lineHeight:1.4}:void 0,children:ke}),_!=null&&_.showProviderLabel?t.jsx(Qe,{type:"secondary",style:{fontSize:s.fontSizeSM,lineHeight:1.4},children:Z}):null]}),Lt(e,{value:K,disabled:te==="saving",size:(_==null?void 0:_.size)??(J?"small":void 0),style:{width:"100%"},"data-testid":_==null?void 0:_.dataTestId,onChange:Ce=>{a.setFieldValue(["providers",T,"reasoning_effort"],Ce),_!=null&&_.autoSave&&Vs(T,Ce)}}),t.jsx(Qe,{type:"secondary",style:J?{fontSize:s.fontSizeSM,lineHeight:1.5}:void 0,children:xe})]})})},$s=o.useCallback(T=>{const _=a.getFieldValue(["providers",T]);return _?T==="copilot"?(y==null?void 0:y.authenticated)??!1:!!_.api_key:!1},[a,y]),Bs=()=>{const T=Z=>{const K=a.getFieldValue(["defaults",Z]);return t.jsx(Ua,{value:K,dataTestId:`model-preference-${Z}-picker`,appearance:"contrast",disabled:te==="saving",onChange:J=>{a.setFieldValue(["defaults",Z],J),Ns(Z,J)}})},_=(Z,K,J)=>t.jsxs("div",{style:{width:"100%",display:"flex",alignItems:"flex-start",gap:s.marginLG,flexWrap:"wrap"},children:[t.jsx("div",{style:{flex:"1 1 420px",minWidth:0},children:t.jsxs(O,{direction:"vertical",size:8,style:{width:"100%"},children:[t.jsx(Qe,{strong:!0,children:K}),T(Z),J?t.jsx(Qe,{type:"secondary",children:J}):null]})}),t.jsx("div",{style:{flex:"0 1 320px",minWidth:280},children:t.jsx(b.Item,{noStyle:!0,shouldUpdate:!0,children:()=>{const ke=a.getFieldValue(["defaults",Z]),xe=ke==null?void 0:ke.provider;return xs(xe,{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:!!xe})}})})]});return t.jsxs(V,{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(zt,{})}),t.jsx(b.Item,{name:["defaults","fast"],noStyle:!0,preserve:!0,children:t.jsx(zt,{})}),t.jsx(b.Item,{name:["defaults","task_summary"],noStyle:!0,preserve:!0,children:t.jsx(zt,{})}),t.jsx(b.Item,{name:["defaults","memory_background"],noStyle:!0,preserve:!0,children:t.jsx(zt,{})}),t.jsx(b.Item,{name:["defaults","sub_agent"],noStyle:!0,preserve:!0,children:t.jsx(zt,{})}),t.jsx(b.Item,{name:["defaults","vision"],noStyle:!0,preserve:!0,children:t.jsx(zt,{})}),t.jsxs(O,{direction:"vertical",size:16,style:{width:"100%"},children:[_("chat",e("settings.providerTab.defaultModel")),_("fast",e("settings.providerTab.fastModel"),e("settings.providerTab.fastModelHelp")),_("task_summary",e("settings.providerTab.taskSummaryModel"),e("settings.providerTab.taskSummaryModelHelp")),_("memory_background",e("settings.providerTab.memoryBackgroundModel"),e("settings.providerTab.memoryBackgroundModelHelp")),_("sub_agent",e("settings.providerTab.subAgentModel"),e("settings.providerTab.subAgentModelHelp")),_("vision",e("settings.providerTab.visionModel"),e("settings.providerTab.visionModelHelp"))]})]})},St=T=>{const _=S.map(K=>K.name);return t.jsx(b.Item,{name:["providers",T,"request_overrides_json"],label:e("settings.providerTab.advancedRequestOverrides"),extra:t.jsxs(O,{direction:"vertical",size:4,children:[t.jsx(Qe,{type:"secondary",children:e("settings.providerTab.advancedRequestOverridesHelp")}),t.jsxs(Qe,{type:"secondary",children:[e("settings.providerTab.envVarInjection")," ",t.jsx(Qe,{code:!0,children:'{ "type": "env_ref", "name": "YOUR_ENV_NAME" }'})]}),_.length>0&&t.jsx(O,{wrap:!0,size:[6,6],children:_.map(K=>t.jsx(oe,{children:K},K))})]}),children:t.jsx(B.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"}})})},qs=T=>{const _=f.has(T),Z=J=>_?[]:[{required:!0,message:J}],K=J=>_?e("settings.providerTab.apiKeyKeepPlaceholder","Configured — leave empty to keep"):J;switch(T){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(B.Password,{"data-testid":"api-key-input",placeholder:K(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(B,{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:Lt(e)}),t.jsx(b.Item,{name:["providers","openai","responses_only_models"],label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:ua(e),children:t.jsx(ae,{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(la,{placeholder:K(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(B,{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(B,{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:Lt(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(la,{placeholder:K(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(B,{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:Lt(e)}),t.jsx(Pe,{dashed:!0}),St("gemini")]});case"copilot":return t.jsxs(t.Fragment,{children:[t.jsxs(V,{size:"small",style:{marginBottom:16},title:e("settings.providerTab.authStatusTitle"),extra:I?t.jsx(ls,{size:"small"}):y!=null&&y.authenticated?t.jsx(oe,{icon:t.jsx(un,{}),color:"success",children:e("settings.providerTab.authenticated")}):t.jsx(oe,{icon:t.jsx(An,{}),color:"error",children:e("settings.providerTab.notAuthenticated")}),children:[(y==null?void 0:y.message)&&t.jsx(rn,{type:"secondary",style:{marginBottom:16},children:y.message}),t.jsxs(O,{children:[y!=null&&y.authenticated?t.jsx(R,{danger:!0,icon:t.jsx(yr,{}),onClick:ce,loading:j,children:e("settings.providerTab.logoutCopilot")}):t.jsx(R,{type:"primary",icon:t.jsx(fa,{}),onClick:fe,loading:j,children:e("settings.providerTab.authenticateCopilot")}),t.jsx(R,{onClick:N,loading:I,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(pe,{})}),t.jsx(b.Item,{name:["providers","copilot","reasoning_effort"],label:e("settings.providerTab.reasoningEffortOptional"),extra:e("settings.providerTab.reasoningEffortHelp"),children:Lt(e)}),t.jsx(b.Item,{name:["providers","copilot","responses_only_models"],label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:ua(e),children:t.jsx(ae,{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(rn,{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(B.Password,{"data-testid":"bodhi-api-key-input",placeholder:K(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(B,{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(ae,{placeholder:e("settings.providerTab.targetProviderPlaceholder","openai"),allowClear:!0,children:[t.jsx(ae.Option,{value:"openai",children:"OpenAI"}),t.jsx(ae.Option,{value:"anthropic",children:"Anthropic"}),t.jsx(ae.Option,{value:"gemini",children:"Gemini"})]})}),t.jsx(b.Item,{name:["providers","bodhi","reasoning_effort"],label:e("settings.providerTab.reasoningEffortOptional"),extra:e("settings.providerTab.reasoningEffortHelp"),children:Lt(e)}),t.jsx(Pe,{dashed:!0}),St("bodhi")]});default:return null}},Ht=T=>{const _=$s(T),Z=vt[T];return t.jsxs(O,{size:"small",children:[t.jsx("span",{style:{fontWeight:500},children:Z}),_?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(V,{title:e("settings.providerTab.title"),loading:r&&!c,className:"lotus-settings-card",children:[t.jsx(rn,{type:"secondary",children:e("settings.providerTab.description")}),t.jsx(Pe,{}),t.jsxs(b,{form:a,layout:"vertical",onFinish:Os,disabled:r&&!c,children:[!h&&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(ae,{"data-testid":"provider-select",size:"large",onChange:T=>m(T),children:Object.keys(vt).map(T=>t.jsx(ae.Option,{value:T,children:vt[T]},T))})}),t.jsx(b.Item,{noStyle:!0,shouldUpdate:!0,children:()=>xs(a.getFieldValue("provider")||p,{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($t,{}),onClick:qe,loading:$,children:e($?"settings.providerTab.fetchingAllModels":"settings.providerTab.fetchAllModels")}),te==="saving"&&t.jsx(ls,{size:"small",style:{marginLeft:8}}),te==="success"&&t.jsx(un,{style:{color:"var(--lotus-chart-secondary)",marginLeft:8}}),te==="error"&&t.jsx(we,{title:ve,children:t.jsx(An,{style:{color:"var(--lotus-chart-danger)",marginLeft:8}})})]}),Bs(),h?t.jsx(Tl,{instances:se,defaultInstanceId:Q,onInstancesChanged:Ne}):t.jsx(Fs,{activeKey:P,onChange:T=>X(Array.isArray(T)?T.map(String):T?[String(T)]:[]),ghost:!0,style:{marginBottom:16},items:ns.map(T=>({key:T,label:Ht(T),children:qs(T)}))}),t.jsx(Pe,{}),t.jsx(O,{size:"middle",children:t.jsx(R,{"data-testid":"save-api-settings",type:"primary",htmlType:"submit",icon:t.jsx(As,{}),loading:r||l,size:"large",children:e("settings.providerTab.saveAndApply")})})]}),t.jsx(Ea,{open:L,onCancel:()=>A(!1),onComplete:z,onCopyCode:be,completingAuth:U,copiedUserCode:k,deviceCodeInfo:x,timeRemaining:H,token:s})]})},{Text:ga}=ue,wl=({skill:e,disabled:s=!1,busy:n=!1,onToggleDisabled:a})=>{const{t:r}=re(),{token:i}=Se.useToken();return t.jsx(V,{title:t.jsxs(O,{size:i.marginXS,wrap:!0,style:{width:"100%",justifyContent:"space-between"},children:[t.jsxs(O,{size:i.marginXS,wrap:!0,children:[t.jsx("span",{children:e.name}),s&&t.jsx(oe,{color:"default",children:r("components.skillManager.disabledTag")}),e.license&&t.jsxs(oe,{color:"processing",children:["License: ",e.license]})]}),a&&t.jsx(pe,{checked:!s,loading:n,onChange:l=>a(e.id,!l),checkedChildren:r("components.skillManager.switchEnabled"),unCheckedChildren:r("components.skillManager.switchDisabled")})]}),styles:{body:{padding:i.paddingMD}},style:{opacity:s?.72:1},children:t.jsxs(O,{direction:"vertical",size:i.marginXS,style:{width:"100%"},children:[t.jsx(ga,{type:"secondary",children:e.description}),e.compatibility&&t.jsxs(ga,{type:"secondary",children:["Compatibility: ",e.compatibility]}),e.tool_refs.length>0&&t.jsx(O,{size:i.marginXXS,wrap:!0,children:e.tool_refs.map(l=>t.jsx(oe,{style:{background:i.colorFillSecondary,borderColor:i.colorBorderSecondary,color:i.colorText},children:l},l))})]})})},Cl=3e4,Ml=()=>{const{t:e}=re(),{message:s}=rt.useApp(),n=xt(A=>A.config),a=xt(A=>A.loadConfig),r=xt(A=>A.saveConfig),[i,l]=o.useState([]),[g,p]=o.useState(!1),[m,c]=o.useState(null),[u,f]=o.useState(null),[D,y]=o.useState(""),[d,I]=o.useState(new Date),E=o.useMemo(()=>{var A;return new Set((((A=n==null?void 0:n.skills)==null?void 0:A.disabled)??[]).map(U=>U.trim()).filter(Boolean))},[n]),j=o.useCallback(async(A=!0)=>{p(!0),c(null);try{const[U]=await Promise.all([Ha.listSkills({includeDisabled:!0},A),a({force:A})]);l(U.skills),I(new Date)}catch(U){const ie=U instanceof Error?U.message:e("components.skillManager.loadFailed");c(ie)}finally{p(!1)}},[a,e]);o.useEffect(()=>{j(!0);const A=setInterval(()=>{j(!0)},Cl);return()=>clearInterval(A)},[j]),o.useEffect(()=>{const A=()=>{j(!0)};return window.addEventListener("focus",A),()=>window.removeEventListener("focus",A)},[j]);const w=o.useCallback(async()=>{await j(!0),s.success(e("components.skillManager.skillsRefreshed"))},[j,s,e]);o.useEffect(()=>{m&&(s.error(m),c(null))},[m,s]);const x=o.useCallback(async(A,U)=>{var ie;f(A);try{const H=await a({force:!0}),C=((ie=H==null?void 0:H.skills)==null?void 0:ie.disabled)??[],k=Array.from(new Set((U?[...C,A]:C.filter(M=>M!==A)).map(M=>M.trim()).filter(Boolean))).sort();await r({...H??{},skills:{...(H==null?void 0:H.skills)??{},disabled:k}}),s.success(e("components.skillManager.skillStateSaved"))}catch(H){s.error(H instanceof Error?H.message:e("components.skillManager.saveFailed"))}finally{f(null)}},[a,s,r,e]),v=i.filter(A=>{const U=D.trim().toLowerCase();return!(U&&![A.name,A.description,A.license??"",A.compatibility??"",...A.tool_refs].join(" ").toLowerCase().includes(U))}),L=()=>{const U=new Date().getTime()-d.getTime(),ie=Math.floor(U/1e3);if(ie<5)return e("components.skillManager.justNow");if(ie<60)return e("components.skillManager.secondsAgo",{count:ie});const H=Math.floor(ie/60);return H<60?e("components.skillManager.minutesAgo",{count:H}):d.toLocaleTimeString()};return t.jsx("div",{style:{padding:"24px"},children:t.jsxs(V,{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($t,{spin:g}),onClick:w,loading:g,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:L()})})]}),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(B,{placeholder:e("components.skillManager.searchPlaceholder"),prefix:t.jsx(fr,{}),value:D,onChange:A=>y(A.target.value),allowClear:!0})}),t.jsx(ls,{spinning:g,children:v.length===0?t.jsx(Be,{description:e(D?"components.skillManager.noMatch":"components.skillManager.noSkillsFound")}):t.jsx(He,{grid:{gutter:16,xs:1,sm:2,md:3,lg:3,xl:4},dataSource:v,renderItem:A=>t.jsx(He.Item,{children:t.jsx(wl,{skill:A,disabled:E.has(A.id),busy:u===A.id,onToggleDisabled:x})})})})]})})},{Title:El,Text:_s,Paragraph:Pl}=ue,yn="model_limits",Ft={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 Dl(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)??Ft.max_context_tokens,max_output_tokens:os(s.max_output_tokens)??Ft.max_output_tokens,safety_margin:os(s.safety_margin)??Ft.safety_margin}:Ft}function Il(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 i=s.safety_margin??s.safetyMargin,l=typeof i=="number"&&Number.isFinite(i)&&i>=0?Math.floor(i):void 0;return{model_pattern:n.trim(),max_context_tokens:a,max_output_tokens:r,safety_margin:l}}function Fl(e){const s=e==null?void 0:e[yn];return Array.isArray(s)?s.map(n=>Il(n)).filter(n=>n!==null):[]}function pa(e,s,n){const a=new Map(s.map(l=>[l.model_pattern,l])),r=[],i=new Set;for(const l of s)i.has(l.model_pattern)||(i.add(l.model_pattern),r.push(l.model_pattern));for(const l of n){const g=l.trim();g&&!i.has(g)&&(i.add(g),r.push(g))}return r.map(l=>{const g=a.get(l);return{id:l,model_pattern:l,isCustom:!1,customized:!!g,max_context_tokens:(g==null?void 0:g.max_context_tokens)??e.max_context_tokens,max_output_tokens:(g==null?void 0:g.max_output_tokens)??e.max_output_tokens,safety_margin:g==null?void 0:g.safety_margin}})}function Al(e,s){const n=new Set;for(const a of e){const r=a.model_pattern.trim();if(!r)return s("settings.modelLimits.validation.modelPatternEmpty");const i=r.toLowerCase();if(n.has(i))return s("settings.modelLimits.validation.duplicateModelPattern",{pattern:r});if(n.add(i),a.max_context_tokens<1e3)return s("settings.modelLimits.validation.contextWindowMin",{pattern:r});if(a.max_output_tokens<1)return s("settings.modelLimits.validation.maxOutputMin",{pattern:r});if(a.max_output_tokens>a.max_context_tokens)return s("settings.modelLimits.validation.maxOutputExceedsContext",{pattern:r});if(typeof a.safety_margin=="number"){if(a.safety_margin<0)return s("settings.modelLimits.validation.safetyMarginNegative",{pattern:r});if(a.safety_margin>=a.max_context_tokens)return s("settings.modelLimits.validation.safetyMarginTooLarge",{pattern:r})}}return null}const ln=o.memo(function({value:s,min:n,max:a,step:r,disabled:i,ariaLabel:l,onCommit:g}){const[p,m]=o.useState(s);return o.useEffect(()=>{m(s)},[s]),t.jsx(Ee,{"aria-label":l,value:p,min:n,max:a,step:r,disabled:i,onChange:c=>m(typeof c=="number"?c:null),onBlur:()=>{const c=typeof p=="number"&&Number.isFinite(p)?p:s;m(c),c!==s&&g(c)},style:{width:"100%"}})}),Rl=o.memo(function({value:s,placeholder:n,ariaLabel:a,onCommit:r}){const[i,l]=o.useState(s);return o.useEffect(()=>{l(s)},[s]),t.jsx(B,{"aria-label":a,value:i,placeholder:n,onChange:g=>l(g.target.value),onBlur:()=>{i!==s&&r(i)}})}),zl=()=>{const{t:e}=re(),[s,n]=o.useState(Ft),[a,r]=o.useState([]),[i,l]=o.useState(!1),[g,p]=At.useMessage(),m=o.useRef(!1),c=o.useRef(0),u=o.useCallback(async()=>{l(!0);try{const[x,v]=await Promise.all([Re.getBambooConfig(),Re.getModelLimitDefaults()]),L=Dl(v);n(L),r(pa(L,Fl(x),wn()))}catch(x){console.error("Failed to load model limits settings:",x),g.error(e("settings.modelLimits.loadFailed")),n(Ft),r(pa(Ft,[],wn()))}finally{l(!1)}},[g,e]);o.useEffect(()=>{m.current||(m.current=!0,u())},[u]);const f=o.useCallback((x,v)=>{r(L=>L.map(A=>A.id===x?{...A,...v}:A))},[]),D=o.useCallback(x=>{r(v=>v.map(L=>L.id===x?{...L,customized:!0}:L))},[]),y=o.useCallback(x=>{r(v=>{const L=v.find(A=>A.id===x);return L!=null&&L.isCustom?v.filter(A=>A.id!==x):v.map(A=>A.id===x?{...A,customized:!1,max_context_tokens:s.max_context_tokens,max_output_tokens:s.max_output_tokens,safety_margin:void 0}:A)})},[s]),d=o.useCallback(x=>{r(v=>{const L=v.find(A=>A.id===x);return L&&!L.isCustom&&L.model_pattern.trim()&&Ka(L.model_pattern),v.filter(A=>A.id!==x)})},[]),I=o.useCallback(()=>{r(x=>[...x,{id:`custom-${c.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]),E=async()=>{const x=a.filter(L=>L.customized).map(L=>({model_pattern:L.model_pattern.trim(),max_context_tokens:L.max_context_tokens,max_output_tokens:L.max_output_tokens,...typeof L.safety_margin=="number"?{safety_margin:L.safety_margin}:{}})),v=Al(x,e);if(v){g.error(v);return}l(!0);try{await Re.setBambooConfig({[yn]:x}),g.success(e("settings.modelLimits.saveSuccess"))}catch(L){console.error("Failed to save model limits settings:",L),g.error(e("settings.modelLimits.saveFailed"))}finally{l(!1)}},j=async()=>{l(!0);try{await Re.setBambooConfig({[yn]:[]}),r(x=>x.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}))),g.success(e("settings.modelLimits.resetSuccess"))}catch(x){console.error("Failed to reset model limits settings:",x),g.error(e("settings.modelLimits.resetFailed"))}finally{l(!1)}},w=o.useMemo(()=>[{title:e("settings.modelLimits.columns.model"),dataIndex:"model_pattern",key:"model_pattern",width:240,render:(x,v)=>v.isCustom?t.jsx(Rl,{value:x,ariaLabel:`model-${v.id}`,placeholder:e("settings.modelLimits.placeholders.model"),onCommit:L=>f(v.id,{model_pattern:L})}):t.jsx(_s,{strong:!0,children:x})},{title:e("settings.modelLimits.columns.contextWindow"),dataIndex:"max_context_tokens",key:"max_context_tokens",width:170,render:(x,v)=>t.jsx(ln,{value:x,ariaLabel:`context-${v.id}`,min:1e3,max:5e6,step:1e3,disabled:!v.customized,onCommit:L=>f(v.id,{max_context_tokens:L})})},{title:e("settings.modelLimits.columns.maxOutput"),dataIndex:"max_output_tokens",key:"max_output_tokens",width:150,render:(x,v)=>t.jsx(ln,{value:x,ariaLabel:`output-${v.id}`,min:1,max:5e6,step:256,disabled:!v.customized,onCommit:L=>f(v.id,{max_output_tokens:L})})},{title:e("settings.modelLimits.columns.safetyMargin"),dataIndex:"safety_margin",key:"safety_margin",width:150,render:(x,v)=>t.jsx(ln,{value:x??s.safety_margin,ariaLabel:`safety-${v.id}`,min:0,max:1e6,step:100,disabled:!v.customized,onCommit:L=>f(v.id,{safety_margin:L})})},{title:e("settings.modelLimits.columns.status"),key:"status",width:150,render:(x,v)=>v.customized?t.jsx(oe,{color:"blue",children:e("settings.modelLimits.badge.customized")}):t.jsx(we,{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:(x,v)=>t.jsxs(O,{size:"small",children:[!v.customized&&t.jsx(R,{size:"small",type:"link",onClick:()=>D(v.id),children:e("settings.modelLimits.actions.customize")}),v.customized&&!v.isCustom&&t.jsx(R,{size:"small",onClick:()=>y(v.id),children:e("settings.modelLimits.actions.revert")}),t.jsx(R,{size:"small",type:"text",danger:!0,onClick:()=>d(v.id),children:e("settings.modelLimits.actions.remove")})]})}],[e,s.safety_margin,f,D,y,d]);return t.jsxs("div",{className:"model-limits-settings",children:[p,t.jsxs(V,{children:[t.jsx(El,{level:4,children:e("settings.modelLimits.title")}),t.jsxs(Pl,{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(_s,{strong:!0,children:e("settings.modelLimits.defaultsTitle")}),t.jsx(_s,{type:"secondary",children:e("settings.modelLimits.defaultsDescription")}),t.jsx(_s,{type:"secondary",children:e("settings.modelLimits.globalDefault",{context:s.max_context_tokens.toLocaleString(),output:s.max_output_tokens.toLocaleString()})})]}),t.jsx(et,{dataSource:a,columns:w,rowKey:x=>x.id,pagination:!1,size:"small",style:{margin:"16px 0"},scroll:{x:1060},locale:{emptyText:t.jsx(Be,{description:e("settings.modelLimits.emptyState")})}}),t.jsxs(O,{wrap:!0,children:[t.jsx(R,{icon:t.jsx(at,{}),onClick:I,children:e("settings.modelLimits.actions.addModel")}),t.jsx(R,{type:"primary",icon:t.jsx(As,{}),onClick:()=>void E(),loading:i,children:e("settings.modelLimits.actions.save")}),t.jsx(R,{icon:t.jsx($t,{}),onClick:()=>void j(),loading:i,children:e("settings.modelLimits.actions.resetToDefaults")}),t.jsx(R,{onClick:()=>void u(),loading:i,children:e("settings.modelLimits.actions.reload")})]})]})]})},{Text:cn}=ue,{useToken:Ll}=Se,Ol="bamboo_dark_mode",Jl=({themeMode:e,onThemeModeChange:s,locale:n,onLocaleChange:a,onBack:r})=>{const{t:i}=re(),{token:l}=Ll(),{deleteAllChats:g}=Cr(),[p,m]=o.useState(!1),[c,u]=At.useMessage(),[f,D]=o.useState(""),[y,d]=o.useState(Cn()),[I,E]=o.useState(Mn()),[j,w]=o.useState(En()),[x,v]=o.useState(Pn()),L=nt(h=>h.currentProvider),U=nt(h=>h.getProviderType)(L)==="copilot",ie=dn(h=>h.activeTabKey),H=dn(h=>h.setActiveTabKey),C=Wa(h=>h.isAdvanced),k=l.paddingSM,M=(h,F)=>({key:h,label:t.jsx(cn,{style:{color:l.colorTextSecondary,fontSize:12,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em",cursor:"default",userSelect:"none"},children:F}),disabled:!0,children:null}),S=(h,F)=>t.jsx("span",{"data-testid":`settings-tab-${h}`,children:F}),G=()=>{localStorage.clear(),c.success(i("settings.notifications.localStorageCleared"))},$=async()=>{m(!0);try{await g(),await Re.resetSetupStatus(),await Re.resetBambooConfig(),localStorage.clear(),c.success(i("settings.notifications.resetSuccessReloading")),setTimeout(()=>{window.location.reload()},1500)}catch(h){console.error("Failed to reset application:",h),c.error(h instanceof Error?h.message:i("settings.notifications.resetFailed")),m(!1)}},ee=()=>{Ja(f),c.success(i("settings.notifications.promptEnhancementSaved"))},se=h=>{d(h),Qa(h)},le=h=>{E(h),Za(h)},Q=h=>{w(h),Ya(h)},ye=h=>{v(h),er(h),window.dispatchEvent(new Event("lotus-vdi-safe-mode-change")),c.success(h?i("settings.appTab.vdiSafeModeEnabled","Graphics compatibility mode enabled"):i("settings.appTab.vdiSafeModeDisabled","Graphics compatibility mode disabled"))};return o.useEffect(()=>{D(Ga()),d(Cn()),E(Mn()),w(En()),v(Pn())},[]),t.jsxs(W,{vertical:!0,role:"region","aria-label":i("settings.page.title"),style:{height:"100vh",overflow:"hidden",background:l.colorBgContainer},children:[u,t.jsxs(W,{align:"center",justify:"space-between",style:{padding:l.padding,paddingTop:l.padding+k,borderBottom:`1px solid ${l.colorBorderSecondary}`},children:[t.jsxs(W,{align:"center",gap:l.marginSM,children:[t.jsx(R,{icon:t.jsx(br,{}),onClick:r,"aria-label":i("settings.page.back"),children:i("settings.page.back")}),t.jsx(cn,{strong:!0,"data-testid":"settings-page-title",children:i("settings.page.title")})]}),t.jsxs(cn,{type:"secondary","data-testid":"settings-page-version",children:[i("settings.appTab.runningVersion","Running version"),": v",ma]})]}),t.jsx(xr.Content,{style:{flex:1,minHeight:0,overflow:"auto",padding:l.padding},children:t.jsx(Es,{tabPosition:"left",activeKey:ie,onChange:h=>H(h),items:[M("group-ai",i("settings.page.groups.ai")),{key:"provider",label:S("provider",i("settings.page.tabs.provider")),children:t.jsx(_l,{})},{key:"model-limits",label:S("model-limits",i("settings.page.tabs.modelLimits")),children:t.jsx(zl,{})},{key:"prompts",label:S("prompts",i("settings.page.tabs.prompts")),children:t.jsx($r,{promptEnhancement:f,onPromptEnhancementChange:D,mermaidEnhancementEnabled:y,taskEnhancementEnabled:I,showCopilotConclusionWithOptionsEnhancement:U,copilotConclusionWithOptionsEnhancementEnabled:j,onMermaidToggle:se,onTaskToggle:le,onCopilotConclusionWithOptionsToggle:Q,onSaveEnhancement:ee})},M("group-tools",i("settings.page.groups.toolsAndExtensions")),{key:"skills",label:S("skills",i("settings.page.tabs.skills")),children:t.jsx(Ml,{})},{key:"mcp",label:S("mcp",i("settings.page.tabs.mcp")),children:t.jsx(Oi,{})},{key:"plugins",label:S("plugins",i("settings.page.tabs.plugins")),children:t.jsx(eo,{})},{key:"workflows",label:S("workflows",i("settings.page.tabs.workflows")),children:t.jsx(oi,{})},{key:"hooks",label:S("hooks",i("settings.page.tabs.hooks")),children:t.jsx(Xo,{})},M("group-security",i("settings.page.groups.securityAndPrivacy")),{key:"permissions",label:S("permissions",i("settings.page.tabs.permissions")),children:t.jsx(Xr,{})},{key:"masking",label:S("masking",i("settings.page.tabs.masking")),children:t.jsx(Kr,{})},{key:"env-vars",label:S("env-vars",i("settings.page.tabs.envVars")),children:t.jsx(Zr,{})},M("group-deployment",i("settings.page.groups.deployment","Deployment")),{key:"clusters",label:S("clusters",i("settings.page.tabs.clusters","Clusters")),children:t.jsx(ni,{})},M("group-monitoring",i("settings.page.groups.monitoring")),{key:"metrics",label:S("metrics",i("settings.page.tabs.metrics")),children:t.jsx(Ho,{})},{key:"sessions",label:S("sessions",i("settings.page.tabs.sessions")),children:t.jsx(ll,{})},M("group-system",i("settings.page.groups.system")),{key:"config",label:S("config",i("settings.page.tabs.config")),children:t.jsx(Rr,{msgApi:c,locale:n,onLocaleChange:a})},{key:"schedules",label:S("schedules",i("settings.page.tabs.schedules")),children:t.jsx(ol,{})},{key:"notifications",label:S("notifications",i("settings.page.tabs.notifications","Notifications")),children:t.jsx(yl,{})},{key:"app",label:S("app",i("settings.page.tabs.app")),children:t.jsx(qr,{themeMode:e,onThemeModeChange:s,vdiSafeMode:x,onVdiSafeModeToggle:ye,onClearLocalStorage:G,onResetApp:$,isResetting:p,darkModeKey:Ol})}].filter(h=>!(!C&&h.key&&Xa.has(h.key)||!C&&(h.key==="group-security"||h.key==="group-deployment"||h.key==="group-monitoring")))})})]})},Nl=()=>{const{t:e}=re(),{message:s}=rt.useApp(),n=Le(d=>d.systemPrompts),a=Le(d=>d.addSystemPrompt),r=Le(d=>d.updateSystemPrompt),i=Le(d=>d.deleteSystemPrompt),[l,g]=o.useState(!1),[p,m]=o.useState(null),[c]=b.useForm(),u=(d=null)=>{if(d!=null&&d.isDefault){s.warning(e("settings.systemPromptManager.defaultPromptLocked"));return}m(d),c.setFieldsValue(d||{name:"",description:"",content:""}),g(!0)},f=()=>{g(!1),m(null),c.resetFields()},D=async()=>{if(p!=null&&p.isDefault){s.warning(e("settings.systemPromptManager.defaultPromptLocked"));return}try{const d=await c.validateFields();p?(await r({...p,...d}),s.success(e("settings.systemPromptManager.updateSuccess"))):(await a(d),s.success(e("settings.systemPromptManager.addSuccess"))),f()}catch(d){console.error("Failed to save prompt:",d),s.error(d instanceof Error?d.message:e("settings.systemPromptManager.saveError"))}},y=async d=>{try{await i(d),s.success(e("settings.systemPromptManager.deleteSuccess"))}catch(I){console.error("Failed to delete prompt:",I),s.error(I instanceof Error?I.message:e("settings.systemPromptManager.deleteError"))}};return t.jsxs("div",{children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:16},children:[t.jsx("h2",{children:e("settings.systemPromptManager.title")}),t.jsx(R,{type:"primary",icon:t.jsx(at,{}),onClick:()=>u(),children:e("settings.systemPromptManager.addButton")})]}),t.jsx(He,{itemLayout:"horizontal",dataSource:n,renderItem:d=>t.jsxs(He.Item,{actions:[d.isDefault?null:t.jsx(R,{type:"text",icon:t.jsx(Vt,{}),onClick:()=>u(d)}),d.isDefault?null:t.jsx(Tt,{title:e("settings.systemPromptManager.deleteConfirm"),onConfirm:()=>y(d.id),okText:e("common.yes"),cancelText:e("common.no"),children:t.jsx(R,{type:"text",danger:!0,icon:t.jsx(kt,{}),"aria-label":e("common.delete")})})],children:[t.jsx(He.Item.Meta,{title:d.name,description:d.description||d.content.substring(0,200)+(d.content.length>200?"...":"")}),d.isDefault&&t.jsx(oe,{children:e("settings.systemPromptManager.defaultTag")})]})}),t.jsx(Xe,{title:e(p?"settings.systemPromptManager.editTitle":"settings.systemPromptManager.addTitle"),open:l,onOk:D,onCancel:f,width:"60%",forceRender:!0,children:t.jsxs(b,{form:c,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(B,{})}),t.jsx(b.Item,{name:"description",label:e("settings.systemPromptManager.descriptionLabel"),rules:[{required:!1,message:e("settings.systemPromptManager.descriptionRequired")}],children:t.jsx(B.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(B.TextArea,{rows:10})})]})})]})},Vl=Object.freeze(Object.defineProperty({__proto__:null,default:Nl},Symbol.toStringTag,{value:"Module"}));export{Jl as SystemSettingsPage};