@bigduu/lotus 2026.7.13 → 2026.7.14

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