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