@bigduu/lotus 2026.6.1 → 2026.6.2
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-BXg9aOQo.js → App-CiBjfJbZ.js} +57 -57
- package/dist/assets/{MetricsService-CS2FzJEZ.js → MetricsService-B6NNBaFU.js} +1 -1
- package/dist/assets/{SubAgentsPanel-CTmxBJOI.js → SubAgentsPanel-CJmIvsg3.js} +1 -1
- package/dist/assets/{architectureDiagram-3BPJPVTR-CfNd2ju1.js → architectureDiagram-3BPJPVTR-B6Aigvp7.js} +1 -1
- package/dist/assets/{blockDiagram-GPEHLZMM-CzaJ_pbA.js → blockDiagram-GPEHLZMM-BG4jFash.js} +1 -1
- package/dist/assets/{c4Diagram-AAUBKEIU-ypj9j2s3.js → c4Diagram-AAUBKEIU-Bmsq6Nwl.js} +1 -1
- package/dist/assets/{chunk-2J33WTMH-cxR1lkw0.js → chunk-2J33WTMH-BeBOyD8r.js} +1 -1
- package/dist/assets/{chunk-4BX2VUAB-BMCnsVjr.js → chunk-4BX2VUAB-CvWY7Izk.js} +1 -1
- package/dist/assets/{chunk-55IACEB6-D5qDBBVU.js → chunk-55IACEB6-CSRfOrIS.js} +1 -1
- package/dist/assets/{chunk-727SXJPM-C74VNgAu.js → chunk-727SXJPM-k_VOeRRa.js} +1 -1
- package/dist/assets/{chunk-AQP2D5EJ-DbUWOqIq.js → chunk-AQP2D5EJ-eCCYzF54.js} +1 -1
- package/dist/assets/{chunk-FMBD7UC4-BVb6PdZp.js → chunk-FMBD7UC4-B7yGAY4w.js} +1 -1
- package/dist/assets/{chunk-ND2GUHAM-v91-WFgP.js → chunk-ND2GUHAM-pNlL9ELu.js} +1 -1
- package/dist/assets/{chunk-QZHKN3VN-xcLEyNod.js → chunk-QZHKN3VN-C46sDVU5.js} +1 -1
- package/dist/assets/classDiagram-4FO5ZUOK-Bt1SwZSt.js +1 -0
- package/dist/assets/classDiagram-v2-Q7XG4LA2-Bt1SwZSt.js +1 -0
- package/dist/assets/{cose-bilkent-S5V4N54A-DzcQkCVo.js → cose-bilkent-S5V4N54A-BbJSEGbL.js} +1 -1
- package/dist/assets/{dagre-BM42HDAG-DV3G1jIK.js → dagre-BM42HDAG-DAgnHbAW.js} +1 -1
- package/dist/assets/{diagram-2AECGRRQ-ClQcS_zG.js → diagram-2AECGRRQ-DvSwTGxM.js} +1 -1
- package/dist/assets/{diagram-5GNKFQAL-xHZWrs3k.js → diagram-5GNKFQAL-DEJHaLfu.js} +1 -1
- package/dist/assets/{diagram-KO2AKTUF-BGYvfmA8.js → diagram-KO2AKTUF-DrqjmP_T.js} +1 -1
- package/dist/assets/{diagram-LMA3HP47-2bYJHrSx.js → diagram-LMA3HP47-Bjo5cwtc.js} +1 -1
- package/dist/assets/{diagram-OG6HWLK6-Kk9gxCVl.js → diagram-OG6HWLK6-Xt8OEUbk.js} +1 -1
- package/dist/assets/{en-US-Bn6iZkOI.js → en-US-Bj91Ptrm.js} +1 -1
- package/dist/assets/{erDiagram-TEJ5UH35-BODZveFO.js → erDiagram-TEJ5UH35-CyY6UxKD.js} +1 -1
- package/dist/assets/{flowDiagram-I6XJVG4X-CXtrCQJF.js → flowDiagram-I6XJVG4X-CxYF-4G3.js} +1 -1
- package/dist/assets/{ganttDiagram-6RSMTGT7-BBPnJiUa.js → ganttDiagram-6RSMTGT7-CPOiW77k.js} +1 -1
- package/dist/assets/{gitGraphDiagram-PVQCEYII-CFmk9GD0.js → gitGraphDiagram-PVQCEYII-DrOgkuZM.js} +1 -1
- package/dist/assets/{index-BLrE8oNh.js → index-2nERrqJS.js} +1 -1
- package/dist/assets/{index-CnF7-tch.js → index-B4T1KHs6.js} +1 -1
- package/dist/assets/{index-B6xj4xYP.js → index-BWX57hkV.js} +1 -1
- package/dist/assets/{index-B4aaoHUX.js → index-BeXVgYXk.js} +1 -1
- package/dist/assets/{index-Bdt7YoZz.js → index-BjFjcKGZ.js} +1 -1
- package/dist/assets/{index-obms6vkJ.js → index-BmrwviZb.js} +1 -1
- package/dist/assets/{index-JRKXto4y.js → index-D6dXobma.js} +1 -1
- package/dist/assets/{index-6B8IkGDb.js → index-DNS3k4mM.js} +1 -1
- package/dist/assets/{index-BuED28Gm.js → index-DPAR85WM.js} +1 -1
- package/dist/assets/{index-D4RmBZ35.js → index-Di8pH-kP.js} +1 -1
- package/dist/assets/index-DiWM3I28.js +22 -0
- package/dist/assets/{infoDiagram-5YYISTIA-AS1OZJpo.js → infoDiagram-5YYISTIA-C84arbm7.js} +1 -1
- package/dist/assets/{ishikawaDiagram-YF4QCWOH-yh6mGC1K.js → ishikawaDiagram-YF4QCWOH-CcecJvgD.js} +1 -1
- package/dist/assets/{journeyDiagram-JHISSGLW-CfHcAvFf.js → journeyDiagram-JHISSGLW-BUqT2Za3.js} +1 -1
- package/dist/assets/{kanban-definition-UN3LZRKU-D7-RkKh-.js → kanban-definition-UN3LZRKU-CzZzby99.js} +1 -1
- package/dist/assets/main-CvPZyRz3.js +8 -0
- package/dist/assets/{mindmap-definition-RKZ34NQL-ByOSyFEz.js → mindmap-definition-RKZ34NQL-CmVDGb3s.js} +1 -1
- package/dist/assets/{pieDiagram-4H26LBE5-D97Mptgo.js → pieDiagram-4H26LBE5-DH2IiUT-.js} +1 -1
- package/dist/assets/{quadrantDiagram-W4KKPZXB-DKmv7sbz.js → quadrantDiagram-W4KKPZXB--NA0nuaI.js} +1 -1
- package/dist/assets/{requirementDiagram-4Y6WPE33-DSDo-apm.js → requirementDiagram-4Y6WPE33-DgTgIhBX.js} +1 -1
- package/dist/assets/{sankeyDiagram-5OEKKPKP-CNgJWj6_.js → sankeyDiagram-5OEKKPKP-CALJaoqk.js} +1 -1
- package/dist/assets/{sequenceDiagram-3UESZ5HK-DVMQ9erI.js → sequenceDiagram-3UESZ5HK-BXGdJmYN.js} +1 -1
- package/dist/assets/{stateDiagram-AJRCARHV-CAlvotuZ.js → stateDiagram-AJRCARHV-CLL4nh4w.js} +1 -1
- package/dist/assets/{stateDiagram-v2-BHNVJYJU-rFHRfg3k.js → stateDiagram-v2-BHNVJYJU-CFglal-4.js} +1 -1
- package/dist/assets/{timeline-definition-PNZ67QCA-HxLzqMGH.js → timeline-definition-PNZ67QCA-BIZqkLkh.js} +1 -1
- package/dist/assets/{vendor-charts-DoGYnHid.js → vendor-charts-CRpjYi1a.js} +1 -1
- package/dist/assets/{vendor-mermaid-CmKdUpW3.js → vendor-mermaid-DBtTSFLf.js} +3 -3
- package/dist/assets/{vendor-pdf-DAUhee3g.js → vendor-pdf-DpZo6MNQ.js} +3 -3
- package/dist/assets/{vennDiagram-CIIHVFJN-CZrGRioU.js → vennDiagram-CIIHVFJN-D1jzM1K8.js} +1 -1
- package/dist/assets/{wardley-L42UT6IY-DLqtcZsS.js → wardley-L42UT6IY-Yq8es9jt.js} +1 -1
- package/dist/assets/{wardleyDiagram-YWT4CUSO-I4nxJXjC.js → wardleyDiagram-YWT4CUSO-DlhxW9kY.js} +1 -1
- package/dist/assets/{xychartDiagram-2RQKCTM6-I13trKeP.js → xychartDiagram-2RQKCTM6-BipN62gu.js} +1 -1
- package/dist/assets/{zh-CN-Cw8YiQz9.js → zh-CN-C8K1JeQZ.js} +1 -1
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/dist/assets/classDiagram-4FO5ZUOK-DqFhz_US.js +0 -1
- package/dist/assets/classDiagram-v2-Q7XG4LA2-DqFhz_US.js +0 -1
- package/dist/assets/index-Byd6pVRV.js +0 -22
- package/dist/assets/main-CAEW-hKr.js +0 -8
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-BmrwviZb.js","./vendor-markdown-DrYaLZhb.js","./vendor-i18n-Dm-c3D_C.js","./vendor-antd-CKNrd1kL.js","./App-CiBjfJbZ.js","./vendor-mermaid-DBtTSFLf.js","./main-CvPZyRz3.js","./main-B6snAd4S.css","./App-D0TZLRrI.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
var cn=Object.defineProperty;var dn=(e,s,a)=>s in e?cn(e,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[s]=a;var ia=(e,s,a)=>dn(e,typeof s!="symbol"?s+"":s,a);import{j as t}from"./vendor-markdown-DrYaLZhb.js";import{a as o,u as te,R as oa,i as ae}from"./vendor-i18n-Dm-c3D_C.js";import{F as un,u as Ue,b as gn,O as mn,s as pn,P as ea,k as Ze,x as ot,Q as hn,R as pt,S as Fe,T as fn,U as yn,V as xn,W as bn,X as Ga,Y as nt,Z as Te,D as la,a as et,_ as Ja,B as ta,d as vn,c as Js,o as Tn,$ as ca,a0 as jn,a1 as Sn,a2 as ht,a3 as xs,a4 as _n,a5 as kn,a6 as da,a7 as wn,a8 as ua,a9 as ga,aa as ma,ab as pa,f as Cn,ac as Mn,A as En,ad as Dn,ae as Pn,af as In,ag as Fn,ah as An}from"./App-CiBjfJbZ.js";import{G as z,j as A,A as Ve,l as ce,a3 as H,N as O,t as fe,Y as v,W as es,aE as vs,aF as Q,aG as me,z as Qe,aH as We,aI as le,q as ve,aJ as qe,aK as Me,aL as Rn,aC as Re,F as W,aM as Ss,aN as zn,a0 as ts,a1 as ns,ak as On,aO as Ln,X as Ft,aP as _s,$ as ks,Z as Ct,aQ as ha,o as re,aR as ct,a2 as lt,as as At,V as Rt,ag as Pt,aS as Nn,aj as Vn,aT as fa,aU as Ae,Q as $e,ar as Xa,aV as $n,aW as dt,aX as Se,B as Bn,aY as ya,aZ as qn,a_ as Un,p as Xs,I as Hn,a$ as Kn,b0 as Wn,b1 as Ya,b2 as ft,b3 as xa,b4 as Gn,ab as Jn,ax as Xn,b5 as Yn}from"./vendor-antd-CKNrd1kL.js";import{_ as Ys}from"./vendor-mermaid-DBtTSFLf.js";import{r as Zn}from"./onboardingStorage-BVcEpmTy.js";import"./main-CvPZyRz3.js";import{m as Zt}from"./MetricsService-B6NNBaFU.js";import{R as zt,B as sa,C as rs,X as is,Y as os,T as Ot,L as aa,a as Ts,b as Za,c as It,P as Qn,d as er,e as tr}from"./vendor-charts-CRpjYi1a.js";function sr(e){return e instanceof un}function ar(){const{chats:e,currentSessionId:s,currentChat:a,addMessage:n,selectSession:r,deleteSession:i,deleteSessions:l,deleteMessage:c,updateSession:d,persistSessionTitle:u,pinSession:g,unpinSession:j,loadChats:h}=Ue(gn(w=>({chats:w.chats,currentSessionId:w.currentSessionId,currentChat:mn(w),addMessage:w.addMessage,selectSession:w.selectSession,deleteSession:w.deleteSession,deleteSessions:w.deleteSessions,deleteMessage:w.deleteMessage,updateSession:w.updateSession,persistSessionTitle:w.persistSessionTitle,pinSession:w.pinSession,unpinSession:w.unpinSession,loadChats:w.loadChats}))),S=Ue(pn(s)),k=o.useMemo(()=>(a==null?void 0:a.messages)||[],[a]),_=o.useMemo(()=>e.filter(w=>w.pinned),[e]),F=o.useMemo(()=>e.filter(w=>!w.pinned),[e]),M=e.length;return{chats:e,currentSessionId:s,currentChat:a,isProcessing:S,baseMessages:k,pinnedChats:_,unpinnedChats:F,chatCount:M,addMessage:n,deleteMessage:c,selectSession:r,deleteSession:i,deleteSessions:l,pinSession:g,unpinSession:j,updateSession:d,persistSessionTitle:u,loadChats:h}}function nr(e){const s=Ue(h=>h.addChat),a=Ue(h=>h.lastSelectedPromptId),n=Ue(h=>h.systemPrompts),r=ea.getInstance(),i=o.useCallback(async(h,S)=>{var M,w;const k=n.find(D=>D.id===a),_=(k==null?void 0:k.id)||(n.length>0?((M=n.find(D=>D.id==="general_assistant"))==null?void 0:M.id)||n[0].id:""),F={title:h||"New Session",createdAt:Date.now(),messages:[],config:{systemPromptId:_,baseSystemPrompt:(k==null?void 0:k.content)||(n.length>0?((w=n.find(D=>D.id==="general_assistant"))==null?void 0:w.content)||n[0].content:""),lastUsedEnhancedPrompt:null,...Ze.getState().isProviderModelRefEnabled()?{model_ref:Ze.getState().selectedModelRef}:{}},...S};await s(F)},[s,a,n]),l=o.useCallback(async h=>{ot("[ChatOps]","[useChatOperations] createChatWithSystemPrompt started with prompt:",h);const S={title:`New Session - ${h.name}`,createdAt:Date.now(),messages:[],config:{systemPromptId:h.id,baseSystemPrompt:h.content,lastUsedEnhancedPrompt:null}};ot("[ChatOps]","[useChatOperations] Calling addChat with newChatData.config:",S.config),await s(S)},[s]),c=o.useCallback(h=>{const S=e.chats.find(k=>k.id===h);S&&(S.pinned?e.unpinSession(h):e.pinSession(h))},[e]),d=o.useCallback((h,S)=>{e.updateSession(h,{title:S})},[e]),u=o.useCallback(async()=>{await r.cleanupSessions("empty",!0),await Ue.getState().loadChats()},[r]),g=o.useCallback(async()=>{await r.cleanupSessions("all",!0),await Ue.getState().loadChats()},[r]),j=o.useCallback(async()=>{await r.cleanupSessions("all",!1),await Ue.getState().loadChats()},[r]);return{createNewChat:i,createChatWithSystemPrompt:l,toggleChatPin:c,updateChatTitle:d,deleteEmptyChats:u,deleteAllUnpinnedChats:g,deleteAllChats:j}}function rr(e,s){const a=o.useMemo(()=>e.baseMessages,[e.baseMessages]),n=o.useCallback(async()=>{var u;if(!e.currentSessionId||!e.currentChat)return;const r=[...e.baseMessages];if(r.length===0)return;const i=r[r.length-1];let l=r;if((i==null?void 0:i.role)==="assistant"){if(!(await e.deleteMessage(e.currentSessionId,i.id)).success)return;l=r.slice(0,-1)}const c=[...l].reverse().find(g=>g.role==="user");if(!c)return;const d="content"in c?c.content:c.displayText;typeof d=="string"&&await((u=s==null?void 0:s.onRetry)==null?void 0:u.call(s,d))},[e,s]);return{currentMessages:a,retryLastMessage:n}}const ir=()=>{const e=ar(),s=nr(e),a=hn({sessionId:e.currentSessionId,addMessage:e.addMessage,updateSession:e.updateSession}),n=rr(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:gs}=ce,{useToken:or}=fe,lr=({httpProxy:e,httpsProxy:s,onHttpProxyChange:a,onHttpsProxyChange:n,onReload:r,onSave:i,isLoading:l})=>{const{t:c}=te(),{token:d}=or(),u=pt(m=>m.proxyAuthStatus),g=pt(m=>m.isLoadingProxyAuthStatus),j=pt(m=>m.loadProxyAuthStatus),h=pt(m=>m.applyProxyAuth),S=pt(m=>m.clearProxyAuth),[k,_]=o.useState({username:"",password:""}),[F,M]=o.useState(!1);o.useEffect(()=>{j()},[j]);const w=async()=>{const m=k.username.trim();if(m){M(!0);try{await h({username:m,password:k.password}),_({username:"",password:""})}catch(x){console.error("Failed to apply proxy auth:",x)}finally{M(!1)}}},D=async()=>{M(!0);try{await S()}catch(m){console.error("Failed to clear proxy auth:",m)}finally{M(!1)}};return t.jsx(z,{size:"small",title:t.jsx(gs,{strong:!0,children:c("settings.networkCard.title")}),className:"lotus-settings-card",children:t.jsxs(A,{direction:"vertical",size:d.marginSM,style:{width:"100%"},children:[t.jsx(Ve,{message:c("settings.networkCard.guideTip"),type:"info",showIcon:!0}),t.jsxs(A,{direction:"vertical",size:d.marginXXS,style:{width:"100%"},children:[t.jsx(gs,{type:"secondary",children:c("settings.networkCard.httpProxy")}),t.jsx(H,{"data-testid":"proxy-url",style:{width:"100%"},value:e,onChange:m=>a(m.target.value),placeholder:c("settings.networkCard.proxyPlaceholder"),disabled:l})]}),t.jsxs(A,{direction:"vertical",size:d.marginXXS,style:{width:"100%"},children:[t.jsx(gs,{type:"secondary",children:c("settings.networkCard.httpsProxy")}),t.jsx(H,{style:{width:"100%"},value:s,onChange:m=>n(m.target.value),placeholder:c("settings.networkCard.proxyPlaceholder"),disabled:l})]}),t.jsx(z,{size:"small",title:c("settings.networkCard.proxyAuthTitle"),className:"lotus-settings-card",style:{marginTop:d.marginSM},children:u!=null&&u.configured?t.jsxs(A,{direction:"vertical",style:{width:"100%"},children:[t.jsx(Ve,{type:"success",message:c("settings.networkCard.proxyConfiguredForUser",{username:u.username??""}),showIcon:!0}),t.jsx(O,{onClick:D,loading:F||g,danger:!0,children:c("settings.networkCard.clearCredentials")})]}):t.jsxs(A,{direction:"vertical",size:d.marginXS,style:{width:"100%"},children:[t.jsx(H,{placeholder:c("settings.networkCard.username"),value:k.username,onChange:m=>_(x=>({...x,username:m.target.value}))}),t.jsx(H.Password,{placeholder:c("settings.networkCard.password"),value:k.password,onChange:m=>_(x=>({...x,password:m.target.value}))}),t.jsx(O,{type:"primary",onClick:w,loading:F||g,disabled:!k.username.trim(),children:c("settings.networkCard.apply")})]})}),t.jsx(gs,{type:"secondary",style:{fontSize:d.fontSizeSM},children:c("settings.networkCard.credentialsStorageNote")}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:d.marginSM},children:[t.jsx(O,{onClick:()=>Promise.resolve(r()).finally(()=>j({force:!0})),disabled:l,children:c("settings.networkCard.reload")}),t.jsx(O,{"data-testid":"save-proxy-settings",type:"primary",onClick:()=>Promise.resolve(i()).finally(()=>j({force:!0})),disabled:l,children:c("settings.networkCard.save")})]})]})})};function Qa(e){return typeof e=="object"&&e!==null&&"errorFields"in e}const{Text:cr}=ce,{useToken:dr}=fe,ur=({msgApi:e})=>{const{t:s}=te(),{token:a}=dr(),[n]=v.useForm(),[r,i]=o.useState(!1),[l,c]=o.useState(!1),[d,u]=o.useState(!1),[g,j]=o.useState(!1),[h,S]=o.useState(null),k=d&&!g,_=o.useMemo(()=>s(d?g?"settings.configTab.accessPassword.helperLocalBypass":"settings.configTab.accessPassword.helperRemote":"settings.configTab.accessPassword.helperNotEnabled"),[g,d,s]),F=o.useCallback(async()=>{i(!0),S(null);try{const w=await Fe.getAccessStatus();u(w.password_enabled),j(w.local_bypass)}catch(w){const D=w instanceof Error?w.message:s("settings.configTab.accessPassword.loadStatusFailed","Failed to load access status");S(D)}finally{i(!1)}},[s]);o.useEffect(()=>{F()},[F]);const M=async()=>{var w;try{const D=await n.validateFields();c(!0),await Fe.updateAccessPassword({current_password:((w=D.currentPassword)==null?void 0:w.trim())||void 0,new_password:D.newPassword.trim()}),e.success(s(d?"settings.configTab.accessPassword.updated":"settings.configTab.accessPassword.enabled")),n.resetFields(),await F()}catch(D){if(Qa(D))return;const m=D instanceof Error?D.message:s("settings.configTab.accessPassword.updateFailed","Failed to update access password");e.error(m)}finally{c(!1)}};return t.jsx(z,{size:"small",className:"lotus-settings-card",title:t.jsx(cr,{strong:!0,children:s("settings.configTab.accessPasswordTitle")}),children:t.jsxs(A,{direction:"vertical",size:a.marginMD,style:{width:"100%"},children:[t.jsx(Ve,{type:d?"info":"warning",showIcon:!0,message:s(d?"settings.configTab.accessPassword.statusEnabled":"settings.configTab.accessPassword.statusDisabled"),description:_}),h?t.jsx(Ve,{type:"error",showIcon:!0,message:h}):null,t.jsxs(v,{form:n,layout:"vertical",disabled:r||l,children:[k?t.jsx(v.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(v.Item,{label:s(d?"settings.configTab.accessPassword.newPasswordLabel":"settings.configTab.accessPassword.setPasswordLabel"),name:"newPassword",rules:[{required:!0,message:s("settings.configTab.accessPassword.validation.newPasswordRequired")},{min:4,message:s("settings.configTab.accessPassword.validation.minLength")}],children:t.jsx(H.Password,{autoComplete:"new-password"})}),t.jsx(v.Item,{label:s("settings.configTab.accessPassword.confirmPasswordLabel"),name:"confirmPassword",dependencies:["newPassword"],rules:[{required:!0,message:s("settings.configTab.accessPassword.validation.confirmPasswordRequired")},({getFieldValue:w})=>({validator(D,m){return!m||w("newPassword")===m?Promise.resolve():Promise.reject(new Error(s("settings.configTab.accessPassword.validation.passwordMismatch")))}})],children:t.jsx(H.Password,{autoComplete:"new-password"})}),t.jsx(O,{type:"primary",loading:l,onClick:()=>void M(),children:s(d?"settings.configTab.accessPassword.updateAction":"settings.configTab.accessPassword.enableAction")})]})]})})},{Text:Xe}=ce,{useToken:gr}=fe,ba="http://127.0.0.1:9562/v1",Xt=e=>[...new Set(e.map(s=>s.trim()).filter(s=>s.length>0))].sort(),mr=e=>{var a;const s=(a=e.tools)==null?void 0:a.disabled;return Array.isArray(s)?Xt(s.filter(n=>typeof n=="string")):[]},pr=({msgApi:e,locale:s,onLocaleChange:a})=>{const{t:n}=te(),{token:r}=gr(),[i,l]=o.useState({http_proxy:"",https_proxy:"",memory:{auto_dream_enabled:!1}}),[c,d]=o.useState(ba),[u,g]=o.useState([]),[j,h]=o.useState([]),[S,k]=o.useState([]),[_,F]=o.useState(!1),[M,w]=o.useState(!1),D=o.useCallback(async()=>{var R;F(!0);try{const[B,se]=await Promise.all([Fe.getBambooConfig(),Fe.getBambooTools()]);l({http_proxy:B.http_proxy||"",https_proxy:B.https_proxy||"",memory:{auto_dream_enabled:((R=B.memory)==null?void 0:R.auto_dream_enabled)??!1}});const G=mr(B);h(G),k(G),g(Xt(se.tools||[]))}catch(B){console.error("Failed to load config:",B),e.error(n("settings.configTab.loadConfigFailed"))}finally{F(!1)}},[e,n]);o.useEffect(()=>{D()},[D]);const m=R=>{l(B=>({...B,http_proxy:R}))},x=R=>{l(B=>({...B,https_proxy:R}))},L=R=>{l(B=>({...B,memory:{...B.memory,auto_dream_enabled:R}}))},P=async()=>{var R,B;F(!0);try{const se=await Fe.validateBambooConfigPatch(i);if(!se.valid){const ge=((B=(R=se.errors)==null?void 0:R.proxy)==null?void 0:B[0])??Object.values(se.errors||{}).flat().filter(Boolean)[0];e.error((ge==null?void 0:ge.message)||n("settings.configTab.invalidConfig"));return}await Fe.setBambooConfig(i),e.success(n("settings.configTab.saveConfigSuccess"))}catch(se){console.error("Failed to save config:",se);const G=se instanceof Error&&se.message.trim()?se.message:n("settings.configTab.saveConfigFailed");e.error(G)}finally{F(!1)}},K=async()=>{e.success(n("settings.configTab.backendSaved"))},Z=()=>{d(ba),e.success(n("settings.configTab.backendResetDefault"))},N=(R,B)=>{h(se=>{const G=new Set(se);return B?G.delete(R):G.add(R),Xt([...G])})},f=async()=>{w(!0);try{const R=await Fe.getBambooTools();g(Xt(R.tools||[])),e.success(n("settings.configTab.toolsReloadSuccess"))}catch(R){console.error("Failed to reload tools:",R),e.error(n("settings.configTab.toolsLoadFailed"))}finally{w(!1)}},b=async()=>{w(!0);try{const R=Xt(j);await Fe.setBambooConfig({tools:{disabled:R}}),h(R),k(R),e.success(n("settings.configTab.toolsSaveSuccess"))}catch(R){console.error("Failed to save tool settings:",R),e.error(n("settings.configTab.toolsSaveFailed"))}finally{w(!1)}},E=JSON.stringify(j)!==JSON.stringify(S),I=new Set(j);return t.jsx(es,{spinning:_,tip:n("settings.common.loading"),children:t.jsx(vs,{items:[{key:"general",label:n("settings.configTab.tabs.general"),children:t.jsxs(A,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[t.jsx(lr,{httpProxy:i.http_proxy,httpsProxy:i.https_proxy,onHttpProxyChange:m,onHttpsProxyChange:x,onReload:D,onSave:P,isLoading:_}),t.jsx(z,{size:"small",className:"lotus-settings-card",title:t.jsx(Xe,{strong:!0,children:n("settings.configTab.language")}),children:t.jsx(Q,{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:R=>a(R)})}),t.jsx(z,{size:"small",className:"lotus-settings-card",title:t.jsx(Xe,{strong:!0,children:n("settings.configTab.memoryTitle")}),children:t.jsxs(A,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[t.jsx(Xe,{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(Xe,{strong:!0,children:n("settings.configTab.autoDreamEnabled")}),t.jsx("div",{children:t.jsx(Xe,{type:"secondary",style:{fontSize:r.fontSizeSM},children:n("settings.configTab.autoDreamEnabledHint")})})]}),t.jsx(me,{"data-testid":"auto-dream-toggle",checked:i.memory.auto_dream_enabled,onChange:L})]}),t.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:t.jsx(O,{"data-testid":"save-memory-settings",type:"primary",onClick:P,loading:_,children:n("settings.configTab.save")})})]})}),t.jsx(z,{size:"small",title:t.jsx(Xe,{strong:!0,children:n("settings.configTab.backendApiBaseUrlTitle")}),children:t.jsxs(A,{direction:"vertical",size:r.marginSM,style:{width:"100%"},children:[t.jsx(A,{direction:"vertical",size:r.marginXXS,style:{width:"100%"},children:t.jsx(H,{style:{width:"100%"},value:c,onChange:R=>d(R.target.value),placeholder:n("settings.configTab.backendApiPlaceholder")})}),t.jsx(Xe,{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(O,{"data-testid":"reset-to-defaults",onClick:Z,children:n("settings.configTab.resetToDefault")}),t.jsx(O,{"data-testid":"save-api-settings",type:"primary",onClick:K,children:n("settings.configTab.save")})]})]})}),t.jsx(ur,{msgApi:e})]})},{key:"tools",label:n("settings.configTab.tabs.tools"),children:t.jsx(z,{size:"small",title:t.jsx(Xe,{strong:!0,children:n("settings.configTab.toolsTitle")}),children:t.jsxs(A,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[t.jsx(Xe,{type:"secondary",children:n("settings.configTab.toolsDescription")}),u.length===0?t.jsx(Ve,{type:"info",showIcon:!0,message:n("settings.configTab.toolsEmpty")}):t.jsx(Qe,{bordered:!0,dataSource:u,renderItem:R=>t.jsx(Qe.Item,{actions:[t.jsx(me,{checked:!I.has(R),onChange:B=>N(R,B)},`${R}-switch`)],children:t.jsx(Xe,{code:!0,children:R})})}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:r.marginSM},children:[t.jsx(O,{onClick:f,loading:M,children:n("settings.configTab.reloadTools")}),t.jsx(O,{type:"primary",onClick:b,loading:M,disabled:!E,children:n("settings.configTab.save")})]})]})})}]})})},{Title:hr,Text:zs}=ce,{useToken:fr}=fe,yr=()=>{const{t:e}=te(),{token:s}=fr(),a=fn(),n=yn(),r=xn(),[i]=v.useForm(),l=oa.useRef(a);oa.useEffect(()=>{l.current!==a&&(i.setFieldsValue(a),l.current=a)},[a,i]);const c=u=>{l.current={...l.current,...u},n(u)},d=()=>{r(),i.resetFields()};return t.jsxs("div",{style:{padding:"24px",maxWidth:"1200px",margin:"0 auto"},children:[t.jsx(hr,{level:3,style:{marginBottom:"8px"},children:e("settings.mermaidTab.title")}),t.jsx(zs,{type:"secondary",style:{display:"block",marginBottom:"24px"},children:e("settings.mermaidTab.description")}),t.jsxs(v,{form:i,layout:"vertical",initialValues:a,onValuesChange:c,children:[t.jsxs(z,{title:e("settings.mermaidTab.themeCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:[t.jsx(We,{gutter:16,children:t.jsx(le,{span:24,children:t.jsx(v.Item,{name:"theme",label:t.jsxs(A,{children:[e("settings.mermaidTab.themeLabel"),t.jsx(ve,{title:e("settings.mermaidTab.themeTooltip"),children:t.jsx(qe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsxs(Q,{children:[t.jsx(Q.Option,{value:"default",children:e("settings.mermaidTab.themeOptions.default")}),t.jsx(Q.Option,{value:"neutral",children:e("settings.mermaidTab.themeOptions.neutral")}),t.jsx(Q.Option,{value:"dark",children:e("settings.mermaidTab.themeOptions.dark")}),t.jsx(Q.Option,{value:"forest",children:e("settings.mermaidTab.themeOptions.forest")}),t.jsx(Q.Option,{value:"base",children:e("settings.mermaidTab.themeOptions.base")})]})})})}),t.jsxs(zs,{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(z,{title:e("settings.mermaidTab.globalCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:[t.jsxs(We,{gutter:16,children:[t.jsx(le,{span:12,children:t.jsx(v.Item,{name:"fontSize",label:t.jsxs(A,{children:[e("settings.mermaidTab.fontSizeLabel"),t.jsx(ve,{title:e("settings.mermaidTab.fontSizeTooltip"),children:t.jsx(qe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:10,max:32,step:1,style:{width:"100%"},addonAfter:"px"})})}),t.jsx(le,{span:12,children:t.jsx(v.Item,{name:"defaultScale",label:t.jsxs(A,{children:[e("settings.mermaidTab.defaultZoomLabel"),t.jsx(ve,{title:e("settings.mermaidTab.defaultZoomTooltip"),children:t.jsx(qe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:.1,max:3,step:.1,style:{width:"100%"}})})})]}),t.jsx(v.Item,{name:"useMaxWidth",label:t.jsxs(A,{children:[e("settings.mermaidTab.responsiveWidthLabel"),t.jsx(ve,{title:e("settings.mermaidTab.responsiveWidthTooltip"),children:t.jsx(qe,{style:{color:s.colorTextSecondary}})})]}),valuePropName:"checked",children:t.jsx(me,{})})]}),t.jsx(z,{title:e("settings.mermaidTab.flowchartCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsxs(We,{gutter:16,children:[t.jsx(le,{span:8,children:t.jsx(v.Item,{name:"flowchartNodeSpacing",label:t.jsxs(A,{children:[e("settings.mermaidTab.flowchartNodeSpacingLabel"),t.jsx(ve,{title:e("settings.mermaidTab.flowchartNodeSpacingTooltip"),children:t.jsx(qe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:20,max:200,step:10,style:{width:"100%"}})})}),t.jsx(le,{span:8,children:t.jsx(v.Item,{name:"flowchartRankSpacing",label:t.jsxs(A,{children:[e("settings.mermaidTab.flowchartRankSpacingLabel"),t.jsx(ve,{title:e("settings.mermaidTab.flowchartRankSpacingTooltip"),children:t.jsx(qe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:20,max:200,step:10,style:{width:"100%"}})})}),t.jsx(le,{span:8,children:t.jsx(v.Item,{name:"flowchartCurve",label:t.jsxs(A,{children:[e("settings.mermaidTab.flowchartCurveTypeLabel"),t.jsx(ve,{title:e("settings.mermaidTab.flowchartCurveTypeTooltip"),children:t.jsx(qe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsxs(Q,{children:[t.jsx(Q.Option,{value:"basis",children:e("settings.mermaidTab.flowchartCurveOptions.basis")}),t.jsx(Q.Option,{value:"linear",children:e("settings.mermaidTab.flowchartCurveOptions.linear")}),t.jsx(Q.Option,{value:"cardinal",children:e("settings.mermaidTab.flowchartCurveOptions.cardinal")})]})})})]})}),t.jsx(z,{title:e("settings.mermaidTab.sequenceCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsxs(We,{gutter:16,children:[t.jsx(le,{span:6,children:t.jsx(v.Item,{name:"sequenceActorMargin",label:t.jsxs(A,{children:[e("settings.mermaidTab.sequenceActorMarginLabel"),t.jsx(ve,{title:e("settings.mermaidTab.sequenceActorMarginTooltip"),children:t.jsx(qe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:20,max:200,step:10,style:{width:"100%"}})})}),t.jsx(le,{span:6,children:t.jsx(v.Item,{name:"sequenceMessageMargin",label:t.jsxs(A,{children:[e("settings.mermaidTab.sequenceMessageMarginLabel"),t.jsx(ve,{title:e("settings.mermaidTab.sequenceMessageMarginTooltip"),children:t.jsx(qe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:10,max:100,step:5,style:{width:"100%"}})})}),t.jsx(le,{span:6,children:t.jsx(v.Item,{name:"sequenceWidth",label:t.jsxs(A,{children:[e("settings.mermaidTab.sequenceActorWidthLabel"),t.jsx(ve,{title:e("settings.mermaidTab.sequenceActorWidthTooltip"),children:t.jsx(qe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:100,max:300,step:10,style:{width:"100%"}})})}),t.jsx(le,{span:6,children:t.jsx(v.Item,{name:"sequenceHeight",label:t.jsxs(A,{children:[e("settings.mermaidTab.sequenceActorHeightLabel"),t.jsx(ve,{title:e("settings.mermaidTab.sequenceActorHeightTooltip"),children:t.jsx(qe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:40,max:150,step:5,style:{width:"100%"}})})})]})}),t.jsx(z,{title:e("settings.mermaidTab.ganttCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsxs(We,{gutter:16,children:[t.jsx(le,{span:12,children:t.jsx(v.Item,{name:"ganttBarHeight",label:t.jsxs(A,{children:[e("settings.mermaidTab.ganttBarHeightLabel"),t.jsx(ve,{title:e("settings.mermaidTab.ganttBarHeightTooltip"),children:t.jsx(qe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:10,max:50,step:5,style:{width:"100%"},addonAfter:"px"})})}),t.jsx(le,{span:12,children:t.jsx(v.Item,{name:"ganttTopPadding",label:t.jsxs(A,{children:[e("settings.mermaidTab.ganttTopPaddingLabel"),t.jsx(ve,{title:e("settings.mermaidTab.ganttTopPaddingTooltip"),children:t.jsx(qe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(Me,{min:20,max:100,step:10,style:{width:"100%"}})})})]})}),t.jsx(A,{children:t.jsx(O,{icon:t.jsx(Rn,{}),onClick:d,children:e("settings.mermaidTab.resetToDefaults")})}),t.jsx(Re,{}),t.jsx(z,{title:e("settings.mermaidTab.previewTitle"),styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsx(zs,{type:"secondary",children:e("settings.mermaidTab.previewDescription")})})]})]})},xr=o.lazy(()=>Ys(()=>import("./index-BmrwviZb.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8]),import.meta.url)),{Text:bt}=ce,{useToken:br}=fe,vr=({promptEnhancement:e,onPromptEnhancementChange:s,mermaidEnhancementEnabled:a,taskEnhancementEnabled:n,showCopilotConclusionWithOptionsEnhancement:r,copilotConclusionWithOptionsEnhancementEnabled:i,onMermaidToggle:l,onTaskToggle:c,onCopilotConclusionWithOptionsToggle:d,onSaveEnhancement:u})=>{const{t:g}=te(),{token:j}=br(),h=j.marginLG;return t.jsxs(W,{vertical:!0,gap:h,children:[t.jsx(z,{size:"small",className:"lotus-settings-card",children:t.jsx(o.Suspense,{fallback:t.jsx(es,{size:"small"}),children:t.jsx(xr,{})})}),t.jsx(z,{size:"small",className:"lotus-settings-card",children:t.jsxs(A,{direction:"vertical",size:j.marginXS,style:{width:"100%"},children:[t.jsx(bt,{strong:!0,children:g("settings.promptsTab.title")}),t.jsxs(W,{align:"center",gap:j.marginSM,children:[t.jsx(bt,{strong:!0,children:g("settings.promptsTab.mermaidEnhancement")}),t.jsx(me,{checked:a,onChange:l})]}),t.jsxs(W,{align:"center",gap:j.marginSM,children:[t.jsx(bt,{strong:!0,children:g("settings.promptsTab.taskListRules")}),t.jsx(me,{checked:n,onChange:c})]}),r&&t.jsxs(A,{direction:"vertical",size:j.marginXXS,style:{width:"100%"},children:[t.jsxs(W,{align:"center",gap:j.marginSM,children:[t.jsx(bt,{strong:!0,children:g("settings.promptsTab.copilotConclusionWithOptionsBeforeFinish")}),t.jsx(me,{checked:i,onChange:d})]}),t.jsx(bt,{type:"secondary",style:{fontSize:j.fontSizeSM},children:g("settings.promptsTab.copilotConclusionWithOptionsBeforeFinishDescription",{defaultValue:bn()})})]}),t.jsx(H.TextArea,{rows:6,placeholder:g("settings.promptsTab.enhancementPlaceholder"),value:e,onChange:S=>s(S.target.value)}),t.jsx(W,{justify:"flex-end",children:t.jsx(O,{type:"primary",onClick:u,children:g("settings.promptsTab.saveEnhancement")})}),t.jsx(bt,{type:"secondary",style:{fontSize:j.fontSizeSM},children:g("settings.promptsTab.description")})]})}),a&&t.jsx(Ss,{size:"small",items:[{key:"mermaid",label:t.jsx(bt,{strong:!0,children:g("settings.mermaidTab.title")}),children:t.jsx(yr,{})}]})]})},{Text:gt}=ce,{useToken:Tr}=fe,jr=({themeMode:e,onThemeModeChange:s,vdiSafeMode:a,onVdiSafeModeToggle:n,onClearLocalStorage:r,onResetApp:i,isResetting:l,darkModeKey:c})=>{const{t:d}=te(),{token:u}=Tr();return t.jsx(z,{size:"small",className:"lotus-settings-card",children:t.jsxs(A,{direction:"vertical",size:u.marginSM,style:{width:"100%"},children:[t.jsxs(W,{align:"center",justify:"space-between",gap:u.marginSM,children:[t.jsx(gt,{strong:!0,children:d("settings.appTab.runningVersion","Running version")}),t.jsxs(gt,{code:!0,"data-testid":"settings-app-version",children:["v",Ga]})]}),t.jsx(gt,{type:"secondary",style:{fontSize:u.fontSizeSM},children:d("settings.appTab.runningVersionDesc","This is the currently running Lotus frontend version.")}),t.jsxs(W,{align:"center",gap:u.marginSM,children:[t.jsx(gt,{strong:!0,children:d("settings.appTab.darkMode")}),t.jsx(me,{"data-testid":"dark-mode-toggle",checked:e==="dark",onChange:g=>{const j=g?"dark":"light";s(j),localStorage.setItem(c,j)}})]}),t.jsxs(W,{align:"center",gap:u.marginSM,children:[t.jsx(gt,{strong:!0,children:d("settings.appTab.vdiSafeMode","Graphics compatibility mode")}),t.jsx(me,{"data-testid":"vdi-safe-mode-toggle",checked:a,onChange:n})]}),t.jsx(gt,{type:"secondary",style:{fontSize:u.fontSizeSM},children:d("settings.appTab.vdiSafeModeDesc","Disables blur and glass effects that can break dropdowns and hover overlays in some virtual desktop, remote, or graphics-constrained environments.")}),t.jsx(O,{block:!0,icon:t.jsx(zn,{}),onClick:()=>{Zn(),window.location.reload()},children:d("settings.appTab.resetStepReplayGuide")}),t.jsx(ts,{title:d("settings.appTab.clearLocalStorageTitle"),description:d("settings.appTab.clearLocalStorageDescription"),onConfirm:r,okText:d("settings.appTab.confirmClear"),cancelText:d("settings.appTab.cancel"),placement:"top",children:t.jsx(O,{danger:!0,block:!0,icon:t.jsx(ns,{}),children:d("settings.appTab.clearLocalStorageButton")})}),t.jsx(Re,{style:{margin:`${u.marginSM}px 0`}}),t.jsxs(W,{align:"center",gap:u.marginSM,children:[t.jsx(On,{style:{color:u.colorError}}),t.jsx(gt,{strong:!0,style:{color:u.colorError},children:d("settings.appTab.dangerZone")})]}),t.jsx(gt,{type:"secondary",style:{fontSize:u.fontSizeSM},children:d("settings.appTab.dangerDescription")}),t.jsx(ts,{title:d("settings.appTab.resetApplicationTitle"),description:t.jsxs("div",{children:[t.jsx("p",{children:d("settings.appTab.resetApplicationIntro")}),t.jsxs("ul",{style:{margin:0,paddingLeft:16},children:[t.jsx("li",{children:d("settings.appTab.resetStepDeleteAllSessions")}),t.jsx("li",{children:d("settings.appTab.resetStepClearStorage")}),t.jsx("li",{children:d("settings.appTab.resetStepResetConfig")}),t.jsx("li",{children:d("settings.appTab.resetStepSetupFlow")}),t.jsx("li",{children:d("settings.appTab.resetStepReload")})]})]}),onConfirm:i,okText:d("settings.appTab.resetConfirm"),cancelText:d("settings.appTab.cancel"),placement:"top",okButtonProps:{danger:!0},children:t.jsx(O,{"data-testid":"reset-to-defaults",danger:!0,block:!0,type:"primary",icon:t.jsx(Ln,{}),loading:l,children:d("settings.appTab.resetButton")})})]})})},{Text:vt}=ce,{useToken:Sr}=fe,va=[{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,}"}],_r=(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:ae.t("settings.keywordMaskingTab.invalidRegexPattern")}}},kr=()=>{const{t:e}=te(),{message:s}=Ft.useApp(),{token:a}=Sr(),[n,r]=o.useState([]),[i,l]=o.useState(!1),[c,d]=o.useState(null),[u,g]=o.useState(""),[j,h]=o.useState("exact"),[S,k]=o.useState(!0),[_,F]=o.useState(),[M,w]=o.useState("My token is sk-123"),D=o.useCallback(async()=>{try{l(!0);const E=await nt.getInstance().getKeywordMaskingConfig();r(E.entries)}catch(b){s.error(e("settings.keywordMaskingTab.loadFailed")),console.error(b)}finally{l(!1)}},[e]);o.useEffect(()=>{D()},[D]);const m=async b=>{try{const E=nt.getInstance(),I=await E.validateKeywordEntries(b);if(!I.valid&&I.errors){const B=I.errors.map(se=>`Entry ${se.index+1}: ${se.message}`).join("; ");return s.error(`${e("settings.keywordMaskingTab.validationFailedPrefix")}: ${B}`),!1}const R=await E.updateKeywordMaskingConfig(b);return r(R.entries),s.success(e("settings.keywordMaskingTab.saveSuccess")),!0}catch(E){return s.error(E instanceof Error?E.message:e("settings.keywordMaskingTab.saveFailed")),!1}},x=async()=>{const b={pattern:"",match_type:"exact",enabled:!0},E=[...n,b];r(E),d(E.length-1),g(""),h("exact"),k(!0),F(void 0)},L=b=>{const E=n[b];d(b),g(E.pattern),h(E.match_type),k(E.enabled),F(void 0)},P=async()=>{if(c===null)return;if(!u.trim()){s.error(e("settings.keywordMaskingTab.patternRequired"));return}const b=[...n];b[c]={pattern:u.trim(),match_type:j,enabled:S},await m(b)&&d(null)},K=()=>{var b;c!==null&&!((b=n[c])!=null&&b.pattern)&&r(n.filter((E,I)=>I!==c)),d(null)},Z=async b=>{const E=n.filter((I,R)=>R!==b);await m(E)},N=async(b,E)=>{const I=[...n];I[b]={...I[b],enabled:E},await m(I)},f=_r(M,u,j);return t.jsx(z,{className:"lotus-settings-card",title:e("settings.keywordMaskingTab.title"),extra:t.jsx(O,{"data-testid":"add-keyword",type:"primary",icon:t.jsx(Ct,{}),onClick:x,loading:i,children:e("settings.keywordMaskingTab.addKeyword")}),children:t.jsxs(A,{direction:"vertical",style:{width:"100%"},size:"large",children:[t.jsx(vt,{type:"secondary",children:e("settings.keywordMaskingTab.description")}),t.jsx(Qe,{loading:i,dataSource:n,locale:{emptyText:e("settings.keywordMaskingTab.empty")},renderItem:(b,E)=>t.jsx(Qe.Item,{style:{backgroundColor:a.colorFillAlter,marginBottom:8,borderRadius:a.borderRadius,padding:12},actions:c===E?[t.jsx(O,{"data-testid":"save-keyword",type:"primary",icon:t.jsx(_s,{}),onClick:P,"aria-label":e("settings.keywordMaskingTab.save")},"save"),t.jsx(O,{onClick:K,children:e("settings.keywordMaskingTab.cancel")},"cancel")]:[t.jsx(O,{icon:t.jsx(ks,{}),onClick:()=>L(E),"aria-label":e("settings.keywordMaskingTab.edit")},"edit"),t.jsx(O,{"data-testid":`delete-keyword-${E}`,danger:!0,icon:t.jsx(ns,{}),onClick:()=>Z(E),"aria-label":e("settings.keywordMaskingTab.delete")},"delete")],children:t.jsx(W,{vertical:!0,style:{width:"100%"},gap:8,children:c===E?t.jsxs(t.Fragment,{children:[t.jsx(H,{"data-testid":"keyword-pattern-input",placeholder:e("settings.keywordMaskingTab.patternPlaceholder"),value:u,onChange:I=>g(I.target.value),autoFocus:!0}),t.jsxs(W,{gap:8,align:"center",wrap:"wrap",children:[t.jsx(Q,{"data-testid":"keyword-examples-select","aria-label":e("settings.keywordMaskingTab.examples"),placeholder:e("settings.keywordMaskingTab.examples"),value:_,onChange:I=>{F(I);const R=va.find(B=>B.value===I);R&&(g(R.pattern),h(R.match_type))},options:va.map(I=>({value:I.value,label:e(I.labelKey)})),style:{minWidth:220}}),t.jsx(Q,{value:j,onChange:h,options:[{value:"exact",label:e("settings.keywordMaskingTab.exactMatch")},{value:"regex",label:e("settings.keywordMaskingTab.regexPattern")}],style:{width:150}}),t.jsx(me,{checked:S,onChange:k})]}),t.jsxs(W,{vertical:!0,gap:6,children:[t.jsx(vt,{type:"secondary",children:e("settings.keywordMaskingTab.sampleText")}),t.jsx(H,{placeholder:e("settings.keywordMaskingTab.sampleTextPlaceholder"),value:M,onChange:I=>w(I.target.value)}),t.jsx(vt,{type:"secondary",children:e("settings.keywordMaskingTab.maskedPreview")}),t.jsx(H,{readOnly:!0,value:f.masked,status:f.error?"error":void 0}),f.error&&t.jsx(vt,{type:"danger",children:f.error})]})]}):t.jsxs(W,{justify:"space-between",align:"center",children:[t.jsxs(W,{vertical:!0,gap:4,children:[t.jsx(vt,{strong:!0,children:b.pattern||e("settings.keywordMaskingTab.emptyPattern")}),t.jsxs(W,{gap:8,children:[t.jsx(vt,{type:"secondary",style:{fontSize:12},children:b.match_type==="regex"?e("settings.keywordMaskingTab.regexPattern"):e("settings.keywordMaskingTab.exactMatch")}),!b.enabled&&t.jsx(vt,{type:"warning",style:{fontSize:12},children:e("settings.keywordMaskingTab.disabled")})]})]}),t.jsx(me,{checked:b.enabled,onChange:I=>N(E,I),size:"small"})]})})})})]})})},{Text:Mt,Paragraph:wr}=ce,Cr=/^[A-Za-z_][A-Za-z0-9_]*$/,Mr=()=>{const{t:e}=te(),{message:s}=Ft.useApp(),[a,n]=o.useState([]),[r,i]=o.useState(!1),[l,c]=o.useState(!1),[d,u]=o.useState(null),[g]=v.useForm(),j=o.useCallback(async()=>{i(!0);try{const w=await Te.getEnvVars();n(w.entries)}catch{s.error(e("settings.envVars.fetchError","Failed to load environment variables"))}finally{i(!1)}},[e]);o.useEffect(()=>{j()},[j]);const h=async w=>{var m;const D={name:w.name.trim(),value:w.value,secret:w.secret??!1,description:((m=w.description)==null?void 0:m.trim())||void 0};try{const x=await Te.upsertEnvVar(D);n(x.entries),s.success(d?e("settings.envVars.updated","Variable updated"):e("settings.envVars.created","Variable created")),F()}catch(x){s.error((x instanceof Error?x.message:void 0)||e("settings.envVars.saveError","Failed to save variable"))}},S=async w=>{try{const D=await Te.deleteEnvVar(w);n(D.entries),s.success(e("settings.envVars.deleted","Variable deleted"))}catch(D){s.error((D instanceof Error?D.message:void 0)||e("settings.envVars.deleteError","Failed to delete variable"))}},k=()=>{u(null),g.resetFields(),g.setFieldsValue({secret:!1}),c(!0)},_=w=>{u(w.name),g.setFieldsValue({name:w.name,value:"",secret:w.secret,description:w.description??""}),c(!0)},F=()=>{c(!1),u(null),g.resetFields()},M=[{title:e("settings.envVars.name","Name"),dataIndex:"name",key:"name",render:w=>t.jsx(Mt,{code:!0,children:w})},{title:e("settings.envVars.value","Value"),dataIndex:"value",key:"value",render:(w,D)=>D.secret?t.jsxs(Mt,{type:"secondary",children:[t.jsx(ha,{style:{marginRight:4}}),D.has_value?"••••••••":e("settings.envVars.notSet","(not set)")]}):t.jsx(Mt,{children:w||t.jsx(Mt,{type:"secondary",children:e("settings.envVars.empty","(empty)")})})},{title:e("settings.envVars.type","Type"),key:"secret",width:100,render:(w,D)=>D.secret?t.jsx(re,{color:"warning",icon:t.jsx(ha,{}),children:e("settings.envVars.secret","Secret")}):t.jsx(re,{color:"processing",children:e("settings.envVars.plain","Plain")})},{title:e("settings.envVars.descriptionCol","Description"),dataIndex:"description",key:"description",ellipsis:!0,render:w=>w?t.jsx(Mt,{type:"secondary",children:w}):t.jsx(Mt,{type:"secondary",italic:!0,children:"—"})},{title:e("settings.envVars.actions","Actions"),key:"actions",width:120,render:(w,D)=>t.jsxs(A,{size:"small",children:[t.jsx(O,{type:"text",size:"small",icon:t.jsx(ks,{}),onClick:()=>_(D),"aria-label":e("settings.envVars.edit","Edit")}),t.jsx(ts,{title:e("settings.envVars.deleteConfirm","Delete this variable?"),onConfirm:()=>S(D.name),okText:e("settings.envVars.yes","Yes"),cancelText:e("settings.envVars.no","No"),children:t.jsx(O,{type:"text",size:"small",danger:!0,icon:t.jsx(ns,{}),"aria-label":e("settings.envVars.delete","Delete")})})]})}];return t.jsxs("div",{style:{maxWidth:900},children:[t.jsxs(z,{className:"lotus-settings-card",title:e("settings.envVars.title","Environment Variables"),extra:t.jsx(O,{type:"primary",icon:t.jsx(Ct,{}),onClick:k,children:e("settings.envVars.addButton","Add Variable")}),children:[t.jsx(wr,{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(ct,{dataSource:a,columns:M,rowKey:"name",size:"small",pagination:!1,loading:r,locale:{emptyText:e("settings.envVars.noVars","No environment variables configured")}})]}),t.jsx(lt,{title:d?e("settings.envVars.editTitle","Edit Variable"):e("settings.envVars.addTitle","Add Environment Variable"),open:l,onCancel:F,onOk:()=>g.submit(),okText:e("settings.envVars.save","Save"),cancelText:e("settings.envVars.cancel","Cancel"),destroyOnClose:!0,children:t.jsxs(v,{form:g,layout:"vertical",onFinish:h,initialValues:{secret:!1},children:[t.jsx(v.Item,{name:"name",label:e("settings.envVars.name","Name"),rules:[{required:!0,message:e("settings.envVars.nameRequired","Variable name is required")},{pattern:Cr,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:d!==null,autoFocus:d===null})}),t.jsx(v.Item,{name:"value",label:e("settings.envVars.value","Value"),rules:[{required:d===null,message:e("settings.envVars.valueRequired","Value is required for new variables")}],extra:d?e("settings.envVars.valueEditHint","Leave empty to keep the existing value"):void 0,children:t.jsx(H.Password,{placeholder:d?e("settings.envVars.valuePlaceholderEdit","Enter new value or leave empty"):e("settings.envVars.valuePlaceholder","Enter value"),visibilityToggle:!0})}),t.jsx(v.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(me,{})}),t.jsx(v.Item,{name:"description",label:e("settings.envVars.descriptionField","Description"),children:t.jsx(H,{placeholder:e("settings.envVars.descriptionPlaceholder","Optional description")})})]})})]})},kt=class kt{constructor(){}static getInstance(){return kt.instance||(kt.instance=new kt),kt.instance}async listWorkflows(){try{ot("[WorkflowManager]","[WorkflowManagerService] Listing workflows");const s=await la.get("bamboo/workflows"),a=Array.isArray(s)?s:[];return ot("[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{ot("[WorkflowManager]","[WorkflowManagerService] Getting workflow: "+s);const a=await la.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 ot("[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),sr(a)&&a.status===404?new Error("Workflow '"+s+"' not found"):a instanceof Error&&a.message.includes("404")?new Error("Workflow '"+s+"' not found"):a}}};ia(kt,"instance");let Zs=kt;const{Text:Os}=ce,{TextArea:Er}=H,{useToken:Dr}=fe,Pr=e=>!(!e||e.includes("/")||e.includes("\\")||e.includes("..")),Ir=()=>{const{t:e}=te(),{token:s}=Dr(),[a,n]=At.useMessage(),[r,i]=o.useState([]),[l,c]=o.useState(!1),[d,u]=o.useState(!1),[g,j]=o.useState(!1),[h,S]=o.useState(null),[k,_]=o.useState(""),[F,M]=o.useState(""),[w,D]=o.useState(!1),m=o.useMemo(()=>Zs.getInstance(),[]),x=o.useCallback(async()=>{c(!0);try{const N=await m.listWorkflows();return i(N),N}catch{return a.error(e("settings.workflowsTab.loadFailed")),[]}finally{c(!1)}},[a,e,m]);o.useEffect(()=>{x()},[x]);const L=o.useCallback(async N=>{S(N),_(N.name),D(!1),u(!0);try{const f=await m.getWorkflow(N.name);M(f.content??"")}catch{a.error(e("settings.workflowsTab.loadContentFailed")),M("")}finally{u(!1)}},[a,e,m]),P=()=>{S(null),_(""),M(""),D(!1)},K=o.useCallback(async()=>{if(!Pr(k)){a.error(e("settings.workflowsTab.invalidName"));return}const N=r.some(f=>f.name===k);if(!h&&N){a.error(e("settings.workflowsTab.nameAlreadyExists"));return}j(!0);try{await nt.getInstance().saveWorkflow(k,F),a.success(e("settings.workflowsTab.saved")),D(!1);const E=(await x()).find(I=>I.name===k);E&&S(E)}catch(f){a.error(f instanceof Error?f.message:e("settings.workflowsTab.saveFailed"))}finally{j(!1)}},[F,k,x,a,h,e,r]),Z=o.useCallback(async N=>{try{await nt.getInstance().deleteWorkflow(N.name),a.success(e("settings.workflowsTab.deleted")),(h==null?void 0:h.name)===N.name&&P(),await x()}catch(f){a.error(f instanceof Error?f.message:e("settings.workflowsTab.deleteFailed"))}},[x,a,h,e]);return t.jsxs("div",{style:{padding:"24px"},children:[n,t.jsxs(z,{title:e("settings.workflowsTab.title"),extra:t.jsxs(A,{children:[t.jsx(O,{icon:t.jsx(Rt,{}),onClick:x,loading:l,children:e("settings.workflowsTab.refresh")}),t.jsx(O,{"data-testid":"create-workflow",icon:t.jsx(Ct,{}),onClick:P,children:e("settings.workflowsTab.newWorkflow")}),t.jsx(O,{"data-testid":"save-workflow",type:"primary",icon:t.jsx(_s,{}),onClick:K,loading:g,disabled:!w,children:e("settings.workflowsTab.save")})]}),children:[t.jsx(Os,{type:"secondary",children:e("settings.workflowsTab.description")}),t.jsxs(W,{gap:s.marginLG,style:{marginTop:s.marginLG},children:[t.jsx("div",{style:{width:320,flexShrink:0},children:t.jsx(Qe,{loading:l,dataSource:r,locale:{emptyText:e("settings.workflowsTab.empty")},renderItem:N=>t.jsx(Qe.Item,{style:{cursor:"pointer",backgroundColor:(h==null?void 0:h.name)===N.name?s.colorFillSecondary:"transparent",borderRadius:s.borderRadius,padding:s.paddingSM},onClick:()=>L(N),actions:[t.jsx(O,{"data-testid":`delete-workflow-${N.name}`,type:"text",danger:!0,size:"small",icon:t.jsx(ns,{}),onClick:f=>{f.stopPropagation(),Z(N)},"aria-label":e("settings.workflowsTab.delete")},"delete")],children:t.jsxs(A,{direction:"vertical",size:0,children:[t.jsxs(Os,{strong:!0,children:["/",N.name]}),t.jsx(Os,{type:"secondary",style:{fontSize:12},children:N.filename})]})})})}),t.jsx("div",{style:{flex:1},children:t.jsxs(A,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(H,{"data-testid":"workflow-name",placeholder:e("settings.workflowsTab.namePlaceholder"),value:k,onChange:N=>{_(N.target.value),D(!0)},disabled:!!h,prefix:t.jsx(ks,{})}),t.jsx(Er,{"data-testid":"workflow-content",placeholder:e("settings.workflowsTab.contentPlaceholder"),value:F,onChange:N=>{M(N.target.value),D(!0)},autoSize:{minRows:12},disabled:d})]})})]})]})]})};var q=(e=>(e.Connecting="connecting",e.Ready="ready",e.Degraded="degraded",e.Stopped="stopped",e.Error="error",e))(q||{});const ls=6e4,cs=3e4,ss=2e4,js=1e4,ws=e=>({id:e,enabled:!0,transport:{type:"stdio",command:"",args:[],env:{},startup_timeout_ms:ss},request_timeout_ms:ls,healthcheck_interval_ms:cs,allowed_tools:[],denied_tools:[]}),Fr=()=>({status:"stopped",tool_count:0,restart_count:0}),Ar=e=>{switch(typeof e=="string"?e.trim().toLowerCase():""){case q.Connecting:return q.Connecting;case q.Ready:return q.Ready;case q.Degraded:return q.Degraded;case q.Error:return q.Error;case q.Stopped:default:return q.Stopped}},rt=(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},Rr=(e,s)=>{if(!e||typeof e!="object")return s;const a=e;if(a.type==="sse"){const i=Array.isArray(a.headers)?a.headers.map(l=>{if(!l||typeof l!="object")return null;const c=l;return typeof c.name!="string"||typeof c.value!="string"?null:{name:c.name,value:c.value}}).filter(l=>!!l):[];return{type:"sse",url:typeof a.url=="string"?a.url:"",headers:i,connect_timeout_ms:rt(a.connect_timeout_ms,js)}}const n=Array.isArray(a.args)?a.args.filter(i=>typeof i=="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((i,[l,c])=>(typeof c=="string"&&(i[l]=c),i),{}),startup_timeout_ms:rt(a.startup_timeout_ms,ss)}},zr=(e,s)=>{const a=ws(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:rt(n.request_timeout_ms,ls),healthcheck_interval_ms:rt(n.healthcheck_interval_ms,cs),allowed_tools:Array.isArray(n.allowed_tools)?n.allowed_tools.filter(i=>typeof i=="string"):[],denied_tools:Array.isArray(n.denied_tools)?n.denied_tools.filter(i=>typeof i=="string"):[],reconnect:n.reconnect&&typeof n.reconnect=="object"?{enabled:typeof n.reconnect.enabled=="boolean"?n.reconnect.enabled:!0,initial_backoff_ms:rt(n.reconnect.initial_backoff_ms,1e3),max_backoff_ms:rt(n.reconnect.max_backoff_ms,3e4),max_attempts:rt(n.reconnect.max_attempts,0)}:void 0,transport:Rr(n.transport,a.transport)}},Or=e=>{const s=Fr(),n=e.runtime??{},r=n.status??e.status;return{status:Ar(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:rt(n.tool_count??e.tool_count,s.tool_count),restart_count:rt(n.restart_count??e.restart_count,s.restart_count),last_ping_at:typeof n.last_ping_at=="string"?n.last_ping_at:void 0}},Lr=e=>{const s=zr(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:Or(e)}},Nr=(e,s)=>`mcp__${e}__${s}`,Vr=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}},$r=(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,i=r&&typeof r=="string"?Vr(r):null,l=(typeof n.server_id=="string"?n.server_id:void 0)??(typeof n.serverId=="string"?n.serverId:void 0)??(i==null?void 0:i.server_id)??s??"",c=(typeof n.original_name=="string"?n.original_name:void 0)??(typeof n.originalName=="string"?n.originalName:void 0)??(i==null?void 0:i.original_name)??(typeof n.name=="string"?n.name:void 0)??"",d=r??(l&&c?Nr(l,c):""),u=typeof n.description=="string"?n.description:"",g=n,j="parameters"in g?g.parameters:"inputSchema"in g?g.inputSchema:"input_schema"in g?g.input_schema:void 0,h=d||c||`mcp_tool_${a}`;return{alias:h,server_id:l||"unknown",original_name:c||h,description:u,parameters:j}};class Br{async getServers(){const s=await et.get("mcp/servers");return Array.isArray(s.servers)?s.servers.map(Lr):[]}async addServer(s){return et.post("mcp/servers",s)}async updateServer(s,a){const n={...a,id:s};return et.put(`mcp/servers/${s}`,n)}async deleteServer(s){return et.delete(`mcp/servers/${s}`)}async connectServer(s){return et.post(`mcp/servers/${s}/connect`)}async disconnectServer(s){return et.post(`mcp/servers/${s}/disconnect`)}async refreshTools(s){return et.post(`mcp/servers/${s}/refresh`)}async getTools(s){const a=s?`mcp/servers/${s}/tools`:"mcp/tools",n=await et.get(a);return(Array.isArray(n.tools)?n.tools:[]).map((i,l)=>$r(i,s,l)).filter(i=>!!i)}async importServers(s){return et.post("mcp/servers/import",s)}}const en=new Br,qr=5e3,tt=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,Ta=(e,s)=>`${e}:${s}`,Ur=(e={})=>{const{service:s=en,autoRefreshMs:a=qr,autoRefreshEnabled:n=!0}=e,[r,i]=o.useState([]),[l,c]=o.useState(null),[d,u]=o.useState({}),[g,j]=o.useState({}),[h,S]=o.useState({}),[k,_]=o.useState(!1),[F,M]=o.useState(!1),[w,D]=o.useState(!1),[m,x]=o.useState(null),L=o.useRef({}),P=o.useCallback(C=>{const J=new Set(C.map(ee=>ee.id)),Y=C.map(ee=>{const Pe=L.current[ee.id]??ee.config,Be={...Pe,id:ee.id,name:Pe.name??ee.name};return L.current[ee.id]=Be,{...ee,name:ee.name||Be.name||ee.id,enabled:ee.enabled??Be.enabled,config:Be}});return Object.keys(L.current).forEach(ee=>{J.has(ee)||delete L.current[ee]}),Y},[]),K=o.useCallback(async({silent:C=!1}={})=>{C||_(!0);try{const J=await s.getServers(),Y=P(J);i(Y),c(ee=>{var De;return ee&&Y.some(Pe=>Pe.id===ee)?ee:((De=Y[0])==null?void 0:De.id)??null}),x(null)}catch(J){throw x(tt(J,"Failed to load MCP servers")),J}finally{C||_(!1)}},[P,s]),Z=o.useCallback(async(C,J=!1)=>{if(!C)return[];if(!J&&d[C])return d[C];j(Y=>({...Y,[C]:!0}));try{const Y=await s.getTools(C);return u(ee=>({...ee,[C]:Y})),x(null),Y}catch(Y){throw x(tt(Y,"Failed to load MCP tools")),Y}finally{j(Y=>({...Y,[C]:!1}))}},[s,d]),N=o.useCallback((C,J,Y)=>{const ee=Ta(C,J);S(De=>({...De,[ee]:Y}))},[]),f=o.useCallback(async C=>{M(!0);try{await s.addServer(C),L.current[C.id]=C,await K()}catch(J){throw x(tt(J,"Failed to add MCP server")),J}finally{M(!1)}},[K,s]),b=o.useCallback(async(C,J)=>{M(!0);try{const Y={...J,id:C};await s.updateServer(C,Y),L.current[C]=Y,await K()}catch(Y){throw x(tt(Y,"Failed to update MCP server")),Y}finally{M(!1)}},[K,s]),E=o.useCallback(async C=>{N(C,"delete",!0);try{await s.deleteServer(C),u(J=>{const Y={...J};return delete Y[C],Y}),delete L.current[C],await K()}catch(J){throw x(tt(J,"Failed to delete MCP server")),J}finally{N(C,"delete",!1)}},[K,s,N]),I=o.useCallback(async C=>{N(C,"connect",!0);try{await s.connectServer(C),await K({silent:!0})}catch(J){throw x(tt(J,"Failed to connect MCP server")),J}finally{N(C,"connect",!1)}},[K,s,N]),R=o.useCallback(async C=>{N(C,"disconnect",!0);try{await s.disconnectServer(C),await K({silent:!0})}catch(J){throw x(tt(J,"Failed to disconnect MCP server")),J}finally{N(C,"disconnect",!1)}},[K,s,N]),B=o.useCallback(async C=>{N(C,"refresh",!0);try{await s.refreshTools(C),await Z(C,!0),await K({silent:!0})}catch(J){throw x(tt(J,"Failed to refresh MCP tools")),J}finally{N(C,"refresh",!1)}},[Z,K,s,N]),se=o.useCallback(async()=>{D(!0);try{const C=r.map(J=>J.id);await Promise.all(C.map(async J=>{try{await s.refreshTools(J)}catch{}})),await K(),l&&await Z(l,!0)}catch(C){throw x(tt(C,"Failed to refresh MCP status")),C}finally{D(!1)}},[Z,K,l,r,s]),G=o.useCallback(C=>{c(C)},[]),ge=o.useCallback((C,J)=>!!h[Ta(C,J)],[h]),he=o.useMemo(()=>l?d[l]??[]:[],[l,d]),Ee=o.useMemo(()=>l?!!g[l]:!1,[l,g]);return o.useEffect(()=>{K().catch(()=>{})},[K]),o.useEffect(()=>{if(!n||a<=0)return;const C=window.setInterval(()=>{K({silent:!0}).catch(()=>{})},a);return()=>{window.clearInterval(C)}},[n,a,K]),o.useEffect(()=>{l&&Z(l).catch(()=>{})},[Z,l]),{servers:r,selectedServerId:l,selectedServerTools:he,isLoadingServers:k,isMutatingConfig:F,isRefreshingAll:w,isSelectedServerToolsLoading:Ee,error:m,setSelectedServerId:G,refreshServers:K,addServer:f,updateServer:b,deleteServer:E,connectServer:I,disconnectServer:R,refreshServerTools:B,refreshAll:se,isServerActionLoading:ge}},Hr={[q.Connecting]:"blue",[q.Ready]:"green",[q.Degraded]:"orange",[q.Stopped]:"default",[q.Error]:"red"},Kr=e=>e===q.Connecting||e===q.Ready||e===q.Degraded,Wr=e=>{if(!e)return;const s=e.replace(/\s+/g," ").trim();if(s)return s.length>180?`${s.slice(0,180)}...`:s},Gr=({servers:e,loading:s=!1,selectedServerId:a,onSelectServer:n,onEditServer:r,onDeleteServer:i,onConnectServer:l,onDisconnectServer:c,onRefreshTools:d,isServerActionLoading:u})=>{const{t:g}=te(),{token:j}=fe.useToken(),h=o.useMemo(()=>({[q.Connecting]:g("settings.mcpTab.statusHelp.connecting"),[q.Ready]:g("settings.mcpTab.statusHelp.ready"),[q.Degraded]:g("settings.mcpTab.statusHelp.degraded"),[q.Stopped]:g("settings.mcpTab.statusHelp.stopped"),[q.Error]:g("settings.mcpTab.statusHelp.error")}),[g]),S=o.useMemo(()=>[{key:"name",title:g("settings.mcpServerTable.columns.name"),render:(k,_)=>_.name||_.id},{key:"transport",title:g("settings.mcpServerTable.columns.transportType"),render:(k,_)=>_.config.transport.type==="sse"?g("settings.mcpServerTable.transportOptions.sse"):g("settings.mcpServerTable.transportOptions.stdio"),width:140},{key:"status",title:g("settings.mcpServerTable.columns.status"),render:(k,_)=>{var m,x;const F=((m=_.runtime)==null?void 0:m.status)??q.Stopped,M=Wr((x=_.runtime)==null?void 0:x.last_error),w=h[F],D={[q.Connecting]:g("settings.mcpTab.status.connecting"),[q.Ready]:g("settings.mcpTab.status.ready"),[q.Degraded]:g("settings.mcpTab.status.degraded"),[q.Stopped]:g("settings.mcpTab.status.stopped"),[q.Error]:g("settings.mcpTab.status.error")};return t.jsx(ve,{title:M?`${w} ${g("settings.mcpTab.statusLastError",{error:M})}`:w,children:t.jsx(re,{color:F===q.Stopped?void 0:Hr[F],style:{marginInlineEnd:0,cursor:"help",...F===q.Stopped?{background:j.colorFillSecondary,borderColor:j.colorBorderSecondary,color:j.colorTextSecondary}:void 0},children:D[F]})})},width:120},{key:"toolCount",title:g("settings.mcpServerTable.columns.toolCount"),render:(k,_)=>{var F;return((F=_.runtime)==null?void 0:F.tool_count)??0},width:100},{key:"actions",title:g("settings.mcpServerTable.columns.actions"),width:360,render:(k,_)=>{var w;const F=((w=_.runtime)==null?void 0:w.status)??q.Stopped,M=Kr(F);return t.jsxs(A,{size:j.marginXS,children:[t.jsx(O,{size:"small",onClick:D=>{D.stopPropagation(),r==null||r(_)},children:g("settings.mcpServerTable.actions.edit")}),t.jsx(ts,{title:g("settings.mcpServerTable.deleteTitle"),description:g("settings.mcpServerTable.deleteDescription",{name:_.name||_.id}),onConfirm:()=>i==null?void 0:i(_),okText:g("settings.mcpServerTable.actions.delete"),okButtonProps:{danger:!0,loading:u==null?void 0:u(_.id,"delete")},children:t.jsx(O,{size:"small",danger:!0,loading:u==null?void 0:u(_.id,"delete"),onClick:D=>D.stopPropagation(),children:g("settings.mcpServerTable.actions.delete")})}),M?t.jsx(O,{size:"small",onClick:D=>{D.stopPropagation(),c==null||c(_)},loading:u==null?void 0:u(_.id,"disconnect"),children:g("settings.mcpServerTable.actions.disconnect")}):t.jsx(O,{size:"small",type:"primary",ghost:!0,onClick:D=>{D.stopPropagation(),l==null||l(_)},loading:u==null?void 0:u(_.id,"connect"),children:g("settings.mcpServerTable.actions.connect")}),t.jsx(O,{size:"small",onClick:D=>{D.stopPropagation(),d==null||d(_)},loading:u==null?void 0:u(_.id,"refresh"),children:g("settings.mcpServerTable.actions.refreshTools")})]})}}],[u,l,i,c,r,d,h,g,j.colorBorderSecondary,j.colorFillSecondary,j.colorTextSecondary,j.marginXS]);return t.jsx(ct,{rowKey:"id",columns:S,dataSource:e,loading:s,pagination:!1,locale:{emptyText:g("settings.mcpServerTable.empty")},onRow:k=>({onClick:()=>n==null?void 0:n(k.id),style:{cursor:n?"pointer":"default",backgroundColor:a===k.id?j.colorFillSecondary:void 0}})})},{Text:ja}=ce,{TextArea:Jr}=H,Sa=e=>{const s=e??ws(""),a=s.transport,n=a.type==="stdio"?Object.entries(a.env??{}).map(([i,l])=>({key:i,value:l})):[],r=a.type==="sse"?a.headers.map(i=>({name:i.name,value:i.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||ls,healthcheckIntervalMs:s.healthcheck_interval_ms||cs,allowedTools:s.allowed_tools||[],deniedTools:s.denied_tools||[]}},Xr=e=>e.reduce((s,a)=>{var r;const n=(r=a.key)==null?void 0:r.trim();return n&&(s[n]=a.value??""),s},{}),Yr=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??""}}),_a=(e,s,a)=>{var g,j,h;const n=s==="edit"&&(a==null?void 0:a.id)||e.id,r=(g=e.name)==null?void 0:g.trim(),i=typeof e.requestTimeoutMs=="number"?e.requestTimeoutMs:(a==null?void 0:a.request_timeout_ms)??ls,l=typeof e.healthcheckIntervalMs=="number"?e.healthcheckIntervalMs:(a==null?void 0:a.healthcheck_interval_ms)??cs,c=Array.isArray(e.allowedTools)?e.allowedTools:(a==null?void 0:a.allowed_tools)??[],d=Array.isArray(e.deniedTools)?e.deniedTools:(a==null?void 0:a.denied_tools)??[],u=e.transportType==="sse"?{type:"sse",url:((j=e.url)==null?void 0:j.trim())||"",headers:Yr(e.headerEntries||[]),connect_timeout_ms:(a==null?void 0:a.transport.type)==="sse"?a.transport.connect_timeout_ms??js:js}:{type:"stdio",command:((h=e.command)==null?void 0:h.trim())||"",args:e.args||[],env:Xr(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??ss:ss};return{id:n,name:r||void 0,enabled:e.enabled,transport:u,request_timeout_ms:i,healthcheck_interval_ms:l,allowed_tools:c,denied_tools:d,reconnect:a==null?void 0:a.reconnect}},ka=e=>JSON.stringify(e||ws(""),null,2),Ls=(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 j=n;return!j.transport||typeof j.transport!="object"?{valid:!1,error:s("settings.mcpServerForm.missingTransportField")}:{valid:!0,config:j}}const i=typeof n.enabled=="boolean"?n.enabled:typeof n.disabled=="boolean"?!n.disabled:!0,l=typeof n.request_timeout_ms=="number"?n.request_timeout_ms:ls,c=typeof n.healthcheck_interval_ms=="number"?n.healthcheck_interval_ms:cs,d=Array.isArray(n.allowed_tools)?n.allowed_tools.filter(j=>typeof j=="string"):[],u=Array.isArray(n.denied_tools)?n.denied_tools.filter(j=>typeof j=="string"):[],g=typeof n.name=="string"?n.name:void 0;if(typeof n.url=="string"){const j=n.headers,h=Array.isArray(j)?j.map(k=>{if(!k||typeof k!="object")return null;const _=k,F=typeof _.name=="string"?_.name:"",M=typeof _.value=="string"?_.value:"";return F.trim()?{name:F,value:M}:null}).filter(k=>!!k):j&&typeof j=="object"?Object.entries(j).filter(([k])=>k.trim()).map(([k,_])=>({name:k,value:typeof _=="string"?_:""})):[],S=typeof n.connect_timeout_ms=="number"?n.connect_timeout_ms:js;return{valid:!0,config:{id:r,name:g,enabled:i,transport:{type:"sse",url:n.url,headers:h,connect_timeout_ms:S},request_timeout_ms:l,healthcheck_interval_ms:c,allowed_tools:d,denied_tools:u,reconnect:void 0}}}if(typeof n.command=="string"){const j=Array.isArray(n.args)?n.args.filter(_=>typeof _=="string"):[],h=n.env,S=h&&typeof h=="object"?Object.entries(h).reduce((_,[F,M])=>(typeof M=="string"&&(_[F]=M),_),{}):{},k=typeof n.startup_timeout_ms=="number"?n.startup_timeout_ms:ss;return{valid:!0,config:{id:r,name:g,enabled:i,transport:{type:"stdio",command:n.command,args:j,cwd:typeof n.cwd=="string"?n.cwd:void 0,env:S,startup_timeout_ms:k},request_timeout_ms:l,healthcheck_interval_ms:c,allowed_tools:d,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")})}}},Zr=({open:e,mode:s,initialConfig:a,confirmLoading:n=!1,onCancel:r,onSubmit:i})=>{const{t:l}=te(),[c]=v.useForm(),[d,u]=o.useState("form"),[g,j]=o.useState(""),[h,S]=o.useState(null),k=o.useMemo(()=>Sa(a),[a]),_=v.useWatch("transportType",c)??"stdio";o.useEffect(()=>{e&&(c.setFieldsValue(k),j(ka(a)),S(null),u("form"))},[c,k,a,e]);const F=()=>{c.resetFields(),j(""),S(null),r()},M=async()=>{if(d==="json"){const m=Ls(g,l);if(!m.valid){S(m.error);return}S(null);try{await i(m.config),j("")}catch(x){console.error("MCP server JSON submission error:",x)}return}try{const m=await c.validateFields(),x=_a(m,s,a);await i(x),c.resetFields()}catch(m){console.error("MCP server form submission error:",m)}},w=m=>{j(m),h&&Ls(m,l).valid&&S(null)},D=m=>{if(m==="json")try{const x=c.getFieldsValue(),L=_a(x,s,a);j(JSON.stringify(L,null,2))}catch{j(ka(a))}else{const x=Ls(g,l);x.valid&&c.setFieldsValue(Sa(x.config))}u(m),S(null)};return t.jsxs(lt,{title:l(s==="edit"?"settings.mcpServerForm.editTitle":"settings.mcpServerForm.addTitle"),open:e,onCancel:F,onOk:()=>{M()},okText:l("settings.mcpServerForm.save"),destroyOnClose:!0,forceRender:!0,confirmLoading:n,width:720,children:[t.jsx("div",{style:{marginBottom:16},children:t.jsxs(Pt.Group,{value:d,onChange:m=>D(m.target.value),optionType:"button",buttonStyle:"solid",children:[t.jsxs(Pt.Button,{value:"form",children:[t.jsx(Nn,{})," ",l("settings.mcpServerForm.modeForm")]}),t.jsxs(Pt.Button,{value:"json",children:[t.jsx(Vn,{})," ",l("settings.mcpServerForm.modeJson")]})]})}),d==="json"&&h&&t.jsx(Ve,{type:"error",message:l("settings.mcpServerForm.jsonError"),description:h,showIcon:!0,style:{marginBottom:16},closable:!0,onClose:()=>S(null)}),d==="json"?t.jsx(Jr,{value:g,onChange:m=>w(m.target.value),rows:20,style:{fontFamily:"monospace",fontSize:13},placeholder:JSON.stringify(ws("example-server"),null,2)}):t.jsxs(v,{layout:"vertical",form:c,preserve:!0,initialValues:k,children:[t.jsx(v.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(v.Item,{name:"name",label:l("settings.mcpServerForm.displayName"),children:t.jsx(H,{placeholder:"Filesystem MCP",autoComplete:"off"})}),t.jsx(v.Item,{name:"enabled",label:l("settings.mcpServerForm.enabled"),valuePropName:"checked",extra:l("settings.mcpServerForm.enabledHelp"),children:t.jsx(me,{})}),t.jsx(v.Item,{name:"transportType",label:l("settings.mcpServerForm.transportType"),rules:[{required:!0,message:l("settings.mcpServerForm.transportTypeRequired")}],children:t.jsx(Q,{options:[{label:l("settings.mcpServerForm.transportOptions.stdio"),value:"stdio"},{label:l("settings.mcpServerForm.transportOptions.sse"),value:"sse"}]})}),_==="stdio"?t.jsxs(t.Fragment,{children:[t.jsx(v.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(v.Item,{name:"args",label:l("settings.mcpServerForm.arguments"),children:t.jsx(Q,{mode:"tags",tokenSeparators:[","],placeholder:l("settings.mcpServerForm.argumentsPlaceholder"),open:!1})}),t.jsx(v.List,{name:"envEntries",children:(m,{add:x,remove:L})=>t.jsxs(A,{direction:"vertical",style:{width:"100%"},children:[t.jsxs(A,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[t.jsx(ja,{strong:!0,children:l("settings.mcpServerForm.envVars")}),t.jsx(O,{icon:t.jsx(Ct,{}),onClick:()=>x({key:"",value:""}),type:"dashed",children:l("settings.mcpServerForm.addEnv")})]}),m.map(P=>t.jsxs(A,{align:"baseline",style:{display:"flex"},children:[t.jsx(v.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(v.Item,{...P,name:[P.name,"value"],children:t.jsx(H,{placeholder:"/Users/me/workspace",autoComplete:"off"})}),t.jsx(O,{danger:!0,type:"text",icon:t.jsx(fa,{}),onClick:()=>L(P.name),"aria-label":l("settings.mcpServerForm.removeEnv","Remove environment variable")})]},P.key))]})})]}):t.jsxs(t.Fragment,{children:[t.jsx(v.Item,{name:"url",label:l("settings.mcpServerForm.sseUrl"),rules:[{required:!0,message:l("settings.mcpServerForm.sseUrlRequired")},{validator:async(m,x)=>{if(x)try{new URL(x)}catch{throw new Error(l("settings.mcpServerForm.validUrlRequired"))}}}],children:t.jsx(H,{placeholder:"http://localhost:4000/sse",autoComplete:"off"})}),t.jsx(v.List,{name:"headerEntries",children:(m,{add:x,remove:L})=>t.jsxs(A,{direction:"vertical",style:{width:"100%"},children:[t.jsxs(A,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[t.jsx(ja,{strong:!0,children:l("settings.mcpServerForm.headers")}),t.jsx(O,{icon:t.jsx(Ct,{}),onClick:()=>x({name:"",value:""}),type:"dashed",children:l("settings.mcpServerForm.addHeader")})]}),m.map(P=>t.jsxs(A,{align:"baseline",style:{display:"flex"},children:[t.jsx(v.Item,{...P,name:[P.name,"name"],rules:[{required:!0,message:l("settings.mcpServerForm.headerNameRequired")}],children:t.jsx(H,{placeholder:"Authorization",autoComplete:"off"})}),t.jsx(v.Item,{...P,name:[P.name,"value"],children:t.jsx(H,{placeholder:"Bearer token",autoComplete:"off"})}),t.jsx(O,{danger:!0,type:"text",icon:t.jsx(fa,{}),onClick:()=>L(P.name),"aria-label":l("settings.mcpServerForm.removeHeader","Remove header")})]},P.key))]})})]})]})]})},bs=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Tt=(e,s)=>{const a=e[s];return typeof a=="string"?a:void 0},wa=(e,s)=>{const a=e[s];return typeof a=="boolean"?a:void 0},Qr=(e,s)=>{const a=e[s];return Array.isArray(a)?a:void 0},Yt=e=>{if(!bs(e))return"any";const s=e.type;if(typeof s=="string"){if(s==="array"){const i=e.items;return`array<${Yt(i)}>`}return s==="object"?"object":s}if(Array.isArray(s)){const i=s.filter(l=>typeof l=="string").map(l=>l==="array"?"array<any>":l);return i.length>0?i.join(" | "):"any"}const a=Array.isArray(e.oneOf)?e.oneOf:null;if(a)return a.map(Yt).join(" | ")||"any";const n=Array.isArray(e.anyOf)?e.anyOf:null;if(n)return n.map(Yt).join(" | ")||"any";const r=Array.isArray(e.allOf)?e.allOf:null;return r&&r.map(Yt).join(" & ")||"any"},ei=e=>{if(!bs(e))return null;const s=e.properties;if(!bs(s))return{schemaUri:Tt(e,"$schema"),title:Tt(e,"title"),description:Tt(e,"description"),additionalProperties:wa(e,"additionalProperties"),fields:[]};const a=new Set((Qr(e,"required")??[]).filter(r=>typeof r=="string").map(r=>r)),n=Object.entries(s).map(([r,i])=>{const l=bs(i)?i:void 0;return{name:r,type:Yt(i),required:a.has(r),description:l?Tt(l,"description"):void 0,defaultValue:l?l.default:void 0,enumValues:l&&Array.isArray(l.enum)?l.enum:void 0}});return n.sort((r,i)=>r.required!==i.required?r.required?-1:1:r.name.localeCompare(i.name)),{schemaUri:Tt(e,"$schema"),title:Tt(e,"title"),description:Tt(e,"description"),additionalProperties:wa(e,"additionalProperties"),fields:n}},{Text:Ye}=ce,ti=e=>e===void 0?"":e===null?"null":typeof e=="string"?e:Ja(e,0),si=({schema:e})=>{const{token:s}=fe.useToken(),{t:a}=te(),n=o.useMemo(()=>ei(e),[e]);if(!n)return t.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:Ja(e,2)});const r=[{title:a("components.jsonSchema.field"),dataIndex:"name",key:"name",width:180,render:l=>t.jsx(Ye,{code:!0,children:l})},{title:a("components.jsonSchema.type"),dataIndex:"type",key:"type",width:140,render:l=>t.jsx(Ye,{children:l})},{title:a("components.jsonSchema.required"),dataIndex:"required",key:"required",width:110,render:l=>l?t.jsx(Ye,{strong:!0,style:{color:s.colorError},children:a("components.jsonSchema.yes")}):t.jsx(Ye,{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(Ye,{type:"secondary",children:"-"}):t.jsx(Ye,{children:ti(l)})},{title:a("components.jsonSchema.description"),dataIndex:"description",key:"description",render:l=>l?t.jsx(Ye,{style:{whiteSpace:"pre-wrap"},children:l}):t.jsx(Ye,{type:"secondary",children:"-"})}],i=(n.fields??[]).map(l=>({...l,key:l.name}));return t.jsxs("div",{style:{width:"100%"},children:[t.jsx(Ae,{size:"small",column:1,items:[n.schemaUri?{key:"schema",label:"$schema",children:t.jsx(Ye,{code:!0,children:n.schemaUri})}:null,typeof n.additionalProperties=="boolean"?{key:"additionalProperties",label:"additionalProperties",children:t.jsx(Ye,{children:n.additionalProperties?"true":"false"})}:null].filter(Boolean)}),t.jsx(ct,{size:"small",pagination:!1,columns:r,dataSource:i,locale:{emptyText:a("components.jsonSchema.noProperties")},style:{marginTop:s.marginSM}})]})},{Text:qt}=ce,ai=(e,s)=>`mcp__${e}__${s}`,ni=({server:e,tools:s,loading:a=!1})=>{const{t:n}=te();return t.jsx(z,{title:n("settings.mcpToolList.title"),size:"small",children:e?t.jsx(Qe,{loading:a,dataSource:s,locale:{emptyText:n("settings.mcpToolList.empty")},renderItem:r=>{const i=ai(r.server_id,r.original_name);return t.jsx(Qe.Item,{children:t.jsxs(A,{direction:"vertical",size:2,style:{width:"100%"},children:[t.jsx(qt,{strong:!0,children:r.original_name}),t.jsx(qt,{type:"secondary",children:r.description||n("settings.mcpToolList.noDescription")}),t.jsx(qt,{code:!0,children:r.alias}),t.jsxs(qt,{type:"secondary",children:[n("settings.mcpToolList.aliasMapping"),": ",t.jsx(qt,{code:!0,children:i})]}),r.parameters!==void 0&&t.jsx(Ss,{size:"small",items:[{key:"schema",label:n("settings.mcpToolList.parametersSchema"),children:t.jsx(si,{schema:r.parameters})}]})]})})}}):t.jsx($e,{image:$e.PRESENTED_IMAGE_SIMPLE,description:n("settings.mcpToolList.selectServerHint")})})},{Text:Ut}=ce,{useToken:ri}=fe,{TextArea:ii}=H,Ca={[q.Connecting]:"processing",[q.Ready]:"success",[q.Degraded]:"warning",[q.Stopped]:"default",[q.Error]:"error"},oi=()=>({[q.Connecting]:0,[q.Ready]:0,[q.Degraded]:0,[q.Stopped]:0,[q.Error]:0}),jt=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,li=e=>{var a,n,r;const s={};for(const i of e){const l=(a=i.id)==null?void 0:a.trim();if(!l)continue;const d=!(i.enabled??i.config.enabled),u=i.config.transport;if(u.type==="sse"){const j={};for(const S of u.headers??[]){const k=(n=S.name)==null?void 0:n.trim();k&&(j[k]=S.value??"")}const h={url:u.url};d&&(h.disabled=!0),Object.keys(j).length&&(h.headers=j),s[l]=h;continue}const g={command:u.command};d&&(g.disabled=!0),(r=u.args)!=null&&r.length&&(g.args=u.args),u.cwd&&(g.cwd=u.cwd),u.env&&Object.keys(u.env).length&&(g.env=u.env),s[l]=g}return{mcpServers:s}},ci=()=>{const{t:e}=te(),{token:s}=ri(),[a,n]=At.useMessage(),{servers:r,selectedServerId:i,selectedServerTools:l,isLoadingServers:c,isMutatingConfig:d,isRefreshingAll:u,isSelectedServerToolsLoading:g,error:j,setSelectedServerId:h,addServer:S,updateServer:k,deleteServer:_,connectServer:F,disconnectServer:M,refreshServerTools:w,refreshAll:D,isServerActionLoading:m}=Ur(),x=o.useMemo(()=>({[q.Connecting]:e("settings.mcpTab.status.connecting"),[q.Ready]:e("settings.mcpTab.status.ready"),[q.Degraded]:e("settings.mcpTab.status.degraded"),[q.Stopped]:e("settings.mcpTab.status.stopped"),[q.Error]:e("settings.mcpTab.status.error")}),[e]),L=o.useMemo(()=>({[q.Connecting]:e("settings.mcpTab.statusHelp.connecting"),[q.Ready]:e("settings.mcpTab.statusHelp.ready"),[q.Degraded]:e("settings.mcpTab.statusHelp.degraded"),[q.Stopped]:e("settings.mcpTab.statusHelp.stopped"),[q.Error]:e("settings.mcpTab.statusHelp.error")}),[e]),[P,K]=o.useState(!1),[Z,N]=o.useState("create"),[f,b]=o.useState(null),[E,I]=o.useState(!1),[R,B]=o.useState("merge"),[se,G]=o.useState(""),[ge,he]=o.useState(null),[Ee,C]=o.useState(!1),J=o.useMemo(()=>i?r.find(p=>p.id===i)??null:null,[i,r]),Y=o.useMemo(()=>{const p=oi();let ie=0;return r.forEach(pe=>{var ye,Le;const Oe=((ye=pe.runtime)==null?void 0:ye.status)??q.Stopped;p[Oe]+=1,ie+=((Le=pe.runtime)==null?void 0:Le.tool_count)??0}),{byStatus:p,totalServers:r.length,totalTools:ie}},[r]),ee={background:s.colorFillSecondary,borderColor:s.colorBorderSecondary,color:s.colorTextSecondary},De=async p=>{try{await _(p.id),a.success(e("settings.mcpTab.serverDeleted"))}catch(ie){a.error(jt(ie,e("settings.mcpTab.deleteServerFailed")))}},Pe=async p=>{try{await F(p.id),a.success(e("settings.mcpTab.connectedTo",{name:p.name||p.id}))}catch(ie){a.error(jt(ie,e("settings.mcpTab.connectServerFailed")))}},Be=async p=>{try{await M(p.id),a.success(e("settings.mcpTab.disconnected",{name:p.name||p.id}))}catch(ie){a.error(jt(ie,e("settings.mcpTab.disconnectServerFailed")))}},Je=async p=>{try{await w(p.id),a.success(e("settings.mcpTab.toolsRefreshedFor",{name:p.name||p.id}))}catch(ie){a.error(jt(ie,e("settings.mcpTab.refreshToolsFailed")))}},$=async()=>{try{await D(),a.success(e("settings.mcpTab.statusRefreshed"))}catch(p){a.error(jt(p,e("settings.mcpTab.refreshStatusFailed")))}},be=()=>{b(null),N("create"),K(!0)},He=p=>{b(p),N("edit"),K(!0)},we=async p=>{try{if(Z==="edit"){if(!f){a.error(e("settings.mcpTab.noServerForEditing"));return}await k(f.id,p),a.success(e("settings.mcpTab.savedServer",{name:f.name||f.id}))}else await S(p),a.success(e("settings.mcpTab.addedServer",{name:p.name||p.id}));K(!1),b(null)}catch(ie){a.error(jt(ie,e("settings.mcpTab.saveServerFailed")))}},ze=()=>{I(!0),he(null),B("merge"),G("")},_e=async()=>{const p=li(r),ie=JSON.stringify(p,null,2);try{await ta(ie),a.success(e("settings.mcpTab.copiedConfig"))}catch{I(!0),he(null),B("merge"),G(ie),a.warning(e("settings.mcpTab.clipboardUnavailable"))}},Ke=async()=>{var Oe;he(null);let p;try{p=JSON.parse(se)}catch(ye){he(`${e("settings.mcpTab.invalidJsonPrefix")}: ${ye instanceof Error?ye.message:e("settings.mcpTab.unknownError")}`);return}if(!p||typeof p!="object"){he(e("settings.mcpTab.jsonMustBeObject"));return}const pe=p.mcpServers;if(!pe||typeof pe!="object"){he(e("settings.mcpTab.missingMcpServers"));return}C(!0);try{const ye=await en.importServers({mcpServers:pe,mode:R}),Le=((Oe=ye.start_errors)==null?void 0:Oe.length)??0;a.success(e("settings.mcpTab.importSummary",{count:ye.server_ids.length,added:ye.added,updated:ye.updated,removed:ye.removed,failed:Le})),Le&&a.warning(e("settings.mcpTab.importStartFailures")),I(!1),G(""),await $()}catch(ye){he(jt(ye,e("settings.mcpTab.importFailed")))}finally{C(!1)}};return t.jsxs(A,{direction:"vertical",size:s.marginMD,style:{width:"100%"},children:[n,j?t.jsx(Ve,{type:"error",showIcon:!0,message:j}):null,t.jsx(z,{size:"small",title:e("settings.mcpTab.overviewTitle"),children:t.jsxs(A,{direction:"vertical",size:s.marginXS,style:{width:"100%"},children:[t.jsx(Ut,{type:"secondary",children:e("settings.mcpTab.overviewDescription")}),t.jsxs(A,{wrap:!0,children:[t.jsx(re,{style:ee,children:e("settings.mcpTab.totalServers",{count:Y.totalServers})}),t.jsx(re,{style:ee,children:e("settings.mcpTab.totalTools",{count:Y.totalTools})}),Object.values(q).map(p=>t.jsx(ve,{title:L[p],children:t.jsxs(re,{color:p===q.Stopped?void 0:Ca[p],style:{cursor:"help",...p===q.Stopped?ee:void 0},children:[x[p],": ",Y.byStatus[p]]})},p))]}),t.jsx(Ut,{type:"secondary",children:e("settings.mcpTab.statusGuideTitle")}),t.jsx(A,{direction:"vertical",size:2,style:{width:"100%"},children:Object.values(q).map(p=>t.jsxs(Ut,{type:"secondary",children:[t.jsx(re,{color:p===q.Stopped?void 0:Ca[p],style:{marginInlineEnd:8,...p===q.Stopped?ee:void 0},children:x[p]}),L[p]]},`guide-${p}`))})]})}),t.jsx(z,{size:"small",title:e("settings.mcpTab.serversTitle"),extra:t.jsxs(A,{children:[t.jsx(O,{type:"primary",onClick:be,children:e("settings.mcpTab.addServer")}),t.jsx(O,{icon:t.jsx(Rt,{}),loading:u,onClick:()=>{$()},children:e("settings.mcpTab.refreshAll")}),t.jsx(O,{icon:t.jsx(Xa,{}),onClick:()=>void _e(),children:e("settings.mcpTab.export")}),t.jsx(O,{icon:t.jsx($n,{}),onClick:ze,children:e("settings.mcpTab.import")})]}),children:t.jsx(Gr,{servers:r,loading:c,selectedServerId:i,onSelectServer:h,onEditServer:He,onDeleteServer:De,onConnectServer:Pe,onDisconnectServer:Be,onRefreshTools:Je,isServerActionLoading:m})}),t.jsx(ni,{server:J,tools:l,loading:g}),t.jsx(Zr,{open:P,mode:Z,initialConfig:(f==null?void 0:f.config)??null,confirmLoading:d,onCancel:()=>{d||(K(!1),b(null))},onSubmit:p=>void we(p)}),t.jsx(lt,{open:E,title:e("settings.mcpTab.importModalTitle"),okText:e("settings.mcpTab.import"),onOk:()=>void Ke(),okButtonProps:{loading:Ee},onCancel:()=>{Ee||(I(!1),he(null))},width:800,destroyOnClose:!1,children:t.jsxs(A,{direction:"vertical",style:{width:"100%"},size:"middle",children:[t.jsxs(Ut,{type:"secondary",children:[e("settings.mcpTab.importHint"),t.jsx("br",{}),t.jsx(Ut,{code:!0,children:'{ "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "..."] } } }'})]}),t.jsxs(Pt.Group,{value:R,onChange:p=>B(p.target.value),optionType:"button",buttonStyle:"solid",children:[t.jsx(Pt.Button,{value:"merge",children:e("settings.mcpTab.importModeMerge")}),t.jsx(Pt.Button,{value:"replace",children:e("settings.mcpTab.importModeReplace")})]}),R==="replace"?t.jsx(Ve,{type:"warning",showIcon:!0,message:e("settings.mcpTab.replaceWarning")}):null,ge?t.jsx(Ve,{type:"error",showIcon:!0,message:ge}):null,t.jsx(ii,{value:se,onChange:p=>G(p.target.value),rows:14,placeholder:'{"mcpServers": { "filesystem": { "command": "...", "args": [], "env": {} } }}',spellCheck:!1})]})})]})},tn=1,di=365,sn=e=>Number.isFinite(e)?Math.min(di,Math.max(tn,Math.floor(e??30))):30,Ns=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]),i=new Date(Date.UTC(a,n-1,r));return i.getUTCFullYear()!==a||i.getUTCMonth()!==n-1||i.getUTCDate()!==r?null:i},Ht=e=>e.toISOString().slice(0,10),ui=(e,s)=>{const a=new Date(e.getTime());return a.setUTCDate(a.getUTCDate()+s),a},gi=(e,s)=>{const a=s.getTime()-e.getTime(),n=Math.floor(a/864e5)+1;return sn(n)},na=(e,s=new Date)=>{const a=sn(e.days),n=Ht(s),r=Ns(e.endDate)??Ns(n);if(!r)return{startDate:n,endDate:n,days:tn};const i=Ns(e.startDate);if(i){const c=r<i?i:r;return{startDate:Ht(i),endDate:Ht(c),days:gi(i,c)}}const l=ui(r,-(a-1));return{startDate:Ht(l),endDate:Ht(r),days:a}},mi=15e3,pi=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,hi=(e={})=>{const{filters:s,autoRefreshMs:a=mi}=e,n=o.useMemo(()=>({startDate:s==null?void 0:s.startDate,endDate:s==null?void 0:s.endDate,days:(s==null?void 0:s.days)??30,endpoint:s==null?void 0:s.endpoint,model:s==null?void 0:s.model,limit:(s==null?void 0:s.limit)??100}),[s==null?void 0:s.startDate,s==null?void 0:s.endDate,s==null?void 0:s.days,s==null?void 0:s.endpoint,s==null?void 0:s.model,s==null?void 0:s.limit]),r=o.useMemo(()=>na({startDate:n.startDate,endDate:n.endDate,days:n.days}),[n.days,n.endDate,n.startDate]),[i,l]=o.useState(null),[c,d]=o.useState([]),[u,g]=o.useState([]),[j,h]=o.useState(!1),[S,k]=o.useState(!1),[_,F]=o.useState(null),M=o.useCallback(async D=>{D?h(!0):k(!0);try{const m={startDate:r.startDate,endDate:r.endDate,endpoint:n.endpoint,model:n.model,limit:n.limit},[x,L,P]=await Promise.all([Zt.getForwardSummary(m),Zt.getForwardByEndpoint(m),Zt.getForwardRequests(m)]);l(x),d(L),g(P),F(null)}catch(m){F(pi(m,"Failed to load forward metrics"))}finally{D?h(!1):k(!1)}},[n.endpoint,n.model,n.limit,r.endDate,r.startDate]),w=o.useCallback(async()=>{await M(!1)},[M]);return o.useEffect(()=>{M(!0)},[M]),o.useEffect(()=>{if(a<=0)return;const D=window.setInterval(()=>{M(!1)},a);return()=>{window.clearInterval(D)}},[a,M]),{summary:i,endpointMetrics:c,requests:u,isLoading:j,isRefreshing:S,error:_,refresh:w}},fi=15e3,Ma=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,yi=(e={})=>{const{filters:s,autoRefreshMs:a=fi,service:n=Zt}=e,r=o.useMemo(()=>({startDate:s==null?void 0:s.startDate,endDate:s==null?void 0:s.endDate,model:s==null?void 0:s.model,days:(s==null?void 0:s.days)??30,granularity:(s==null?void 0:s.granularity)??"daily",sessionLimit:(s==null?void 0:s.sessionLimit)??200}),[s==null?void 0:s.startDate,s==null?void 0:s.endDate,s==null?void 0:s.model,s==null?void 0:s.days,s==null?void 0:s.granularity,s==null?void 0:s.sessionLimit]),i=o.useMemo(()=>na({startDate:r.startDate,endDate:r.endDate,days:r.days}),[r.days,r.endDate,r.startDate]),[l,c]=o.useState(null),[d,u]=o.useState([]),[g,j]=o.useState([]),[h,S]=o.useState([]),[k,_]=o.useState(null),[F,M]=o.useState([]),[w,D]=o.useState(null),[m,x]=o.useState(!1),[L,P]=o.useState(!1),[K,Z]=o.useState(!1),[N,f]=o.useState(null),b=o.useCallback(async B=>{B?P(!0):Z(!0);try{const se=n.getMemorySummary?n.getMemorySummary().catch(()=>null):Promise.resolve(null),G=n.getMemoryTimeline?n.getMemoryTimeline({days:i.days,endDate:i.endDate,granularity:r.granularity}).catch(()=>[]):Promise.resolve([]),[ge,he,Ee,C,J,Y]=await Promise.all([n.getSummary({startDate:i.startDate,endDate:i.endDate}),n.getByModel({startDate:i.startDate,endDate:i.endDate}),n.getSessions({startDate:i.startDate,endDate:i.endDate,model:r.model,limit:r.sessionLimit}),n.getDaily({days:i.days,endDate:i.endDate,granularity:r.granularity}),se,G]);c(ge),u(he),j(Ee),S(C),_(J),M(Y),f(null)}catch(se){f(Ma(se,"Failed to load metrics"))}finally{B?P(!1):Z(!1)}},[r.granularity,r.model,r.sessionLimit,i.days,i.endDate,i.startDate,n]),E=o.useCallback(async()=>{await b(!1)},[b]),I=o.useCallback(async B=>{x(!0);try{const se=await n.getSessionDetail(B);D(se)}catch(se){f(Ma(se,"Failed to load session detail"))}finally{x(!1)}},[n]),R=o.useCallback(()=>{D(null)},[]);return o.useEffect(()=>{b(!0)},[b]),o.useEffect(()=>{if(a<=0)return;const B=window.setInterval(()=>{b(!1)},a);return()=>{window.clearInterval(B)}},[a,b]),{summary:l,modelMetrics:d,sessions:g,timeline:h,memorySummary:k,memoryTimeline:F,sessionDetail:w,isLoading:L,isRefreshing:K,isSessionDetailLoading:m,error:N,refresh:E,loadSessionDetail:I,clearSessionDetail:R}},xi=15e3,bi=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,vi=(e={})=>{const{filters:s,autoRefreshMs:a=xi}=e,n=o.useMemo(()=>({startDate:s==null?void 0:s.startDate,endDate:s==null?void 0:s.endDate,days:(s==null?void 0:s.days)??30,model:s==null?void 0:s.model}),[s==null?void 0:s.days,s==null?void 0:s.endDate,s==null?void 0:s.model,s==null?void 0:s.startDate]),r=o.useMemo(()=>na({startDate:n.startDate,endDate:n.endDate,days:n.days}),[n.days,n.endDate,n.startDate]),[i,l]=o.useState(null),[c,d]=o.useState(!1),[u,g]=o.useState(!1),[j,h]=o.useState(null),S=o.useCallback(async _=>{_?d(!0):g(!0);try{const F=await Zt.getUsageBreakdown({startDate:r.startDate,endDate:r.endDate,model:n.model});l(F),h(null)}catch(F){h(bi(F,"Failed to load usage breakdown"))}finally{_?d(!1):g(!1)}},[n.model,r.endDate,r.startDate]),k=o.useCallback(async()=>{await S(!1)},[S]);return o.useEffect(()=>{S(!0)},[S]),o.useEffect(()=>{if(a<=0)return;const _=window.setInterval(()=>{S(!1)},a);return()=>{window.clearInterval(_)}},[a,S]),{data:i,isLoading:c,isRefreshing:u,error:j,refresh:k}},{useToken:Ti}=fe,ji=({data:e,loading:s})=>{const{t:a}=te(),{token:n}=Ti();if(s)return t.jsx(z,{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(z,{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(i=>({endpoint:i.endpoint.split(".").pop()||i.endpoint,requests:i.requests,successful:i.successful,failed:i.failed}));return t.jsx(z,{size:"small",className:"lotus-metric-card",title:a("settings.charts.endpointDistribution"),children:t.jsx("div",{style:{width:"100%",height:240},children:t.jsx(zt,{children:t.jsxs(sa,{data:r,children:[t.jsx(rs,{strokeDasharray:"3 3"}),t.jsx(is,{dataKey:"endpoint"}),t.jsx(os,{}),t.jsx(Ot,{formatter:(i,l)=>[`${i}`,l.charAt(0).toUpperCase()+l.slice(1)]}),t.jsx(aa,{}),t.jsx(Ts,{dataKey:"successful",fill:"var(--lotus-chart-secondary)",name:a("settings.common.successful"),fillOpacity:.9,radius:[4,4,0,0]}),t.jsx(Ts,{dataKey:"failed",fill:"var(--lotus-chart-danger)",name:a("settings.common.failed"),fillOpacity:.9,radius:[4,4,0,0]})]})})})})},Vs=e=>e.replace(/\.0$/,""),an=e=>e.toLocaleString(),nn=e=>Number.isFinite(e)?e.toLocaleString(void 0,{maximumFractionDigits:20}):String(e),ra=e=>{if(!Number.isFinite(e))return String(e);const s=Math.abs(e);if(s>=1e9){const a=s>=1e10?0:1;return`${Vs((e/1e9).toFixed(a))}B`}if(s>=1e6){const a=s>=1e7?0:1;return`${Vs((e/1e6).toFixed(a))}M`}if(s>=1e3){const a=s>=1e4?0:1;return`${Vs((e/1e3).toFixed(a))}K`}return an(e)},Si=e=>Number.isFinite(e)&&Math.abs(e)>=1e3,rn=e=>nn(e),as=e=>{if(!Number.isFinite(e))return String(e);const s=ra(e);return Si(e)?t.jsx(ve,{title:t.jsx("div",{children:nn(e)}),children:t.jsx("span",{children:s})}):s},it=e=>{const s=Number(e??0);return Number.isFinite(s)?as(s):e==null?"-":String(e)},{useToken:_i}=fe,ki=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),i=a%60;return`${r}h ${i}m`}return a>0?`${a}m ${n}s`:`${n}s`},Ea=({summary:e,loading:s})=>{const{t:a}=te(),{token:n}=_i();if(s)return t.jsx(dt,{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(We,{gutter:[n.marginSM,n.marginSM],children:[t.jsx(le,{xs:24,sm:12,xl:6,children:t.jsx(z,{size:"small",className:"lotus-metric-card",children:t.jsx(Se,{title:a("settings.forwardMetricsCards.totalForwardRequests"),value:(e==null?void 0:e.total_requests)??0,precision:0,formatter:it,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),t.jsx(le,{xs:24,sm:12,xl:6,children:t.jsx(z,{size:"small",className:"lotus-metric-card",children:t.jsx(Se,{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(le,{xs:24,sm:12,xl:6,children:t.jsx(z,{size:"small",className:"lotus-metric-card",children:t.jsx(Se,{title:a("settings.forwardMetricsCards.forwardTokens"),value:(e==null?void 0:e.total_tokens.total_tokens)??0,precision:0,formatter:it,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})}),t.jsx(le,{xs:24,sm:12,xl:6,children:t.jsx(z,{size:"small",className:"lotus-metric-card",children:t.jsx(Se,{title:a("settings.forwardMetricsCards.avgResponseTime"),value:ki(e==null?void 0:e.avg_duration_ms),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:St}=ce,wi=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`},Ci=e=>new Date(e).toLocaleString(),Mi=({requests:e,loading:s})=>{const{t:a}=te(),n=[{title:a("settings.metricsTable.forward.columns.id"),dataIndex:"forward_id",key:"forward_id",width:120,render:r=>t.jsxs(St,{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(re,{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(re,{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,i)=>{const l=i.status==="success"?"success":i.status==="error"?"error":"default";return t.jsx(Bn,{status:l,text:i.status_code?t.jsxs("span",{children:[i.status,t.jsxs(St,{type:"secondary",style:{marginLeft:4},children:["(",i.status_code,")"]})]}):i.status||"-"})}},{title:a("settings.metricsTable.forward.columns.tokens"),key:"tokens",width:100,render:(r,i)=>i.token_usage?t.jsx(St,{children:as(i.token_usage.total_tokens)}):t.jsx(St,{type:"secondary",children:"-"})},{title:a("settings.metricsTable.forward.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",width:100,render:r=>wi(r)},{title:a("settings.metricsTable.forward.columns.started"),dataIndex:"started_at",key:"started_at",width:160,render:r=>t.jsx(St,{type:"secondary",style:{fontSize:12},children:Ci(r)})},{title:a("settings.metricsTable.forward.columns.error"),dataIndex:"error",key:"error",width:200,render:r=>r?t.jsx(St,{type:"danger",ellipsis:!0,style:{maxWidth:180},children:r}):t.jsx(St,{type:"secondary",children:"-"})}];return t.jsx(ct,{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:Ei}=fe,Di=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString()},Da=({summary:e,loading:s})=>{const{t:a}=te(),{token:n}=Ei();return s?t.jsx(dt,{active:!0,paragraph:{rows:1}}):t.jsxs(We,{gutter:[n.marginSM,n.marginSM],children:[t.jsx(le,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(z,{size:"small",className:"lotus-metric-card",children:t.jsx(Se,{title:a("settings.unifiedMetricsCards.totalMemories"),value:(e==null?void 0:e.total_memories)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),t.jsx(le,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(z,{size:"small",className:"lotus-metric-card",children:t.jsx(Se,{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(le,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(z,{size:"small",className:"lotus-metric-card",children:t.jsx(Se,{title:a("settings.unifiedMetricsCards.memoryProjects"),value:(e==null?void 0:e.project_count)??0,precision:0,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),t.jsx(le,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(z,{size:"small",className:"lotus-metric-card",children:t.jsx(Se,{title:a("settings.unifiedMetricsCards.lastReindex"),value:Di(e==null?void 0:e.last_reindex_at),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:Pi}=ce,Ii=({data:e,loading:s})=>{const{t:a}=te();return s?t.jsx(z,{size:"small",className:"lotus-metric-card",title:a("settings.charts.memoryTrendTitle"),children:t.jsx(dt,{active:!0,paragraph:{rows:5}})}):t.jsx(z,{size:"small",className:"lotus-metric-card",title:a("settings.charts.memoryTrendTitle"),children:e.length===0?t.jsx($e,{image:$e.PRESENTED_IMAGE_SIMPLE,description:a("settings.charts.noMemoryTrend")}):t.jsxs(t.Fragment,{children:[t.jsx(Pi,{type:"secondary",children:a("settings.charts.memoryTrendDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(zt,{children:t.jsxs(Za,{data:e,children:[t.jsx(rs,{strokeDasharray:"3 3"}),t.jsx(is,{dataKey:"label",minTickGap:24}),t.jsx(os,{allowDecimals:!1}),t.jsx(Ot,{}),t.jsx(aa,{}),t.jsx(It,{type:"monotone",dataKey:"total_memories",name:a("settings.charts.totalMemories"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),t.jsx(It,{type:"monotone",dataKey:"created_memories",name:a("settings.charts.createdMemories"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),t.jsx(It,{type:"monotone",dataKey:"updated_memories",name:a("settings.charts.updatedMemories"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{useToken:Fi}=fe,Ai=e=>{const s=Math.floor(e/1e3),a=Math.floor(s/60),n=s%60;return a>0?`${a}m ${n}s`:`${n}s`},Ri=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)},Pa=({summary:e,sessions:s,loading:a})=>{const{t:n}=te(),{token:r}=Fi();if(a)return t.jsx(dt,{active:!0,paragraph:{rows:1}});const i=Ri(s);return t.jsxs(We,{gutter:[r.marginSM,r.marginSM],children:[t.jsx(le,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(z,{size:"small",className:"lotus-metric-card",children:t.jsx(Se,{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(le,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(z,{size:"small",className:"lotus-metric-card",children:t.jsx(Se,{title:n("settings.metricsCards.totalSessions"),value:(e==null?void 0:e.total_sessions)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),t.jsx(le,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(z,{size:"small",className:"lotus-metric-card",children:t.jsx(Se,{title:n("settings.metricsCards.chatTokens"),value:(e==null?void 0:e.total_tokens.total_tokens)??0,precision:0,formatter:it,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})}),t.jsx(le,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(z,{size:"small",className:"lotus-metric-card",children:t.jsx(Se,{title:n("settings.metricsCards.totalToolCalls"),value:(e==null?void 0:e.total_tool_calls)??0,precision:0,formatter:it,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),t.jsx(le,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(z,{size:"small",className:"lotus-metric-card",children:t.jsx(Se,{title:n("settings.metricsCards.tokensSaved",{defaultValue:"Saved Tokens"}),value:(e==null?void 0:e.total_tokens_saved)??0,precision:0,formatter:it,valueStyle:{color:"var(--lotus-chart-cyan)"}})})}),t.jsx(le,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(z,{size:"small",className:"lotus-metric-card",children:t.jsx(Se,{title:n("settings.metricsCards.toolContextSavedTokens",{defaultValue:"Tool Context Saved Tokens"}),value:(e==null?void 0:e.tool_context_tokens_saved)??0,precision:0,formatter:it,valueStyle:{color:"var(--lotus-chart-accent)"}})})}),t.jsx(le,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(z,{size:"small",className:"lotus-metric-card",children:t.jsx(Se,{title:n("settings.metricsCards.compressionEvents",{defaultValue:"Compression Events"}),value:(e==null?void 0:e.total_compression_events)??0,precision:0,formatter:it,valueStyle:{color:"var(--lotus-chart-secondary)"}})})}),t.jsx(le,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(z,{size:"small",className:"lotus-metric-card",children:t.jsx(Se,{title:n("settings.metricsCards.avgSessionDuration"),value:i>0?Ai(i):"-",valueStyle:{color:"var(--lotus-chart-accent)"}})})})]})},{Text:zi}=ce,Ia=["var(--lotus-chart-primary)","var(--lotus-chart-secondary)","var(--lotus-chart-accent)","var(--lotus-chart-purple)","var(--lotus-chart-cyan)"],Oi=({data:e,loading:s})=>{const{t:a}=te();if(s)return t.jsx(z,{size:"small",className:"lotus-metric-card",title:a("settings.charts.modelDistribution"),children:t.jsx(dt,{active:!0,paragraph:{rows:5}})});const n=e.map(r=>({name:r.model,value:r.tokens.total_tokens}));return t.jsx(z,{size:"small",className:"lotus-metric-card",title:a("settings.charts.modelDistribution"),children:n.length===0?t.jsx($e,{image:$e.PRESENTED_IMAGE_SIMPLE,description:a("settings.charts.noModelMetrics")}):t.jsxs(t.Fragment,{children:[t.jsx(zi,{type:"secondary",children:a("settings.charts.modelDistributionDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(zt,{children:t.jsxs(Qn,{children:[t.jsx(er,{data:n,cx:"50%",cy:"50%",outerRadius:90,fill:"var(--lotus-chart-primary)",dataKey:"value",nameKey:"name",label:!0,children:n.map((r,i)=>t.jsx(tr,{fill:Ia[i%Ia.length]},`${r.name}-${i}`))}),t.jsx(Ot,{formatter:r=>rn(r)})]})})})]})})},Li=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?"-":s.toLocaleString()},Ni=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),i=a%60;return`${r}h ${i}m`}return a>0?`${a}m ${n}s`:`${n}s`},Vi=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"}},$i=(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}},Bi=({sessions:e,loading:s,onSelectSession:a})=>{const{t:n}=te(),r=[{title:n("settings.metricsTable.session.columns.session"),dataIndex:"session_id",key:"session_id",render:i=>t.jsx(ve,{title:i,children:t.jsxs("span",{children:[i.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:i=>t.jsx(re,{color:Vi(i),children:$i(i,n)})},{title:n("settings.metricsTable.session.columns.started"),dataIndex:"started_at",key:"started_at",render:i=>Li(i),width:200,sorter:(i,l)=>new Date(i.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:i=>Ni(i),width:120},{title:n("settings.metricsTable.session.columns.tokens"),key:"tokens",render:(i,l)=>as(l.total_token_usage.total_tokens),width:120,sorter:(i,l)=>i.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:(i,l)=>i.tool_call_count-l.tool_call_count},{title:n("settings.metricsTable.session.columns.messages"),dataIndex:"message_count",key:"message_count",width:120,sorter:(i,l)=>i.message_count-l.message_count},{title:n("settings.metricsTable.session.columns.action"),key:"action",fixed:"right",width:120,render:(i,l)=>t.jsx(O,{type:"link",onClick:()=>{a(l.session_id)},children:n("settings.metricsTable.session.view")})}];return t.jsx(ct,{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}=ce,Fa={message_count:"Message Count",last_message_id:"Last Message",pending_question:"Pending Question"},Ui=e=>Fa[e]?Fa[e]:e.split("_").map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "),Hi=({breakdown:e,loading:s})=>{const{t:a}=te();if(s)return t.jsx(z,{size:"small",className:"lotus-metric-card",title:a("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),children:t.jsx(dt,{active:!0,paragraph:{rows:5}})});const n=Object.entries(e??{}).map(([r,i])=>({reason:r,label:a(`settings.syncMismatchReasons.${r}`,{defaultValue:Ui(r)}),count:i})).sort((r,i)=>i.count-r.count);return t.jsx(z,{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($e,{image:$e.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(zt,{children:t.jsxs(sa,{data:n,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[t.jsx(rs,{strokeDasharray:"3 3"}),t.jsx(is,{type:"number",allowDecimals:!1}),t.jsx(os,{dataKey:"label",type:"category",width:110}),t.jsx(Ot,{formatter:r=>[r.toLocaleString(),a("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})],labelFormatter:r=>a("settings.metricsDashboard.syncMismatchReasonLabel",{defaultValue:"Reason: {{label}}",label:r})}),t.jsx(Ts,{dataKey:"count",fill:"var(--lotus-chart-danger)",radius:[0,6,6,0],name:a("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})})]})})})})},{Text:Ki}=ce,Wi=({data:e,loading:s})=>{const{t:a}=te();return s?t.jsx(z,{size:"small",className:"lotus-metric-card",title:a("settings.charts.tokenUsageOverTime"),children:t.jsx(dt,{active:!0,paragraph:{rows:5}})}):t.jsx(z,{size:"small",className:"lotus-metric-card",title:a("settings.charts.tokenUsageOverTime"),children:e.length===0?t.jsx($e,{image:$e.PRESENTED_IMAGE_SIMPLE,description:a("settings.charts.noTokenUsage")}):t.jsxs(t.Fragment,{children:[t.jsx(Ki,{type:"secondary",children:a("settings.charts.tokenUsageDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(zt,{children:t.jsxs(Za,{data:e,children:[t.jsx(rs,{strokeDasharray:"3 3"}),t.jsx(is,{dataKey:"label",minTickGap:24}),t.jsx(os,{allowDecimals:!1,tickFormatter:ra}),t.jsx(Ot,{formatter:n=>rn(n)}),t.jsx(aa,{}),t.jsx(It,{type:"monotone",dataKey:"totalTokens",name:a("settings.charts.total"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),t.jsx(It,{type:"monotone",dataKey:"promptTokens",name:a("settings.charts.prompt"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),t.jsx(It,{type:"monotone",dataKey:"completionTokens",name:a("settings.charts.completion"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{Text:Gi}=ce,Kt=({title:e,subtitle:s,emptyText:a,color:n="var(--lotus-chart-primary)",data:r,loading:i,countLabel:l})=>{const{t:c}=te();return i?t.jsx(z,{size:"small",className:"lotus-metric-card",title:e,children:t.jsx(dt,{active:!0,paragraph:{rows:5}})}):t.jsx(z,{size:"small",className:"lotus-metric-card",title:e,children:r.length===0?t.jsx($e,{image:$e.PRESENTED_IMAGE_SIMPLE,description:a}):t.jsxs(t.Fragment,{children:[s?t.jsx(Gi,{type:"secondary",children:s}):null,t.jsx("div",{style:{width:"100%",minWidth:0,height:280,marginTop:s?12:0},children:t.jsx(zt,{children:t.jsxs(sa,{data:r,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[t.jsx(rs,{strokeDasharray:"3 3"}),t.jsx(is,{type:"number",allowDecimals:!1}),t.jsx(os,{dataKey:"label",type:"category",width:110}),t.jsx(Ot,{formatter:d=>[d.toLocaleString(),l??c("settings.metricsDashboard.calls",{defaultValue:"Calls"})],labelFormatter:(d,u)=>{var j,h;const g=(h=(j=u==null?void 0:u[0])==null?void 0:j.payload)==null?void 0:h.meta;return g?`${d} · ${g}`:String(d)}}),t.jsx(Ts,{dataKey:"count",fill:n,radius:[0,6,6,0],name:l??c("settings.metricsDashboard.calls",{defaultValue:"Calls"})})]})})})]})})},{useToken:Ji}=fe,Aa=({summary:e,loading:s})=>{const{t:a}=te(),{token:n}=Ji();if(s)return t.jsx(dt,{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(i=>i.value>0);return r.length===0?null:t.jsx(We,{gutter:[n.marginSM,n.marginSM],children:r.map(i=>t.jsx(le,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(z,{size:"small",className:"lotus-metric-card",children:t.jsx(Se,{title:i.title,value:i.value,precision:0,formatter:it,valueStyle:{color:i.color}})})},i.key))})},{Text:_t}=ce,{useToken:Xi}=fe,Ra=e=>"date"in e?e.date:e.label,Yi=(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)"},ms=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),i=a%60;return`${r}h ${i}m`}return a>0?`${a}m ${n}s`:`${n}s`},za=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString()},$s=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}: ${an(n)}`).join(" • ")},Bs=(e,s=320)=>({width:"100%",display:"grid",gridTemplateColumns:`repeat(auto-fit, minmax(${s}px, 1fr))`,gap:e}),Zi=()=>{const{t:e}=te(),{token:s}=Xi(),a=vn(p=>p.themeMode)==="dark",[n,r]=o.useState(void 0),[i,l]=o.useState(void 0),[c,d]=o.useState(void 0),[u,g]=o.useState(30),[j,h]=o.useState("daily"),{summary:S,modelMetrics:k,sessions:_,timeline:F,memorySummary:M,memoryTimeline:w,sessionDetail:D,isLoading:m,isRefreshing:x,isSessionDetailLoading:L,error:P,refresh:K,loadSessionDetail:Z,clearSessionDetail:N}=yi({filters:{startDate:n,endDate:i,model:c,days:u,granularity:j}}),{summary:f,endpointMetrics:b,requests:E,isLoading:I,isRefreshing:R,error:B,refresh:se}=hi({filters:{startDate:n,endDate:i,days:u,model:c}}),{data:G,isLoading:ge,isRefreshing:he,error:Ee,refresh:C}=vi({filters:{startDate:n,endDate:i,days:u,model:c}}),J=o.useMemo(()=>F.map(p=>({label:Ra(p),promptTokens:p.total_token_usage.prompt_tokens,completionTokens:p.total_token_usage.completion_tokens,totalTokens:p.total_token_usage.total_tokens})),[F]),Y=o.useMemo(()=>k.map(p=>({label:p.model,value:p.model})),[k]),ee=o.useMemo(()=>{const p=F.map(pe=>({label:Ra(pe),sessions:pe.total_sessions,tokens:pe.total_token_usage.total_tokens})),ie=p.reduce((pe,Oe)=>Math.max(pe,Oe.sessions),0);return{points:p,maxSessions:ie}},[F]),De=o.useMemo(()=>{const p=E.map(pe=>pe.duration_ms).filter(pe=>typeof pe=="number"&&pe>0).sort((pe,Oe)=>pe-Oe);if(p.length===0)return null;const ie=Math.ceil(p.length*.95)-1;return p[Math.max(0,Math.min(ie,p.length-1))]},[E]),Pe=o.useMemo(()=>[{title:e("settings.metricsDashboard.roundColumns.round"),dataIndex:"round_id",key:"round_id",render:p=>`${p.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:p=>ms(p)},{title:e("settings.metricsDashboard.roundColumns.tokens"),key:"tokens",render:(p,ie)=>as(ie.token_usage.total_tokens)},{title:e("settings.metricsDashboard.roundColumns.toolCalls"),key:"tool_calls",render:(p,ie)=>ie.tool_calls.length}],[e]),Be=o.useMemo(()=>{const p=(S==null?void 0:S.total_sessions)??0,ie=(S==null?void 0:S.total_tokens.total_tokens)??0,pe=(S==null?void 0:S.total_tool_calls)??0,Oe=(S==null?void 0:S.active_sessions)??0,ye=_.reduce((Nt,y)=>Nt+y.total_rounds,0),Le=(S==null?void 0:S.total_tokens_saved)??0,ds=(S==null?void 0:S.tool_context_tokens_saved)??0,Cs=(S==null?void 0:S.non_tool_compression_tokens_saved)??0,Ms=(S==null?void 0:S.prompt_cached_tool_outputs)??0,Lt=(S==null?void 0:S.total_compression_events)??0,ut=(f==null?void 0:f.total_requests)??0,Es=(f==null?void 0:f.total_tokens.total_tokens)??0,Ds=(f==null?void 0:f.failed_requests)??0,Ps=E.filter(Nt=>Nt.is_stream).length,us=p>0?Oe/p*100:0,Is=ut>0?Ds/ut*100:0,Fs=E.length>0?Ps/E.length*100:0,yt=ie>0?Number((Le/ie*100).toFixed(1)):0,As=Le>0?Number((ds/Le*100).toFixed(1)):0;return[{title:e("settings.metricsDashboard.compactStats.avgTokensPerSession"),value:p>0?Math.round(ie/p):0},{title:e("settings.metricsDashboard.compactStats.savedTokens",{defaultValue:"Saved Tokens"}),value:Le},{title:e("settings.metricsDashboard.compactStats.toolContextSavedTokens",{defaultValue:"Tool Context Saved Tokens"}),value:ds},{title:e("settings.metricsDashboard.compactStats.nonToolCompressionSavedTokens",{defaultValue:"Non-Tool Compression Saved Tokens"}),value:Cs},{title:e("settings.metricsDashboard.compactStats.savedTokenRatio",{defaultValue:"Saved / Chat Tokens"}),value:yt,suffix:"%"},{title:e("settings.metricsDashboard.compactStats.toolSavedShare",{defaultValue:"Tool Share of Saved Tokens"}),value:As,suffix:"%"},{title:e("settings.metricsDashboard.compactStats.promptCachedToolOutputs",{defaultValue:"Prompt-Cached Tool Outputs"}),value:Ms},{title:e("settings.metricsDashboard.compactStats.compressionEvents",{defaultValue:"Compression Events"}),value:Lt},{title:e("settings.metricsDashboard.compactStats.avgRoundsPerSession"),value:p>0?Number((ye/p).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.toolCallsPerSession"),value:p>0?Number((pe/p).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.activeSessionRate"),value:Number(us.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.avgTokensPerForward"),value:ut>0?Math.round(Es/ut):0},{title:e("settings.metricsDashboard.compactStats.forwardErrorRate"),value:Number(Is.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.streamingRatio"),value:Number(Fs.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.p95ForwardLatency"),value:ms(De)},{title:e("settings.metricsDashboard.compactStats.modelCoverage"),value:k.length},{title:e("settings.metricsDashboard.compactStats.endpointCoverage"),value:b.length}]},[b.length,E,f,k.length,De,_,S,e]),Je=o.useMemo(()=>{const p=(f==null?void 0:f.total_requests)??0,ie=(f==null?void 0:f.failed_requests)??0,pe=E.filter(Le=>Le.is_stream).length,Oe=E.length>0?pe/E.length*100:0,ye=p>0?ie/p*100:0;return[{title:e("settings.metricsDashboard.forward.performance.p95Latency",{defaultValue:"P95 Latency"}),value:ms(De)},{title:e("settings.metricsDashboard.forward.performance.errorRate",{defaultValue:"Error Rate"}),value:Number(ye.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.streamingRatio",{defaultValue:"Streaming Ratio"}),value:Number(Oe.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.endpointCoverage",{defaultValue:"Endpoint Coverage"}),value:b.length}]},[b.length,E,f,De,e]),$=o.useMemo(()=>G?[{label:e("settings.metricsDashboard.skillsAndMcp.mix.coreTools",{defaultValue:"Core Tools"}),count:G.core_tool_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.skillLoads",{defaultValue:"Skill Loads"}),count:G.skill_load_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.mcpCalls",{defaultValue:"MCP Calls"}),count:G.mcp_calls}].filter(p=>p.count>0):[],[e,G]),be=o.useMemo(()=>((G==null?void 0:G.top_skills)??[]).map(p=>({label:p.skill_id,count:p.count})),[G]),He=o.useMemo(()=>((G==null?void 0:G.top_mcp_servers)??[]).map(p=>({label:p.server_id,count:p.count,meta:e("settings.metricsDashboard.skillsAndMcp.meta.uniqueTools",{defaultValue:"{{count}} tools",count:p.unique_tools})})),[e,G]),we=o.useMemo(()=>((G==null?void 0:G.top_mcp_tools)??[]).map(p=>({label:p.tool_name,count:p.count,meta:p.server_id})),[G]),ze=o.useMemo(()=>((G==null?void 0:G.top_core_tools)??[]).map(p=>({label:p.name,count:p.count})),[G]),_e=D==null?void 0:D.session,Ke=x||R||he;return t.jsxs(A,{direction:"vertical",size:s.marginMD,style:{width:"100%"},children:[P?t.jsx(Ve,{type:"error",showIcon:!0,message:P}):null,B?t.jsx(Ve,{type:"error",showIcon:!0,message:B}):null,Ee?t.jsx(Ve,{type:"error",showIcon:!0,message:Ee}):null,t.jsx(z,{size:"small",title:e("settings.metricsDashboard.filtersTitle"),extra:t.jsx(O,{icon:t.jsx(Rt,{}),loading:Ke,onClick:()=>{K(),se(),C()},children:e("settings.metricsDashboard.refresh")}),children:t.jsxs(A,{wrap:!0,children:[t.jsx(ya,{placeholder:e("settings.metricsDashboard.startDate"),onChange:p=>{r(p?p.format("YYYY-MM-DD"):void 0)}}),t.jsx(ya,{placeholder:e("settings.metricsDashboard.endDate"),onChange:p=>{l(p?p.format("YYYY-MM-DD"):void 0)}}),t.jsx(Q,{allowClear:!0,style:{minWidth:180},placeholder:e("settings.metricsDashboard.model"),value:c,options:Y,onChange:p=>{d(p)}}),t.jsx(Q,{style:{width:120},value:u,options:[7,14,30,90].map(p=>({label:e("settings.metricsDashboard.daysOption",{value:p}),value:p})),onChange:p=>{g(p)}}),t.jsx(Q,{style:{width:140},value:j,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:p=>{h(p)}})]})}),t.jsx(z,{size:"small",title:e("settings.metricsDashboard.dashboardTitle"),children:t.jsx(vs,{size:"small",destroyInactiveTabPane:!0,items:[{key:"overview",label:e("settings.metricsDashboard.tabs.overview"),children:t.jsxs(A,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(z,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.overviewSections.scaleTitle",{defaultValue:"Scale & Activity"}),extra:t.jsx(_t,{type:"secondary",children:e("settings.metricsDashboard.overviewSections.scaleSubtitle",{defaultValue:"Current usage volume across chat, forward, skills, and memory."})}),children:t.jsxs(A,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(Pa,{summary:S,sessions:_,loading:m}),t.jsx(Ea,{summary:f,loading:I}),t.jsx(Aa,{summary:G,loading:ge}),t.jsx(Da,{summary:M,loading:m})]})}),t.jsxs(z,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.overviewSections.efficiencyTitle",{defaultValue:"Compression & Efficiency Advantage"}),extra:t.jsx(_t,{type:"secondary",children:e("settings.metricsDashboard.overviewSections.efficiencySubtitle",{defaultValue:"Real savings from context compression, especially around tool-heavy workflows."})}),children:[t.jsx(We,{gutter:[s.marginSM,s.marginSM],children:Be.map(p=>t.jsx(le,{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(Se,{title:p.title,value:p.value,suffix:p.suffix,formatter:typeof p.value=="number"?it:void 0,valueStyle:{fontSize:s.fontSizeHeading4}})})},p.title))}),t.jsx(_t,{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(A,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(Pa,{summary:S,sessions:_,loading:m}),t.jsxs("div",{style:Bs(s.marginSM,360),children:[t.jsx(Wi,{data:J,loading:m}),t.jsx(Oi,{data:k,loading:m})]}),t.jsxs("div",{style:Bs(s.marginSM,360),children:[t.jsx(Hi,{breakdown:S==null?void 0:S.sync_mismatch_breakdown,loading:m}),t.jsx(z,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.activityHeatmapTitle"),children:ee.points.length===0?t.jsx(_t,{type:"secondary",children:e("settings.metricsDashboard.noActivity")}):t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(72px, 1fr))",gap:s.marginXS},children:ee.points.map(p=>t.jsxs("div",{style:{borderRadius:s.borderRadiusSM,padding:s.paddingXS,background:Yi(p.sessions,ee.maxSessions),minHeight:64,color:p.sessions>0?"var(--lotus-metric-text-strong)":s.colorTextSecondary},children:[t.jsx("div",{style:{fontSize:12,lineHeight:1.2},children:p.label}),t.jsx("div",{style:{fontWeight:600,marginTop:4},children:e("settings.metricsDashboard.sessionsCount",{count:p.sessions})}),t.jsx("div",{style:{fontSize:12},children:e("settings.metricsDashboard.tokensAmount",{value:ra(p.tokens)})})]},p.label))})})]})]})},{key:"skills-and-mcp",label:e("settings.metricsDashboard.tabs.skillsAndMcp",{defaultValue:"Skills & MCP"}),children:t.jsxs(A,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(Aa,{summary:G,loading:ge}),t.jsxs("div",{style:Bs(s.marginSM,360),children:[t.jsx(Kt,{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:$,loading:ge,color:"var(--lotus-chart-primary)"}),t.jsx(Kt,{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:be,loading:ge,color:"var(--lotus-chart-purple)"}),t.jsx(Kt,{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:He,loading:ge,color:"var(--lotus-chart-cyan)"}),t.jsx(Kt,{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:we,loading:ge,color:"var(--lotus-chart-accent)"}),t.jsx(Kt,{title:e("settings.metricsDashboard.skillsAndMcp.topCoreToolsTitle",{defaultValue:"Top Core Tools"}),subtitle:e("settings.metricsDashboard.skillsAndMcp.topCoreToolsSubtitle",{defaultValue:"Canonicalized built-in and server tool usage ranking."}),emptyText:e("settings.metricsDashboard.skillsAndMcp.noCoreTools",{defaultValue:"No core tools were called in this range."}),data:ze,loading:ge,color:"var(--lotus-chart-secondary)"})]})]})},{key:"forward",label:e("settings.metricsDashboard.tabs.forward",{defaultValue:"Forward"}),children:t.jsxs(A,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(Ea,{summary:f,loading:I}),t.jsx(z,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.forward.performanceTitle",{defaultValue:"Forward Performance"}),children:t.jsx(We,{gutter:[s.marginSM,s.marginSM],children:Je.map(p=>t.jsx(le,{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(Se,{title:p.title,value:p.value,suffix:p.suffix,valueStyle:{fontSize:s.fontSizeHeading4}})})},p.title))})}),t.jsx(ji,{data:b,loading:I})]})},{key:"memory",label:e("settings.metricsDashboard.tabs.memory",{defaultValue:"Memory"}),children:t.jsxs(A,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(Da,{summary:M,loading:m}),t.jsx(Ii,{data:w,loading:m}),t.jsx(z,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.memory.breakdownTitle",{defaultValue:"Memory Breakdown"}),children:t.jsxs(Ae,{size:"small",bordered:!0,column:1,children:[t.jsx(Ae.Item,{label:e("settings.metricsDashboard.memory.byType",{defaultValue:"By Type"}),children:$s(M==null?void 0:M.by_type)}),t.jsx(Ae.Item,{label:e("settings.metricsDashboard.memory.byStatus",{defaultValue:"By Status"}),children:$s(M==null?void 0:M.by_status)}),t.jsx(Ae.Item,{label:e("settings.metricsDashboard.memory.byScope",{defaultValue:"By Scope"}),children:$s(M==null?void 0:M.by_scope)}),t.jsx(Ae.Item,{label:e("settings.metricsDashboard.memory.lastDream",{defaultValue:"Last Dream"}),children:za(M==null?void 0:M.last_dream_at)}),t.jsx(Ae.Item,{label:e("settings.metricsDashboard.memory.lastReindex",{defaultValue:"Last Reindex"}),children:za(M==null?void 0:M.last_reindex_at)})]})})]})},{key:"records",label:e("settings.metricsDashboard.tabs.records"),children:t.jsx(vs,{size:"small",destroyInactiveTabPane:!0,items:[{key:"sessions",label:e("settings.metricsDashboard.sessionsTabLabel",{count:_.length}),children:t.jsx(z,{size:"small",extra:t.jsx(_t,{type:"secondary",children:e("settings.metricsDashboard.sessionsHint")}),children:t.jsx(Bi,{sessions:_,loading:m,onSelectSession:p=>{Z(p)}})})},{key:"forward-requests",label:e("settings.metricsDashboard.forwardTabLabel",{count:E.length}),children:t.jsx(z,{size:"small",children:t.jsx(Mi,{requests:E,loading:I})})}]})}]})}),t.jsx(lt,{title:e("settings.metricsDashboard.sessionMetricsTitle"),open:!!D,onCancel:N,onOk:N,width:960,destroyOnClose:!0,children:L?t.jsx(_t,{children:e("settings.metricsDashboard.loadingSessionDetails")}):_e?t.jsxs(A,{direction:"vertical",style:{width:"100%"},size:s.marginMD,children:[t.jsxs(Ae,{size:"small",bordered:!0,column:2,children:[t.jsx(Ae.Item,{label:e("settings.metricsDashboard.sessionDetail.sessionId"),span:2,children:_e.session_id}),t.jsx(Ae.Item,{label:e("settings.metricsDashboard.sessionDetail.model"),children:_e.model}),t.jsx(Ae.Item,{label:e("settings.metricsDashboard.sessionDetail.status"),children:_e.status}),t.jsx(Ae.Item,{label:e("settings.metricsDashboard.sessionDetail.duration"),children:ms(_e.duration_ms)}),t.jsx(Ae.Item,{label:e("settings.metricsDashboard.sessionDetail.messages"),children:_e.message_count}),t.jsx(Ae.Item,{label:e("settings.metricsDashboard.sessionDetail.totalTokens"),children:as(_e.total_token_usage.total_tokens)}),t.jsx(Ae.Item,{label:e("settings.metricsDashboard.sessionDetail.toolCalls"),children:_e.tool_call_count})]}),t.jsx(ct,{rowKey:"round_id",size:"small",columns:Pe,dataSource:D.rounds,pagination:{pageSize:6,showSizeChanger:!1}})]}):t.jsx(_t,{type:"secondary",children:e("settings.metricsDashboard.noDetail")})})]})},{Text:ps}=ce,{useToken:Qi}=fe,eo=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"},to=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},so=()=>{const{t:e}=te(),{token:s}=Qi(),[a,n]=At.useMessage(),[r,i]=o.useState(!1),[l,c]=o.useState(!0),[d,u]=o.useState("placeholder"),g=o.useMemo(()=>[{label:e("settings.hooksTab.mode.placeholder"),value:"placeholder"},{label:e("settings.hooksTab.mode.error"),value:"error"},{label:e("settings.hooksTab.mode.ocr"),value:"ocr"},{label:e("settings.hooksTab.mode.vision"),value:"vision"}],[e]),j=o.useCallback(async()=>{i(!0);try{const _=await Fe.getBambooConfig();c(to(_)),u(eo(_))}catch(_){a.error(_ instanceof Error?_.message:e("settings.hooksTab.loadFailed"))}finally{i(!1)}},[a,e]),h=o.useCallback(async(_,F)=>{await Fe.setBambooConfig({hooks:{image_fallback:{enabled:_,mode:F}}})},[]),S=o.useCallback(async _=>{i(!0);try{await h(_,d),a.success(e(_?"settings.hooksTab.enabled":"settings.hooksTab.disabled")),await j()}catch(F){a.error(F instanceof Error?F.message:e("settings.hooksTab.updateFailed"))}finally{i(!1)}},[j,d,a,h,e]),k=o.useCallback(async _=>{var F;i(!0);try{await h(l,_),a.success(e("settings.hooksTab.modeUpdated",{mode:((F=g.find(M=>M.value===_))==null?void 0:F.label)??_})),await j()}catch(M){a.error(M instanceof Error?M.message:e("settings.hooksTab.modeUpdateFailed"))}finally{i(!1)}},[l,j,g,a,h,e]);return o.useEffect(()=>{j()},[j]),t.jsxs(W,{vertical:!0,gap:s.marginLG,children:[n,t.jsx(z,{size:"small",loading:r,children:t.jsxs(W,{vertical:!0,gap:s.marginXS,children:[t.jsx(ps,{strong:!0,children:e("settings.hooksTab.title")}),t.jsxs(W,{align:"center",justify:"space-between",children:[t.jsx(ps,{children:e("settings.hooksTab.enableImagePreflight")}),t.jsx(me,{checked:l,onChange:S})]}),t.jsxs(W,{align:"center",justify:"space-between",children:[t.jsx(ps,{children:e("settings.hooksTab.modeLabel")}),t.jsx(Q,{style:{width:180},value:d,options:g,onChange:k,disabled:!l})]}),t.jsx(ps,{type:"secondary",style:{fontSize:s.fontSizeSM},children:e("settings.hooksTab.description")})]})})]})};function ke(e){return String(e??"").trim()||void 0}function on(e){return{type:"interval",every_seconds:e}}function ao(e){const s=ke(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 Oa(e){switch(e.trigger_type){case"interval":{const s=Number(e.interval_seconds||0);return s<=0?{errorKey:"settings.schedulesTab.validation.intervalRequired"}:{trigger:on(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}=ao(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=ke(e.cron_expr);return s?{trigger:{type:"cron",expr:s}}:{errorKey:"settings.schedulesTab.validation.cronRequired"}}default:return{errorKey:"settings.schedulesTab.validation.triggerRequired"}}}function La(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:Ce}=ce,st=ea.getInstance();function no(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 ro=[{label:ae.t("settings.schedulesTab.weekdays.mon"),value:"mon"},{label:ae.t("settings.schedulesTab.weekdays.tue"),value:"tue"},{label:ae.t("settings.schedulesTab.weekdays.wed"),value:"wed"},{label:ae.t("settings.schedulesTab.weekdays.thu"),value:"thu"},{label:ae.t("settings.schedulesTab.weekdays.fri"),value:"fri"},{label:ae.t("settings.schedulesTab.weekdays.sat"),value:"sat"},{label:ae.t("settings.schedulesTab.weekdays.sun"),value:"sun"}];function io(e){return(e==null?void 0:e.type)==="interval"?e.every_seconds:null}function oo(e){switch(e.type){case"interval":return ae.t("settings.schedulesTab.triggerLabels.interval",{type:ae.t("settings.schedulesTab.triggerTypes.interval"),seconds:e.every_seconds});case"daily":return ae.t("settings.schedulesTab.triggerLabels.daily",{type:ae.t("settings.schedulesTab.triggerTypes.daily"),time:`${String(e.hour).padStart(2,"0")}:${String(e.minute).padStart(2,"0")}`});case"weekly":return ae.t("settings.schedulesTab.triggerLabels.weekly",{type:ae.t("settings.schedulesTab.triggerTypes.weekly"),weekdays:e.weekdays.join(", ")});case"monthly":return ae.t("settings.schedulesTab.triggerLabels.monthly",{type:ae.t("settings.schedulesTab.triggerTypes.monthly"),days:e.days.join(", ")});case"cron":return ae.t("settings.schedulesTab.triggerLabels.cron",{type:ae.t("settings.schedulesTab.triggerTypes.cron"),expr:e.expr})}}function lo(e){switch(e==null?void 0:e.type){case"skip":return ae.t("settings.schedulesTab.misfirePolicyOptions.skip");case"catch_up_all":return ae.t("settings.schedulesTab.misfirePolicyOptions.catchUpAll");case"catch_up_window":return ae.t("settings.schedulesTab.misfirePolicyOptions.catchUpWindow");case"run_once":default:return ae.t("settings.schedulesTab.misfirePolicyOptions.runOnce")}}function co(e){switch(e){case"allow":return ae.t("settings.schedulesTab.overlapPolicyOptions.allow");case"skip":return ae.t("settings.schedulesTab.overlapPolicyOptions.skip");case"queue_one":default:return ae.t("settings.schedulesTab.overlapPolicyOptions.queueOne")}}function uo(e){var s;return(s=e.state)!=null&&s.next_fire_at?String(e.state.next_fire_at):"-"}function go(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 mo(e){var s,a,n,r;return((s=e.state)==null?void 0:s.running_run_count)>0?{color:"processing",label:ae.t("settings.schedulesTab.statusLabels.running"),detail:ae.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:ae.t("settings.schedulesTab.statusLabels.queued"),detail:ae.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:ae.t("settings.schedulesTab.statusLabels.failing"),detail:ae.t("settings.schedulesTab.statusDetails.consecutiveFailures",{count:e.state.consecutive_failures})}:e.enabled?(r=e.state)!=null&&r.last_success_at?{color:"success",label:ae.t("settings.schedulesTab.statusLabels.healthy"),detail:ae.t("settings.schedulesTab.statusDetails.lastRunSucceeded")}:{color:"default",label:ae.t("settings.schedulesTab.statusLabels.idle")}:{color:"default",label:ae.t("settings.schedulesTab.statusLabels.disabled")}}function po(e){var a,n,r,i,l,c,d,u;const s={name:e.name,enabled:e.enabled,trigger_type:e.trigger.type,timezone:e.timezone||"",start_at:e.start_at||"",end_at:e.end_at||"",misfire_policy:((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:((i=e.run_config)==null?void 0:i.model)||"",workspace_path:((l=e.run_config)==null?void 0:l.workspace_path)||"",enhance_prompt:((c=e.run_config)==null?void 0:c.enhance_prompt)||"",auto_execute:!!((d=e.run_config)!=null&&d.auto_execute)};switch(((u=e.misfire_policy)==null?void 0:u.type)==="catch_up_window"&&(s.catch_up_window_max_runs=e.misfire_policy.max_catch_up_runs,s.catch_up_window_max_lateness_seconds=e.misfire_policy.max_lateness_seconds),e.trigger.type){case"interval":s.interval_seconds=e.trigger.every_seconds;break;case"daily":s.daily_hour=e.trigger.hour,s.daily_minute=e.trigger.minute;break;case"weekly":s.weekly_weekdays=e.trigger.weekdays,s.weekly_hour=e.trigger.hour,s.weekly_minute=e.trigger.minute;break;case"monthly":s.monthly_days=e.trigger.days.join(", "),s.monthly_hour=e.trigger.hour,s.monthly_minute=e.trigger.minute;break;case"cron":s.cron_expr=e.trigger.expr;break}return s}function qs({hourName:e,minuteName:s}){const{t:a}=te();return t.jsxs(W,{gap:12,wrap:"wrap",children:[t.jsx(v.Item,{label:a("settings.schedulesTab.form.dailyHour"),name:e,style:{width:180},children:t.jsx(Me,{min:0,max:23,style:{width:"100%"}})}),t.jsx(v.Item,{label:a("settings.schedulesTab.form.dailyMinute"),name:s,style:{width:180},children:t.jsx(Me,{min:0,max:59,style:{width:"100%"}})})]})}function ho(){const{t:e}=te(),[s,a]=At.useMessage(),[n,r]=o.useState(!1),[i,l]=o.useState([]),[c,d]=o.useState({open:!1,scheduleId:null,sessions:[],loading:!1}),[u,g]=o.useState({open:!1,scheduleId:null,runs:[],loading:!1}),[j,h]=o.useState({open:!1,schedule:null,saving:!1}),S=Js(f=>f.close),[k]=v.useForm(),[_]=v.useForm(),F=v.useWatch("trigger_type",k),M=v.useWatch("misfire_policy",k),w=v.useWatch("trigger_type",_),D=v.useWatch("misfire_policy",_),m=o.useCallback(async()=>{r(!0);try{const f=await st.listSchedules();l(f.schedules||[])}catch(f){console.error("[Schedules] Failed to load schedules:",f),s.error(e("settings.schedulesTab.loadFailed"))}finally{r(!1)}},[s,e]),x=o.useCallback(async(f,b,E)=>{try{await E()}catch(I){console.error(`[Schedules] ${f}:`,I),s.error(e(b))}},[s,e]);o.useEffect(()=>{m()},[m]);const L=[{value:"interval",label:e("settings.schedulesTab.triggerTypes.interval")},{value:"daily",label:e("settings.schedulesTab.triggerTypes.daily")},{value:"weekly",label:e("settings.schedulesTab.triggerTypes.weekly")},{value:"monthly",label:e("settings.schedulesTab.triggerTypes.monthly")},{value:"cron",label:e("settings.schedulesTab.triggerTypes.cron")}],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")}],K=[{value:"queue_one",label:e("settings.schedulesTab.overlapPolicyOptions.queueOne")},{value:"skip",label:e("settings.schedulesTab.overlapPolicyOptions.skip")},{value:"allow",label:e("settings.schedulesTab.overlapPolicyOptions.allow")}],Z=(f,b)=>t.jsxs(t.Fragment,{children:[t.jsxs(W,{gap:12,wrap:"wrap",children:[t.jsx(v.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(v.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(Q,{options:L})}),t.jsx(v.Item,{label:e("settings.schedulesTab.form.enabled"),name:"enabled",valuePropName:"checked",style:{width:120},children:t.jsx(me,{})})]}),f==="interval"?t.jsx(v.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(Me,{min:1,style:{width:"100%"}})}):null,f==="daily"?t.jsx(qs,{hourName:"daily_hour",minuteName:"daily_minute"}):null,f==="weekly"?t.jsxs(t.Fragment,{children:[t.jsx(v.Item,{label:e("settings.schedulesTab.form.weeklyWeekdays"),name:"weekly_weekdays",style:{minWidth:320},children:t.jsx(Q,{mode:"multiple",options:ro})}),t.jsx(qs,{hourName:"weekly_hour",minuteName:"weekly_minute"})]}):null,f==="monthly"?t.jsxs(t.Fragment,{children:[t.jsx(v.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(qs,{hourName:"monthly_hour",minuteName:"monthly_minute"})]}):null,f==="cron"?t.jsx(v.Item,{label:e("settings.schedulesTab.form.cronExpr"),name:"cron_expr",children:t.jsx(H,{placeholder:e("settings.schedulesTab.form.cronExprPlaceholder")})}):null,t.jsxs(W,{gap:12,wrap:"wrap",children:[t.jsx(v.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(v.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(v.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(W,{gap:12,wrap:"wrap",children:[t.jsx(v.Item,{label:e("settings.schedulesTab.form.misfirePolicy"),name:"misfire_policy",style:{flex:"1 1 240px"},children:t.jsx(Q,{options:P})}),t.jsx(v.Item,{label:e("settings.schedulesTab.form.overlapPolicy"),name:"overlap_policy",style:{flex:"1 1 240px"},children:t.jsx(Q,{options:K})})]}),b==="catch_up_window"?t.jsxs(W,{gap:12,wrap:"wrap",children:[t.jsx(v.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxRuns"),name:"catch_up_window_max_runs",style:{width:220},children:t.jsx(Me,{min:1,style:{width:"100%"}})}),t.jsx(v.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxLatenessSeconds"),name:"catch_up_window_max_lateness_seconds",style:{width:260},children:t.jsx(Me,{min:1,style:{width:"100%"}})})]}):null,t.jsx(v.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(v.Item,{label:e("settings.schedulesTab.form.systemPrompt"),name:"system_prompt",children:t.jsx(H.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})}),t.jsxs(W,{gap:12,wrap:"wrap",children:[t.jsx(v.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(v.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(v.Item,{label:e("settings.schedulesTab.form.autoExecute"),name:"auto_execute",valuePropName:"checked",style:{width:160},children:t.jsx(me,{})})]}),t.jsx(v.Item,{label:e("settings.schedulesTab.form.enhancePrompt"),name:"enhance_prompt",children:t.jsx(H.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})})]}),N=o.useMemo(()=>[{title:e("settings.schedulesTab.columns.name"),key:"name",render:(f,b)=>t.jsxs(W,{vertical:!0,gap:6,children:[t.jsx(Ce,{strong:!0,children:b.name}),t.jsxs(W,{gap:6,wrap:"wrap",children:[t.jsx(re,{children:oo(b.trigger)}),b.timezone?t.jsx(re,{color:"blue",children:b.timezone}):null,t.jsx(re,{children:lo(b.misfire_policy)}),t.jsx(re,{children:co(b.overlap_policy)})]})]})},{title:e("settings.schedulesTab.columns.status"),key:"status",render:(f,b)=>{const E=mo(b);return t.jsxs(W,{vertical:!0,gap:4,children:[t.jsx(re,{color:E.color,children:E.label}),E.detail?t.jsx(Ce,{type:"secondary",children:E.detail}):null]})}},{title:e("settings.schedulesTab.columns.activity"),key:"activity",render:(f,b)=>{var E,I,R,B;return t.jsxs(W,{vertical:!0,gap:2,children:[t.jsx(Ce,{type:"secondary",children:e("settings.schedulesTab.activityLabels.queued",{count:((E=b.state)==null?void 0:E.queued_run_count)??0})}),t.jsx(Ce,{type:"secondary",children:e("settings.schedulesTab.activityLabels.running",{count:((I=b.state)==null?void 0:I.running_run_count)??0})}),t.jsx(Ce,{type:"secondary",children:e("settings.schedulesTab.activityLabels.ok",{count:((R=b.state)==null?void 0:R.total_success_count)??0})}),t.jsx(Ce,{type:"secondary",children:e("settings.schedulesTab.activityLabels.fail",{count:((B=b.state)==null?void 0:B.total_failure_count)??0})})]})}},{title:e("settings.schedulesTab.columns.nextRun"),key:"next_run_at",render:(f,b)=>t.jsx(Ce,{type:"secondary",children:uo(b)})},{title:e("settings.schedulesTab.columns.lastRun"),key:"last_run_at",render:(f,b)=>t.jsx(Ce,{type:"secondary",children:go(b)})},{title:e("settings.schedulesTab.columns.autoExecute"),key:"auto_execute",render:(f,b)=>{var E,I;return t.jsx(Ce,{type:(E=b.run_config)!=null&&E.auto_execute?void 0:"secondary",children:(I=b.run_config)!=null&&I.auto_execute?e("settings.schedulesTab.yes"):e("settings.schedulesTab.no")})}},{title:e("settings.schedulesTab.columns.model"),key:"model",render:(f,b)=>{var E;return t.jsx(Ce,{type:"secondary",children:(E=b.run_config)!=null&&E.model?String(b.run_config.model):"-"})}},{title:e("settings.schedulesTab.columns.enabled"),key:"enabled",render:(f,b)=>t.jsx(me,{checked:b.enabled,onChange:async E=>{await x("Failed to toggle","settings.schedulesTab.updateFailed",async()=>{await st.patchSchedule(b.id,{enabled:E}),await m()})}})},{title:e("settings.schedulesTab.columns.actions"),key:"actions",render:(f,b)=>{const E=t.jsx(Me,{min:1,value:io(b.trigger)??void 0,disabled:b.trigger.type!=="interval",onChange:async I=>{const R=typeof I=="number"?I:null;!R||R<=0||await x("Failed to patch interval","settings.schedulesTab.updateFailed",async()=>{await st.patchSchedule(b.id,{trigger:on(R)}),await m()})}});return t.jsxs(W,{vertical:!0,gap:8,children:[t.jsxs(W,{gap:8,wrap:"wrap",children:[t.jsx(O,{size:"small",onClick:()=>{h({open:!0,schedule:b,saving:!1}),_.setFieldsValue(po(b))},children:e("settings.schedulesTab.actions.edit")}),t.jsx(O,{size:"small",onClick:async()=>{await x("Failed to run now","settings.schedulesTab.runNowFailed",async()=>{await st.runScheduleNow(b.id),s.success(e("settings.schedulesTab.enqueuedRun")),await m()})},children:e("settings.schedulesTab.actions.runNow")}),t.jsx(O,{size:"small",onClick:async()=>{d(I=>({...I,open:!0,scheduleId:b.id,loading:!0,sessions:[]}));try{const I=await st.listScheduleSessions(b.id);d(R=>({...R,open:!0,scheduleId:b.id,loading:!1,sessions:(I.sessions||[]).map(B=>({id:B.id,title:B.title,updated_at:B.updated_at}))}))}catch(I){console.error("[Schedules] Failed to list sessions:",I),s.error(e("settings.schedulesTab.loadSessionsFailed")),d(R=>({...R,loading:!1}))}},children:e("settings.schedulesTab.actions.sessions")}),t.jsx(O,{size:"small",onClick:async()=>{g(I=>({...I,open:!0,scheduleId:b.id,loading:!0,runs:[]}));try{const I=await st.listScheduleRuns(b.id);g(R=>({...R,open:!0,scheduleId:b.id,loading:!1,runs:I.runs||[]}))}catch(I){console.error("[Schedules] Failed to list runs:",I),s.error(e("settings.schedulesTab.loadRunsFailed")),g(R=>({...R,loading:!1}))}},children:e("settings.schedulesTab.actions.runs")}),t.jsx(O,{danger:!0,size:"small",onClick:async()=>{await x("Failed to delete","settings.schedulesTab.deleteFailed",async()=>{await st.deleteSchedule(b.id),s.success(e("settings.schedulesTab.deleted")),await m()})},children:e("settings.schedulesTab.actions.delete")})]}),t.jsxs(W,{gap:8,align:"center",wrap:"wrap",children:[t.jsx(Ce,{type:"secondary",children:e("settings.schedulesTab.columns.intervalSeconds")}),b.trigger.type==="interval"?E:t.jsx(ve,{title:e("settings.schedulesTab.nonIntervalReadOnly"),children:t.jsx("span",{children:E})})]})]})}}],[_,s,m,x,e]);return t.jsxs(W,{vertical:!0,gap:16,children:[a,t.jsx(z,{title:e("settings.schedulesTab.createTitle"),className:"lotus-settings-card",children:t.jsxs(v,{form:k,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 f=>{try{const b=!!f.auto_execute,E=ke(f.task_message),I=ke(f.model);if(b&&!E){s.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:R,errorKey:B}=Oa(f);if(!R){s.error(e(B||"settings.schedulesTab.validation.triggerRequired"));return}await st.createSchedule({name:String(f.name||"").trim(),trigger:R,timezone:ke(f.timezone),start_at:ke(f.start_at),end_at:ke(f.end_at),misfire_policy:La(f),overlap_policy:f.overlap_policy,enabled:!!f.enabled,run_config:{system_prompt:ke(f.system_prompt),task_message:E,model:I,workspace_path:ke(f.workspace_path),enhance_prompt:ke(f.enhance_prompt),auto_execute:b}}),s.success(e("settings.schedulesTab.created")),k.resetFields(),await m()}catch(b){console.error("[Schedules] Failed to create schedule:",b),s.error(e("settings.schedulesTab.createFailed"))}},children:[Z(F,M),t.jsx(O,{type:"primary",htmlType:"submit",children:e("settings.schedulesTab.actions.create")})]})}),t.jsx(z,{title:e("settings.schedulesTab.listTitle"),className:"lotus-settings-card",extra:t.jsx(O,{onClick:()=>void m(),loading:n,children:e("settings.schedulesTab.actions.refresh")}),children:t.jsx(ct,{rowKey:"id",columns:N,dataSource:i,loading:n,pagination:{pageSize:10},scroll:{x:1500}})}),t.jsx(lt,{title:e("settings.schedulesTab.scheduleSessionsTitle"),open:c.open,onCancel:()=>d(f=>({...f,open:!1,scheduleId:null})),footer:null,children:c.loading?t.jsx(Ce,{type:"secondary",children:e("settings.schedulesTab.loading")}):t.jsx(W,{vertical:!0,gap:8,children:c.sessions.length===0?t.jsx(Ce,{type:"secondary",children:e("settings.schedulesTab.noSessionsYet")}):c.sessions.map(f=>t.jsxs(W,{justify:"space-between",align:"center",children:[t.jsxs(W,{vertical:!0,style:{minWidth:0},children:[t.jsx(Ce,{strong:!0,ellipsis:!0,children:f.title}),t.jsxs(Ce,{type:"secondary",ellipsis:!0,children:[f.id," • ",f.updated_at]})]}),t.jsx(O,{size:"small",onClick:()=>{Tn(f.id,{forceRefreshIndex:!0,forceLoadHistory:!0,subscribeIfRunning:!0,forceSubscribe:!0}),S()},children:e("settings.schedulesTab.actions.open")})]},f.id))})}),t.jsx(lt,{title:e("settings.schedulesTab.scheduleRunsTitle"),open:u.open,onCancel:()=>g(f=>({...f,open:!1,scheduleId:null})),footer:null,width:960,children:u.loading?t.jsx(Ce,{type:"secondary",children:e("settings.schedulesTab.loading")}):u.runs.length===0?t.jsx(Ce,{type:"secondary",children:e("settings.schedulesTab.noRunsYet")}):t.jsx(ct,{rowKey:"run_id",pagination:{pageSize:8},dataSource:u.runs,columns:[{title:e("settings.schedulesTab.runHistory.columns.status"),key:"status",render:(f,b)=>t.jsx(re,{color:no(b.status),children:b.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:(f,b)=>b.started_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.completedAt"),key:"completed_at",render:(f,b)=>b.completed_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.session"),key:"session_id",render:(f,b)=>b.session_id||"-"},{title:e("settings.schedulesTab.runHistory.columns.duration"),key:"execution_duration_ms",render:(f,b)=>b.execution_duration_ms!=null?`${b.execution_duration_ms}ms`:"-"},{title:e("settings.schedulesTab.runHistory.columns.outcome"),key:"outcome_reason",render:(f,b)=>b.outcome_reason||(b.was_catch_up?"catch-up":"-")}]})}),t.jsx(lt,{title:e("settings.schedulesTab.editTitle"),open:j.open,onCancel:()=>h({open:!1,schedule:null,saving:!1}),okText:e("settings.schedulesTab.actions.save"),confirmLoading:j.saving,onOk:()=>_.submit(),forceRender:!0,children:t.jsx(v,{form:_,layout:"vertical",onFinish:async f=>{const b=j.schedule;if(!b)return;const E=!!f.auto_execute,I=ke(f.task_message),R=ke(f.model);if(E&&!I){s.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:B,errorKey:se}=Oa(f);if(!B){s.error(e(se||"settings.schedulesTab.validation.triggerRequired"));return}h(G=>({...G,saving:!0}));try{await st.patchSchedule(b.id,{name:String(f.name||"").trim()||void 0,enabled:!!f.enabled,trigger:B,timezone:ke(f.timezone),start_at:ke(f.start_at),end_at:ke(f.end_at),misfire_policy:La(f),overlap_policy:f.overlap_policy,run_config:{system_prompt:ke(f.system_prompt),task_message:I,model:R,workspace_path:ke(f.workspace_path),enhance_prompt:ke(f.enhance_prompt),auto_execute:E}}),s.success(e("settings.schedulesTab.updated")),h({open:!1,schedule:null,saving:!1}),await m()}catch(G){console.error("[Schedules] Failed to patch schedule:",G),s.error(e("settings.schedulesTab.updateFailed")),h(ge=>({...ge,saving:!1}))}},children:Z(w,D)})})]})}const{Text:Wt}=ce,Gt=ea.getInstance();function fo(){const{t:e}=te(),{modal:s,message:a}=Ft.useApp(),n=Ue(k=>k.chats),r=Ue(k=>k.currentSessionId),i=Ue(k=>k.refreshChats),l=Ue(k=>k.loadChats),c=Ue(k=>k.loadChatHistory),[d,u]=o.useState(!0),[g,j]=o.useState(!1),h=o.useMemo(()=>r?n.find(k=>k.id===r)??null:null,[n,r]),S=async k=>{if(!g){j(!0);try{await k()}finally{j(!1)}}};return t.jsxs(W,{vertical:!0,gap:16,children:[t.jsx(z,{size:"small",title:e("settings.sessionsTab.currentSessionTitle"),children:h?t.jsxs(W,{vertical:!0,gap:4,children:[t.jsx(Wt,{strong:!0,ellipsis:!0,children:h.title}),t.jsxs(Wt,{type:"secondary",ellipsis:!0,children:[e("settings.sessionsTab.id"),": ",h.id," ","•"," ",e("settings.sessionsTab.kind"),": ",h.kind]}),t.jsx(W,{gap:8,wrap:"wrap",style:{marginTop:8},children:t.jsx(O,{danger:!0,loading:g,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 S(async()=>{await Gt.clearSession(h.id),await c(h.id),await i(),a.success(e("settings.sessionsTab.sessionCleared"))})}})},children:e("settings.sessionsTab.clearMessages")})})]}):t.jsx(Wt,{type:"secondary",children:e("settings.sessionsTab.noActiveSession")})}),t.jsxs(z,{size:"small",title:e("settings.sessionsTab.bulkCleanupTitle"),children:[t.jsxs(W,{align:"center",gap:8,style:{marginBottom:12},children:[t.jsx(Wt,{children:e("settings.sessionsTab.keepPinned")}),t.jsx(me,{checked:d,onChange:u})]}),t.jsxs(W,{gap:8,wrap:"wrap",children:[t.jsx(O,{danger:!0,loading:g,onClick:()=>{s.confirm({title:e("settings.sessionsTab.deleteAllTitle"),content:e(d?"settings.sessionsTab.deleteAllKeepPinned":"settings.sessionsTab.deleteAllIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await S(async()=>{await Gt.cleanupSessions("all",d),await l(),a.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteAll")}),t.jsx(O,{danger:!0,loading:g,onClick:()=>{s.confirm({title:e("settings.sessionsTab.deleteEmptyTitle"),content:e(d?"settings.sessionsTab.deleteEmptyKeepPinned":"settings.sessionsTab.deleteEmptyIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await S(async()=>{await Gt.cleanupSessions("empty",d),await l(),a.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteEmpty")}),t.jsx(O,{danger:!0,loading:g,onClick:()=>{s.confirm({title:e("settings.sessionsTab.deleteChildrenTitle"),content:e(d?"settings.sessionsTab.deleteChildrenKeepPinned":"settings.sessionsTab.deleteChildrenIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await S(async()=>{await Gt.cleanupSessions("children",d),await l(),a.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteChildren")})]})]}),t.jsxs(z,{size:"small",title:e("settings.sessionsTab.devResetTitle"),children:[t.jsx(Wt,{type:"secondary",children:e("settings.sessionsTab.devResetDescription")}),t.jsx(W,{style:{marginTop:12},children:t.jsx(O,{danger:!0,type:"primary",loading:g,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 S(async()=>{await Gt.devResetSessions(),await l(),a.success(e("settings.sessionsTab.devResetDone"))})}})},children:e("settings.sessionsTab.devResetAction")})})]})]})}const{Text:at}=ce,{useToken:yo}=fe,xo=()=>{const{t:e}=te(),{token:s}=yo(),[a,n]=o.useState(ca()),r=jn(),i=(l,c)=>{const d={...a,[l]:c};n(d),Sn({[l]:c})};return o.useEffect(()=>{n(ca())},[]),t.jsx(z,{size:"small",className:"lotus-settings-card",children:t.jsxs(W,{vertical:!0,gap:s.marginMD,children:[!r&&t.jsx(Ve,{type:"info",showIcon:!0,message:e("settings.notificationsTab.desktopOnly","Desktop notifications are only available in the Bodhi desktop app.")}),t.jsxs(W,{align:"center",gap:s.marginSM,children:[t.jsx(qn,{}),t.jsx(at,{strong:!0,children:e("settings.notificationsTab.title","Desktop Notifications")})]}),t.jsx(at,{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(Re,{style:{margin:`${s.marginXS}px 0`}}),t.jsxs(W,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(at,{children:e("settings.notificationsTab.enabled","Enable desktop notifications")}),t.jsx(me,{"data-testid":"notification-enabled-toggle",checked:a.enabled,onChange:l=>i("enabled",l),disabled:!r})]}),t.jsx(Re,{style:{margin:`${s.marginXS}px 0`}}),t.jsx(at,{strong:!0,style:{fontSize:s.fontSizeSM,opacity:a.enabled?1:.5},children:e("settings.notificationsTab.events","Notify when:")}),t.jsxs(W,{vertical:!0,gap:s.marginSM,style:{opacity:a.enabled?1:.5,pointerEvents:a.enabled?"auto":"none"},children:[t.jsxs(W,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(at,{children:e("settings.notificationsTab.onClarification","Agent needs clarification")}),t.jsx(me,{"data-testid":"notification-clarification-toggle",checked:a.onClarification,onChange:l=>i("onClarification",l),disabled:!r})]}),t.jsxs(W,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(at,{children:e("settings.notificationsTab.onToolApproval","Tool execution needs approval")}),t.jsx(me,{"data-testid":"notification-tool-approval-toggle",checked:a.onToolApproval,onChange:l=>i("onToolApproval",l),disabled:!r})]}),t.jsxs(W,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(at,{children:e("settings.notificationsTab.onContextPressure","Context window is critically full")}),t.jsx(me,{"data-testid":"notification-context-pressure-toggle",checked:a.onContextPressure,onChange:l=>i("onContextPressure",l),disabled:!r})]}),t.jsxs(W,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(at,{children:e("settings.notificationsTab.onSubAgentComplete","Background task completes")}),t.jsx(me,{"data-testid":"notification-subagent-complete-toggle",checked:a.onSubAgentComplete,onChange:l=>i("onSubAgentComplete",l),disabled:!r})]})]}),t.jsx(Re,{style:{margin:`${s.marginXS}px 0`}}),t.jsxs(W,{align:"center",gap:s.marginSM,children:[t.jsx(Un,{style:{color:s.colorPrimary}}),t.jsx(at,{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:hs,Paragraph:bo}=ce,ln=({open:e,onCancel:s,onComplete:a,onCopyCode:n,completingAuth:r,copiedUserCode:i,deviceCodeInfo:l,timeRemaining:c,token:d})=>{const{t:u}=te();return t.jsx(lt,{title:u("settings.providerTab.copilotAuthModalTitle"),open:e,onCancel:s,footer:[t.jsx(O,{onClick:s,children:u("settings.providerTab.cancel")},"cancel"),t.jsx(O,{type:"primary",onClick:a,loading:r,children:u("settings.providerTab.completedAuthorization")},"complete")],children:l&&t.jsxs(A,{direction:"vertical",size:"large",style:{width:"100%"},children:[t.jsx(Ve,{message:u("settings.providerTab.browserOpened"),description:t.jsxs("ol",{children:[t.jsx("li",{children:u("settings.providerTab.authStep1")}),t.jsx("li",{children:u("settings.providerTab.authStep2")}),t.jsx("li",{children:u("settings.providerTab.authStep3")})]}),type:"info"}),t.jsx(z,{size:"small",className:"lotus-settings-card",children:t.jsxs(A,{direction:"vertical",style:{width:"100%"},children:[t.jsx(hs,{type:"secondary",children:u("settings.providerTab.visitUrl")}),t.jsx(A,{children:t.jsx(hs,{copyable:{text:l.verification_uri},children:l.verification_uri})})]})}),t.jsx(z,{style:{textAlign:"center",background:d.colorFillTertiary,borderColor:d.colorBorderSecondary},children:t.jsxs(A,{direction:"vertical",style:{width:"100%"},children:[t.jsx(hs,{type:"secondary",children:u("settings.providerTab.enterCode")}),t.jsxs(A,{children:[t.jsx(hs,{style:{color:d.colorText,fontSize:"32px",fontFamily:"monospace",fontWeight:"bold",letterSpacing:"4px"},children:l.user_code}),t.jsx(O,{icon:i?t.jsx(Xs,{}):t.jsx(Xa,{}),onClick:n,type:i?"default":"primary",children:u(i?"settings.providerTab.copied":"settings.providerTab.copyCode")})]}),t.jsx("div",{style:{marginTop:8},children:t.jsxs(re,{color:c<60?"error":c<180?"warning":"success",children:[t.jsx(Hn,{style:{marginRight:4}}),"Expires in ",Math.floor(c/60),":",(c%60).toString().padStart(2,"0")]})})]})}),t.jsx(bo,{type:"secondary",children:u("settings.providerTab.afterContinueHint")})]})})},vo=new Set(["id","type","provider_type","label","enabled","api_key_encrypted"]),Na=e=>e?Object.fromEntries(Object.entries(e).filter(([s])=>!vo.has(s))):{},{Password:Va}=H,{Text:mt,Paragraph:Us}=ce,To=["low","medium","high","xhigh","max"],Jt=(e,s)=>t.jsx(Q,{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:To.map(a=>t.jsx(Q.Option,{value:a,children:e(`chat.input.reasoning.${a}`)},a))}),$a=e=>t.jsx(v.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(Q,{mode:"tags",tokenSeparators:[","," ",`
|
|
3
|
+
`," "],placeholder:e("settings.providerTab.responsesOnlyModelsPlaceholder"),allowClear:!0})}),jo=e=>Array.isArray(e)?e.map(s=>typeof s=="string"?s.trim():"").filter(s=>!!s):[],So=({type:e})=>{const{t:s}=te();if(!e)return null;switch(e){case"openai":return t.jsxs(t.Fragment,{children:[t.jsx(v.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(ft,{})})}),t.jsx(v.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(v.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Jt(s)}),$a(s)]});case"anthropic":return t.jsxs(t.Fragment,{children:[t.jsx(v.Item,{name:"api_key",label:s("settings.providerTab.anthropicApiKey"),rules:[{required:!0,message:s("settings.providerTab.anthropicApiKeyRequired")}],children:t.jsx(Va,{placeholder:s("settings.providerTab.anthropicApiKeyPlaceholder","sk-ant-..."),prefix:t.jsx(ft,{})})}),t.jsx(v.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(v.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(v.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Jt(s)})]});case"gemini":return t.jsxs(t.Fragment,{children:[t.jsx(v.Item,{name:"api_key",label:s("settings.providerTab.geminiApiKey"),rules:[{required:!0,message:s("settings.providerTab.geminiApiKeyRequired")}],children:t.jsx(Va,{placeholder:s("settings.providerTab.geminiApiKeyPlaceholder","AIza..."),prefix:t.jsx(ft,{})})}),t.jsx(v.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(v.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Jt(s)})]});case"copilot":return t.jsxs(t.Fragment,{children:[t.jsx(v.Item,{name:"headless_auth",label:s("settings.providerTab.headlessAuth"),valuePropName:"checked",extra:s("settings.providerTab.headlessAuthHelp"),children:t.jsx(me,{})}),t.jsx(v.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Jt(s)}),$a(s)]});case"bodhi":return t.jsxs(t.Fragment,{children:[t.jsx(v.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(ft,{})})}),t.jsx(v.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(v.Item,{name:"target_provider",label:s("settings.providerTab.targetProvider"),extra:s("settings.providerTab.targetProviderExtra"),children:t.jsxs(Q,{placeholder:s("settings.providerTab.targetProviderPlaceholder","openai"),allowClear:!0,children:[t.jsx(Q.Option,{value:"openai",children:"OpenAI"}),t.jsx(Q.Option,{value:"anthropic",children:"Anthropic"}),t.jsx(Q.Option,{value:"gemini",children:"Gemini"})]})}),t.jsx(v.Item,{name:"reasoning_effort",label:s("settings.providerTab.reasoningEffortOptional"),extra:s("settings.providerTab.reasoningEffortHelp"),children:Jt(s)})]});default:return null}},_o=({instances:e,defaultInstanceId:s,onInstancesChanged:a})=>{const{t:n}=te(),{message:r}=Ft.useApp(),{token:i}=fe.useToken(),[l]=v.useForm(),[c,d]=o.useState(!1),[u,g]=o.useState(null),[j,h]=o.useState(!1),[S,k]=o.useState(null),[_,F]=o.useState(void 0),[M,w]=o.useState(null),[D,m]=o.useState(!1),[x,L]=o.useState(!1),[P,K]=o.useState(0),[Z,N]=o.useState(!1),[f,b]=o.useState(!1),[E,I]=o.useState("unknown"),[R,B]=o.useState(!1),se=o.useCallback($=>({type:$.type,label:$.label,enabled:$.enabled,...Na($.config)}),[]),G=o.useCallback(()=>{g(null),F(void 0),d(!0)},[]),ge=async()=>{try{b(!0);const $=await Te.startCopilotAuth();w($),m(!0),K($.expires_in)}catch($){r.error(n("settings.providerTab.startCopilotAuthFailed","Failed to start Copilot authentication")),console.error("Failed to start Copilot authentication:",$)}finally{b(!1)}},he=async()=>{if(M)try{L(!0),await Te.completeCopilotAuth({device_code:M.device_code,interval:M.interval||5,expires_in:M.expires_in}),r.success(n("settings.providerTab.copilotAuthSuccess","Copilot authentication successful!")),m(!1),w(null),await C()}catch($){r.error(n("settings.providerTab.completeAuthFailed","Authentication completion failed")),console.error("Authentication completion failed:",$)}finally{L(!1)}},Ee=async()=>{if(M)try{await ta(M.user_code),N(!0),r.success(n("settings.providerTab.userCodeCopied","User code copied!")),setTimeout(()=>N(!1),2e3)}catch{r.error(n("settings.providerTab.copyCodeFailed","Failed to copy code"))}},C=o.useCallback(async()=>{try{B(!0);const $=await Te.getCopilotAuthStatus();I($.authenticated?"authenticated":"not_authenticated")}catch($){console.error("Failed to check Copilot auth status:",$),I("unknown")}finally{B(!1)}},[]);o.useEffect(()=>{c&&_==="copilot"&&C()},[C,c,_]);const J=o.useCallback($=>{if(!$){l.resetFields();return}if(u){l.setFieldsValue(se(u)),F(u.type);return}l.setFieldsValue({enabled:!0})},[se,u,l]),Y=($="small")=>t.jsx(z,{size:"small",title:n("settings.providerTab.copilotAuth","GitHub Copilot Authentication"),style:{marginTop:8},children:t.jsxs(A,{direction:"vertical",style:{width:"100%"},children:[t.jsxs(A,{children:[t.jsx(mt,{strong:!0,children:n("settings.providerTab.authStatus","Status:")}),E==="authenticated"?t.jsx(re,{color:"success",children:n("settings.providerTab.authenticated","Authenticated")}):E==="not_authenticated"?t.jsx(re,{color:"warning",children:n("settings.providerTab.notAuthenticated","Not Authenticated")}):t.jsx(re,{children:n("settings.providerTab.unknown","Unknown")}),t.jsx(O,{type:"text",size:"small",onClick:()=>void C(),loading:R,children:n("settings.providerTab.refreshStatus","Refresh")})]}),t.jsx(Us,{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(O,{type:"primary",icon:t.jsx(Ya,{}),onClick:()=>void ge(),loading:f,size:$,children:n("settings.providerTab.authenticateCopilot","Authenticate Copilot")})]})}),ee=o.useCallback($=>{g($),F($.type),d(!0)},[]),De=o.useCallback(async()=>{try{const $=await l.validateFields();h(!0);const{type:be,label:He,enabled:we,request_overrides_json:ze,..._e}=$,Ke=Na(_e);if("responses_only_models"in Ke&&(Ke.responses_only_models=jo(Ke.responses_only_models)),typeof ze=="string"&&ze.trim()&&(Ke.request_overrides=JSON.parse(ze)),u){const p={label:He,enabled:we,config:Ke};await Te.updateProviderInstance(u.id,p),r.success(n("settings.providerTab.instanceUpdated","Provider instance updated"))}else{const p={type:be,label:He||ht[be]||be,enabled:we??!0,config:Ke};await Te.createProviderInstance(p),r.success(n("settings.providerTab.instanceCreated","Provider instance created"))}d(!1),await a(),await Ze.getState().loadProviderInstances()}catch($){(xs($)||$ instanceof Error&&!Qa($))&&r.error($.message)}finally{h(!1)}},[u,l,r,a,n]),Pe=o.useCallback(async $=>{try{k($),await Te.deleteProviderInstance($),r.success(n("settings.providerTab.instanceDeleted","Provider instance deleted")),await a(),await Ze.getState().loadProviderInstances()}catch(be){r.error(xs(be)?be.message:n("settings.providerTab.instanceDeleteFailed","Failed to delete instance"))}finally{k(null)}},[a,r,n]),Be=o.useCallback(async $=>{try{await Te.setDefaultProviderInstance($),r.success(n("settings.providerTab.defaultInstanceSet","Default provider updated")),await a(),await Ze.getState().loadProviderInstances()}catch(be){r.error(xs(be)?be.message:n("settings.providerTab.defaultInstanceFailed","Failed to set default"))}},[a,r,n]),Je=o.useCallback(async()=>{await a()},[a]);return o.useEffect(()=>{Je()},[]),t.jsxs("div",{style:{marginBottom:16},children:[t.jsxs("div",{style:{marginBottom:12,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[t.jsx(mt,{strong:!0,children:n("settings.providerTab.providerInstances","Provider Instances")}),t.jsx(O,{type:"dashed",icon:t.jsx(Ct,{}),onClick:G,"data-testid":"add-provider-instance",children:n("settings.providerTab.addInstance","Add Provider")})]}),e.length===0&&t.jsx(Us,{type:"secondary",children:n("settings.providerTab.noInstances",'No provider instances configured. Click "Add Provider" to create one.')}),t.jsx(Ss,{ghost:!0,items:e.map($=>{const be=$.id===s,He=ht[$.type]||$.type;return{key:$.id,label:t.jsxs(A,{size:"small",children:[t.jsx("span",{style:{fontWeight:500},children:$.label||He}),t.jsx(re,{color:"processing",style:{fontSize:11},children:He}),be&&t.jsxs(re,{color:"gold",style:{fontSize:11},children:[t.jsx(Wn,{})," ",n("settings.providerTab.default","Default")]}),!$.enabled&&t.jsx(re,{color:"default",style:{fontSize:11},children:n("settings.providerTab.disabled","Disabled")})]}),extra:t.jsxs(A,{size:4,onClick:we=>we.stopPropagation(),children:[!be&&t.jsx(ve,{title:n("settings.providerTab.setDefault","Set as default"),children:t.jsx(O,{type:"text",size:"small",icon:t.jsx(Kn,{}),onClick:()=>void Be($.id)})}),t.jsx(O,{type:"text",size:"small",icon:t.jsx(ks,{}),onClick:()=>ee($)}),t.jsx(ts,{title:n("settings.providerTab.confirmDeleteInstance","Delete this provider instance?"),onConfirm:()=>void Pe($.id),okText:n("settings.providerTab.delete","Delete"),cancelText:n("settings.providerTab.cancel","Cancel"),children:t.jsx(O,{type:"text",size:"small",danger:!0,icon:t.jsx(ns,{}),loading:S===$.id})})]}),children:t.jsxs("div",{children:[t.jsxs(Us,{type:"secondary",style:{marginBottom:8},children:["ID: ",t.jsx(mt,{code:!0,children:$.id})," · Type: ",t.jsx(mt,{code:!0,children:$.type})]}),$.config&&Object.keys($.config).length>0&&t.jsx(z,{size:"small",style:{marginBottom:8},children:Object.entries($.config).map(([we,ze])=>we==="api_key"?t.jsxs("div",{style:{marginBottom:4},children:[t.jsxs(mt,{type:"secondary",children:[we,": "]}),t.jsx(mt,{children:"••••••••"})]},we):t.jsxs("div",{style:{marginBottom:4},children:[t.jsxs(mt,{type:"secondary",children:[we,": "]}),t.jsx(mt,{children:typeof ze=="object"?JSON.stringify(ze):String(ze)})]},we))}),$.type==="copilot"&&Y("small")]})}})}),t.jsx(lt,{open:c,title:u?n("settings.providerTab.editInstance","Edit Provider Instance"):n("settings.providerTab.createInstance","Create Provider Instance"),onCancel:()=>d(!1),onOk:()=>void De(),afterOpenChange:J,confirmLoading:j,width:560,forceRender:!0,destroyOnClose:!0,children:t.jsxs(v,{form:l,layout:"vertical",preserve:!1,children:[t.jsx(v.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(Q,{disabled:!!u,placeholder:n("settings.providerTab.selectType","Select provider type"),onChange:$=>F($),children:Object.entries(ht).map(([$,be])=>t.jsx(Q.Option,{value:$,children:be},$))})}),t.jsx(v.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(v.Item,{name:"enabled",label:n("settings.providerTab.enabled","Enabled"),valuePropName:"checked",initialValue:!0,children:t.jsx(me,{})}),t.jsx(Re,{children:n("settings.providerTab.instanceConfig","Configuration")}),t.jsx(v.Item,{noStyle:!0,shouldUpdate:!0,children:()=>t.jsx(So,{form:l,type:_})}),_==="copilot"&&Y("middle")]})}),t.jsx(ln,{open:D,onCancel:()=>m(!1),onComplete:()=>void he(),onCopyCode:()=>void Ee(),completingAuth:x,copiedUserCode:Z,deviceCodeInfo:M,timeRemaining:P,token:i})]})},{Password:Ba}=H,{Text:Ge,Paragraph:Hs}=ce,fs=["openai","anthropic","gemini","copilot","bodhi"],Et=()=>null,Ks=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()))},ko=(e,s,a)=>{const n=e;n[s]={...n[s]??{},model:a}},qa=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},Ua=(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},Ha=e=>t.jsxs(A,{direction:"vertical",size:4,children:[t.jsxs(Ge,{type:"secondary",children:[e("settings.providerTab.responsesOnlyHelp1")," ",t.jsx(Ge,{code:!0,children:"/responses"}),"."]}),t.jsx(Ge,{type:"secondary",children:e("settings.providerTab.responsesOnlyHelp2")})]}),wo=["low","medium","high","xhigh","max"],Dt=(e,s)=>t.jsx(Q,{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:wo.map(a=>t.jsx(Q.Option,{value:a,children:e(`chat.input.reasoning.${a}`)},a))}),Co=()=>{const{t:e}=te(),{token:s}=fe.useToken(),{message:a}=Ft.useApp(),[n]=v.useForm(),[r,i]=o.useState(!1),[l,c]=o.useState(!1),[d,u]=o.useState("copilot"),[g,j]=o.useState(!1),[h,S]=o.useState(null),[k,_]=o.useState(!1),[F,M]=o.useState(!1),[w,D]=o.useState(null),[m,x]=o.useState(!1),[L,P]=o.useState(!1),[K,Z]=o.useState(0),[N,f]=o.useState(!1),[b,E]=o.useState([]),[I,R]=o.useState(!1),[B,se]=o.useState([]),[G,ge]=o.useState(null),[he,Ee]=o.useState(!1),[C,J]=o.useState([]),[Y,ee]=o.useState("idle"),[De,Pe]=o.useState(null),Be=o.useCallback((y,T)=>{const X=y.instances??[],V=X.reduce((oe,ne)=>{const Ne={...ne.config};return Ne.request_overrides&&typeof Ne.request_overrides=="object"&&(Ne.request_overrides_json=JSON.stringify(Ne.request_overrides,null,2)),oe[ne.id]=Ne,oe},{});let U=y.defaults?{...y.defaults}:void 0;const ue=y.default_provider_instance_id??null,de=ue?X.find(oe=>oe.id===ue):void 0,xe=typeof(de==null?void 0:de.config.model)=="string"?de.config.model.trim():void 0;!Ks(U==null?void 0:U.chat)&&ue&&xe&&(U={...U||{},chat:{provider:ue,model:xe}});const Ie=T?qa(T):void 0,je=Ua(U,ue);return Ie&&!(U!=null&&U.memory_background)&&je&&(U={...U||{},memory_background:{provider:je,model:Ie}}),{defaults:U,features:y.features,providers:V}},[]),Je=o.useCallback((y,T)=>{se(y.instances??[]),ge(y.default_provider_instance_id??null),Ee(!0),n.setFieldsValue(Be(y,T)),j(!0)},[Be,n]),$=o.useCallback(y=>{if(!(y!=null&&y.trim()))return;const T=B.find(X=>X.id===y);return T?T.label||ht[T.type]:ht[y]||y},[B]),be=o.useCallback((y,T)=>{const X=new Set;y!=null&&y.trim()&&X.add(y);for(const V of fs){const U=T==null?void 0:T[V];U&&Object.keys(U).length>0&&X.add(V)}return Array.from(X)},[]);o.useEffect(()=>{if(Y!=="success")return;const y=setTimeout(()=>{ee("idle"),Pe(null)},2e3);return()=>clearTimeout(y)},[Y]),o.useEffect(()=>{if(!m||!w){Z(0);return}Z(w.expires_in);const y=setInterval(()=>{Z(T=>T<=1?(clearInterval(y),0):T-1)},1e3);return()=>clearInterval(y)},[m,w]);const He=o.useCallback(async()=>{var y;try{i(!0);const[T,X]=await Promise.all([Te.getProviderConfig(),nt.getInstance().getBambooConfig().catch(()=>({}))]);let V=T.defaults?{...T.defaults}:void 0;if(!((y=V==null?void 0:V.chat)!=null&&y.model)&&T.provider&&T.providers){const je=T.provider,oe=T.providers[je],ne=oe==null?void 0:oe.model;ne&&(V={...V||{},chat:{provider:je,model:ne}})}const U=qa(X),ue=Ua(V,T.provider||null);U&&!(V!=null&&V.memory_background)&&ue&&(V={...V||{},memory_background:{provider:ue,model:U}});const de=Ks(V==null?void 0:V.chat)?V:void 0,xe={provider:T.provider,defaults:de,providers:T.providers||{},features:T.features};ot("[Provider]","Loaded provider config:",xe);const Ie={...xe.providers||{}};fs.forEach(je=>{const oe=Ie[je];oe&&oe.request_overrides&&typeof oe.request_overrides=="object"&&(oe.request_overrides_json=JSON.stringify(oe.request_overrides,null,2))}),u(xe.provider),Ee(!1),J(be(xe.provider,Ie)),n.setFieldsValue({...xe,providers:Ie,defaults:xe.defaults}),j(!0)}catch(T){a.error(e("settings.providerTab.loadConfigFailed")),console.error("Failed to load provider config:",T)}finally{i(!1)}},[n,be,a,e]),we=o.useCallback(async()=>{try{const y=await Te.getEnvVars();E(y.entries||[])}catch(y){console.warn("Failed to load env vars for provider overrides:",y)}},[]),ze=o.useCallback(async()=>{try{const[y,T]=await Promise.all([Te.getProviderInstances(),nt.getInstance().getBambooConfig().catch(()=>({}))]);if(!Array.isArray(y.instances))throw new Error("Provider instances API returned an invalid payload");Je(y,T)}catch{}},[Je]),_e=o.useCallback(async()=>{try{_(!0);const y=await Te.getCopilotAuthStatus();S(y)}catch(y){console.error("Failed to check Copilot auth status:",y),S({authenticated:!1,message:e("settings.providerTab.checkStatusFailed")})}finally{_(!1)}},[e]);o.useEffect(()=>{we(),Ze.getState().loadCatalog(),_e(),(async()=>{try{const[y,T]=await Promise.all([Te.getProviderInstances(),nt.getInstance().getBambooConfig().catch(()=>({}))]);if(!Array.isArray(y.instances))throw new Error("Provider instances API returned an invalid payload");Je(y,T)}catch{await He()}})()},[He,we,_e,Je]);const Ke=async()=>{try{M(!0);const y=await Te.startCopilotAuth();D(y),x(!0)}catch(y){a.error(e("settings.providerTab.startCopilotAuthFailed")),console.error("Failed to start Copilot authentication:",y)}finally{M(!1)}},p=async()=>{if(w)try{P(!0),await Te.completeCopilotAuth({device_code:w.device_code,interval:w.interval||5,expires_in:w.expires_in}),a.success(e("settings.providerTab.copilotAuthSuccess")),x(!1),D(null),await _e()}catch(y){a.error(e("settings.providerTab.completeAuthFailed")),console.error("Authentication completion failed:",y)}finally{P(!1)}},ie=async()=>{if(w)try{await ta(w.user_code),f(!0),a.success(e("settings.providerTab.userCodeCopied")),setTimeout(()=>f(!1),2e3)}catch{a.error(`${e("settings.providerTab.copyCodeFailedPrefix")} ${w.user_code}`)}},pe=async()=>{try{M(!0),await Te.logoutCopilot(),a.success(e("settings.providerTab.logoutSuccess")),await _e()}catch(y){a.error(e("settings.providerTab.logoutFailed")),console.error("Failed to logout:",y)}finally{M(!1)}},Oe=o.useCallback(async()=>{R(!0);try{const y=await Te.fetchCatalogModels();await Ze.getState().loadCatalog();const T=y.fetched.filter(V=>V.models&&V.models.length>0).length;y.fetched.filter(V=>V.error).length>0?a.warning(e("settings.providerTab.fetchModelsPartialSuccess",{success:T,total:y.fetched.length})):a.success(e("settings.providerTab.fetchModelsSuccess",{count:T}))}catch{a.error(e("settings.providerTab.fetchModelsFailed"))}finally{R(!1)}},[a,e]),ye=y=>xs(y)||y instanceof Error?y.message:e("settings.providerTab.unknownError"),Le=y=>{n.setFields([{name:["provider"],errors:[]},{name:["providers",y,"api_key"],errors:[]},{name:["defaults","chat"],errors:[]}])},ds=y=>{const T=y.trim();return T?T.includes(".")?T.split(".").filter(Boolean):T==="provider"?["provider"]:T==="provider/providers"?["provider"]:null:null},Cs=(y,T)=>{if(!y.length)return;const X=y.map(V=>{const U=ds(V.path);return U?{name:U,errors:[V.message]}:V.message.toLowerCase().includes("api key")?{name:["providers",T,"api_key"],errors:[V.message]}:{name:["provider"],errors:[V.message]}}).filter((V,U,ue)=>ue.findIndex(de=>JSON.stringify(de.name)===JSON.stringify(V.name))===U);X.length&&n.setFields(X)},Ms=async y=>{var X;const T=y.provider||d;Le(T);try{const U=await nt.getInstance().validateBambooConfigPatch({provider:y.provider,providers:y.providers||{},defaults:y.defaults,features:{...y.features||{},provider_model_ref:!0}});if(U.valid)return{valid:!0};const ue=((X=U.errors)==null?void 0:X.provider)||[];Cs(ue,T);const de=ue[0];return{valid:!1,message:(de==null?void 0:de.message)||e("settings.providerTab.invalidConfig")}}catch(V){return console.warn("Config validation failed, falling back to save:",V),{valid:!0}}},Lt=async(y,T)=>{var X,V;try{i(!0);const U={provider:y.provider,defaults:y.defaults,providers:{...y.providers||{}},features:{...y.features||{},provider_model_ref:!0}},ue=(X=U.defaults)==null?void 0:X.chat;if(!Ks(ue)){const oe=e("settings.providerTab.selectModelRequired");if(n.setFields([{name:["defaults","chat"],errors:[oe]}]),(T==null?void 0:T.showMessage)!==!1&&a.error(oe),T!=null&&T.throwOnError)throw new Error(oe);return}const de=U.providers;for(const oe of fs){const ne=de[oe];if(!ne)continue;const Ne=ne.request_overrides_json;if(typeof Ne!="string")continue;const xt=Ne.trim();if(!xt)delete ne.request_overrides;else try{ne.request_overrides=JSON.parse(xt)}catch(Vt){const $t=e("settings.providerTab.invalidRequestOverridesJson",{provider:oe,error:Vt.message});if(n.setFields([{name:["providers",oe,"request_overrides_json"],errors:[$t]}]),(T==null?void 0:T.showMessage)!==!1&&a.error($t),T!=null&&T.throwOnError)throw Vt;return}delete ne.request_overrides_json}const xe={...U.providers||{}},Ie=U.provider,je=(V=U.defaults)==null?void 0:V.chat;if(je!=null&&je.model&&Ie&&ko(xe,Ie,je.model),he){const oe=nt.getInstance(),ne={defaults:U.defaults,features:{...U.features||{},provider_model_ref:!0}};ot("[Provider]","Saving instance-mode config:",ne),await oe.setBambooConfig(ne)}else{const ne={provider:U.provider||d,defaults:U.defaults,providers:xe,features:U.features},Ne=await Ms(U);if(!Ne.valid){const xt=Ne.message||e("settings.providerTab.invalidConfig");if((T==null?void 0:T.showMessage)!==!1&&a.error(`${e("settings.providerTab.invalidConfigPrefix")}: ${xt}`),T!=null&&T.throwOnError)throw new Error(xt);return}ot("[Provider]","Saving provider config:",ne),await Te.saveProviderConfig(ne)}(T==null?void 0:T.showMessage)!==!1&&a.success(e("settings.providerTab.saveConfigSuccess"))}catch(U){const ue=ye(U);if((T==null?void 0:T.showMessage)!==!1&&a.error(ue?`${e("settings.providerTab.saveConfigErrorPrefix")}: ${ue}`:e("settings.providerTab.saveConfigFailed")),console.error("Failed to save configuration:",U),T!=null&&T.throwOnError)throw U}finally{i(!1)}},ut=async y=>{var T,X,V,U,ue;try{c(!0);const{useProviderStore:de}=await Ys(async()=>{const{useProviderStore:Bt}=await import("./App-CiBjfJbZ.js").then(Rs=>Rs.ai);return{useProviderStore:Bt}},__vite__mapDeps([4,1,2,3,5,6,7,8]),import.meta.url),{useAppStore:xe}=await Ys(async()=>{const{useAppStore:Bt}=await import("./App-CiBjfJbZ.js").then(Rs=>Rs.aj);return{useAppStore:Bt}},__vite__mapDeps([4,1,2,3,5,6,7,8]),import.meta.url),Ie=(T=de.getState().providerConfig.defaults)==null?void 0:T.chat;he?await de.getState().loadProviderInstances():await de.getState().loadProviderConfig();const je=(X=de.getState().providerConfig.defaults)==null?void 0:X.chat;de.getState().setSelectedModelRef(null);const oe=xe.getState().currentSessionId,ne=oe&&xe.getState().chats.find(Bt=>Bt.id===oe)||null,Ne=Ie?`${Ie.provider}/${Ie.model}`:null,xt=je?`${je.provider}/${je.model}`:null,Vt=(V=ne==null?void 0:ne.config)!=null&&V.model_ref?`${ne.config.model_ref.provider}/${ne.config.model_ref.model}`:null,$t=((ue=(U=ne==null?void 0:ne.config)==null?void 0:U.model)==null?void 0:ue.trim())||null;!!(oe&&(ne!=null&&ne.config)&&je&&xt!==Ne&&(!Vt||Vt===Ne)&&(!$t||$t===(Ie==null?void 0:Ie.model)))&&oe&&(ne!=null&&ne.config)&&je&&xe.getState().updateSession(oe,{config:{...ne.config,model:je.model,model_ref:je}}),(y==null?void 0:y.showMessage)!==!1&&a.success(e("settings.providerTab.applyConfigSuccess"))}catch(de){const xe=ye(de);if((y==null?void 0:y.showMessage)!==!1&&a.error(xe?`${e("settings.providerTab.applyConfigErrorPrefix")}: ${xe}`:e("settings.providerTab.applyConfigFailed")),console.error("Failed to apply configuration:",de),y!=null&&y.throwOnError)throw de}finally{c(!1)}},Es=async y=>{try{const T=n.getFieldsValue(!0);await Lt(T,{throwOnError:!0}),await ut({throwOnError:!0})}catch{}},Ds=async(y,T)=>{if(!(y==="chat"&&!T)&&Y!=="saving"){ee("saving"),Pe(null);try{const X=n.getFieldsValue(!0),V=X.defaults;if(!(V!=null&&V.chat))throw new Error(e("settings.providerTab.selectModelRequired"));X.defaults={...V,[y]:T},await Lt(X,{showMessage:!1,throwOnError:!0}),await ut({showMessage:!1,throwOnError:!0}),ee("success"),a.success(e("settings.providerTab.modelUpdated"))}catch(X){const V=ye(X);ee("error"),Pe(V),a.error(V?`${e("settings.providerTab.updateModelErrorPrefix")}: ${V}`:e("settings.providerTab.updateModelFailed"))}}},Ps=async(y,T)=>{if(Y!=="saving"){ee("saving"),Pe(null);try{if(he){const X=B.find(V=>V.id===y);if(!X)throw new Error(e("settings.providerTab.providerNotConfigured"));await Te.updateProviderInstance(X.id,{config:{reasoning_effort:T??null}}),await ze(),await Ze.getState().loadProviderInstances()}else{const X=n.getFieldsValue(!0);await Lt(X,{showMessage:!1,throwOnError:!0}),await ut({showMessage:!1,throwOnError:!0})}ee("success"),a.success(e("settings.providerTab.reasoningEffortUpdated"))}catch(X){const V=ye(X);ee("error"),Pe(V),a.error(V?`${e("settings.providerTab.updateReasoningEffortErrorPrefix")}: ${V}`:e("settings.providerTab.updateReasoningEffortFailed"))}}},us=(y,T)=>{if(!y)return null;const X=$(y)||y,V=n.getFieldValue(["providers",y,"reasoning_effort"]),U=(T==null?void 0:T.emphasis)==="subtle",ue=(T==null?void 0:T.label)||e("settings.providerTab.reasoningEffortOptional"),de=(T==null?void 0:T.helperText)||e("settings.providerTab.reasoningEffortHelp");return t.jsx("div",{style:{marginTop:(T==null?void 0:T.marginTop)??8,width:"100%"},children:t.jsxs(A,{direction:"vertical",size:U?6:4,style:{width:"100%"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,flexWrap:"wrap"},children:[t.jsx(Ge,{strong:!U,type:U?"secondary":void 0,style:U?{fontSize:s.fontSizeSM,lineHeight:1.4}:void 0,children:ue}),T!=null&&T.showProviderLabel?t.jsx(Ge,{type:"secondary",style:{fontSize:s.fontSizeSM,lineHeight:1.4},children:X}):null]}),Dt(e,{value:V,disabled:Y==="saving",size:(T==null?void 0:T.size)??(U?"small":void 0),style:{width:"100%"},"data-testid":T==null?void 0:T.dataTestId,onChange:xe=>{n.setFieldValue(["providers",y,"reasoning_effort"],xe),T!=null&&T.autoSave&&Ps(y,xe)}}),t.jsx(Ge,{type:"secondary",style:U?{fontSize:s.fontSizeSM,lineHeight:1.5}:void 0,children:de})]})})},Is=o.useCallback(y=>{const T=n.getFieldValue(["providers",y]);return T?y==="copilot"?(h==null?void 0:h.authenticated)??!1:!!T.api_key:!1},[n,h]),Fs=()=>{const y=X=>{const V=n.getFieldValue(["defaults",X]);return t.jsx(_n,{value:V,dataTestId:`model-preference-${X}-picker`,appearance:"contrast",disabled:Y==="saving",onChange:U=>{n.setFieldValue(["defaults",X],U),Ds(X,U)}})},T=(X,V,U)=>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(A,{direction:"vertical",size:8,style:{width:"100%"},children:[t.jsx(Ge,{strong:!0,children:V}),y(X),U?t.jsx(Ge,{type:"secondary",children:U}):null]})}),t.jsx("div",{style:{flex:"0 1 320px",minWidth:280},children:t.jsx(v.Item,{noStyle:!0,shouldUpdate:!0,children:()=>{const ue=n.getFieldValue(["defaults",X]),de=ue==null?void 0:ue.provider;return us(de,{autoSave:!0,dataTestId:`model-preference-${X}-reasoning-effort`,label:e("settings.providerTab.reasoningEffortOptional"),helperText:e("settings.providerTab.reasoningEffortHelp"),marginTop:0,size:"small",emphasis:"subtle",showProviderLabel:!!de})}})})]});return t.jsxs(z,{size:"small",title:e("settings.providerTab.modelPreferences"),style:{marginBottom:16},children:[t.jsx(v.Item,{name:["defaults","chat"],noStyle:!0,preserve:!0,children:t.jsx(Et,{})}),t.jsx(v.Item,{name:["defaults","fast"],noStyle:!0,preserve:!0,children:t.jsx(Et,{})}),t.jsx(v.Item,{name:["defaults","task_summary"],noStyle:!0,preserve:!0,children:t.jsx(Et,{})}),t.jsx(v.Item,{name:["defaults","memory_background"],noStyle:!0,preserve:!0,children:t.jsx(Et,{})}),t.jsx(v.Item,{name:["defaults","sub_agent"],noStyle:!0,preserve:!0,children:t.jsx(Et,{})}),t.jsx(v.Item,{name:["defaults","vision"],noStyle:!0,preserve:!0,children:t.jsx(Et,{})}),t.jsxs(A,{direction:"vertical",size:16,style:{width:"100%"},children:[T("chat",e("settings.providerTab.defaultModel")),T("fast",e("settings.providerTab.fastModel"),e("settings.providerTab.fastModelHelp")),T("task_summary",e("settings.providerTab.taskSummaryModel"),e("settings.providerTab.taskSummaryModelHelp")),T("memory_background",e("settings.providerTab.memoryBackgroundModel"),e("settings.providerTab.memoryBackgroundModelHelp")),T("sub_agent",e("settings.providerTab.subAgentModel"),e("settings.providerTab.subAgentModelHelp")),T("vision",e("settings.providerTab.visionModel"),e("settings.providerTab.visionModelHelp"))]})]})},yt=y=>{const T=b.map(V=>V.name);return t.jsx(v.Item,{name:["providers",y,"request_overrides_json"],label:e("settings.providerTab.advancedRequestOverrides"),extra:t.jsxs(A,{direction:"vertical",size:4,children:[t.jsx(Ge,{type:"secondary",children:e("settings.providerTab.advancedRequestOverridesHelp")}),t.jsxs(Ge,{type:"secondary",children:[e("settings.providerTab.envVarInjection")," ",t.jsx(Ge,{code:!0,children:'{ "type": "env_ref", "name": "YOUR_ENV_NAME" }'})]}),T.length>0&&t.jsx(A,{wrap:!0,size:[6,6],children:T.map(V=>t.jsx(re,{children:V},V))})]}),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"}})})},As=y=>{switch(y){case"openai":return t.jsxs(t.Fragment,{children:[t.jsx(v.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(ft,{})})}),t.jsx(v.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(v.Item,{name:["providers","openai","reasoning_effort"],label:e("settings.providerTab.reasoningEffortOptional"),extra:e("settings.providerTab.reasoningEffortHelp"),children:Dt(e)}),t.jsx(v.Item,{name:["providers","openai","responses_only_models"],label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:Ha(e),children:t.jsx(Q,{mode:"tags",placeholder:e("settings.providerTab.responsesOnlyModelsPlaceholder",'e.g. "gpt-5.3-codex", "gpt-5*"'),tokenSeparators:[","," ",`
|
|
21
|
+
`," "]})}),t.jsx(Re,{dashed:!0}),yt("openai")]});case"anthropic":return t.jsxs(t.Fragment,{children:[t.jsx(v.Item,{name:["providers","anthropic","api_key"],label:e("settings.providerTab.anthropicApiKey"),rules:[{required:!0,message:e("settings.providerTab.anthropicApiKeyRequired")}],children:t.jsx(Ba,{placeholder:e("settings.providerTab.anthropicApiKeyPlaceholder","sk-ant-..."),prefix:t.jsx(ft,{})})}),t.jsx(v.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(v.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(v.Item,{name:["providers","anthropic","reasoning_effort"],label:e("settings.providerTab.reasoningEffortOptional"),extra:e("settings.providerTab.reasoningEffortHelp"),children:Dt(e)}),t.jsx(Re,{dashed:!0}),yt("anthropic")]});case"gemini":return t.jsxs(t.Fragment,{children:[t.jsx(v.Item,{name:["providers","gemini","api_key"],label:e("settings.providerTab.geminiApiKey"),rules:[{required:!0,message:e("settings.providerTab.geminiApiKeyRequired")}],children:t.jsx(Ba,{placeholder:e("settings.providerTab.geminiApiKeyPlaceholder","AIza..."),prefix:t.jsx(ft,{})})}),t.jsx(v.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(v.Item,{name:["providers","gemini","reasoning_effort"],label:e("settings.providerTab.reasoningEffortOptional"),extra:e("settings.providerTab.reasoningEffortHelp"),children:Dt(e)}),t.jsx(Re,{dashed:!0}),yt("gemini")]});case"copilot":return t.jsxs(t.Fragment,{children:[t.jsxs(z,{size:"small",style:{marginBottom:16},title:e("settings.providerTab.authStatusTitle"),extra:k?t.jsx(es,{size:"small"}):h!=null&&h.authenticated?t.jsx(re,{icon:t.jsx(Xs,{}),color:"success",children:e("settings.providerTab.authenticated")}):t.jsx(re,{icon:t.jsx(xa,{}),color:"error",children:e("settings.providerTab.notAuthenticated")}),children:[(h==null?void 0:h.message)&&t.jsx(Hs,{type:"secondary",style:{marginBottom:16},children:h.message}),t.jsxs(A,{children:[h!=null&&h.authenticated?t.jsx(O,{danger:!0,icon:t.jsx(Gn,{}),onClick:pe,loading:F,children:e("settings.providerTab.logoutCopilot")}):t.jsx(O,{type:"primary",icon:t.jsx(Ya,{}),onClick:Ke,loading:F,children:e("settings.providerTab.authenticateCopilot")}),t.jsx(O,{onClick:_e,loading:k,children:e("settings.providerTab.refreshStatus")})]})]}),t.jsx(v.Item,{name:["providers","copilot","headless_auth"],label:e("settings.providerTab.headlessAuth"),valuePropName:"checked",extra:e("settings.providerTab.headlessAuthHelp"),children:t.jsx(me,{})}),t.jsx(v.Item,{name:["providers","copilot","reasoning_effort"],label:e("settings.providerTab.reasoningEffortOptional"),extra:e("settings.providerTab.reasoningEffortHelp"),children:Dt(e)}),t.jsx(v.Item,{name:["providers","copilot","responses_only_models"],label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:Ha(e),children:t.jsx(Q,{mode:"tags",placeholder:e("settings.providerTab.responsesOnlyModelsPlaceholder",'e.g. "gpt-5.3-codex", "gpt-5*"'),tokenSeparators:[","," ",`
|
|
22
|
+
`," "]})}),t.jsx(Re,{dashed:!0}),yt("copilot"),t.jsxs(Hs,{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(v.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(ft,{})})}),t.jsx(v.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(v.Item,{name:["providers","bodhi","target_provider"],label:e("settings.providerTab.targetProvider"),extra:e("settings.providerTab.targetProviderExtra"),children:t.jsxs(Q,{placeholder:e("settings.providerTab.targetProviderPlaceholder","openai"),allowClear:!0,children:[t.jsx(Q.Option,{value:"openai",children:"OpenAI"}),t.jsx(Q.Option,{value:"anthropic",children:"Anthropic"}),t.jsx(Q.Option,{value:"gemini",children:"Gemini"})]})}),t.jsx(v.Item,{name:["providers","bodhi","reasoning_effort"],label:e("settings.providerTab.reasoningEffortOptional"),extra:e("settings.providerTab.reasoningEffortHelp"),children:Dt(e)}),t.jsx(Re,{dashed:!0}),yt("bodhi")]});default:return null}},Nt=y=>{const T=Is(y),X=ht[y];return t.jsxs(A,{size:"small",children:[t.jsx("span",{style:{fontWeight:500},children:X}),T?t.jsx(re,{color:"success",style:{fontSize:11},children:e("settings.providerTab.authenticated")}):t.jsx(re,{color:"default",style:{fontSize:11},children:e("settings.providerTab.providerNotConfigured")})]})};return t.jsxs(z,{title:e("settings.providerTab.title"),loading:r&&!g,className:"lotus-settings-card",children:[t.jsx(Hs,{type:"secondary",children:e("settings.providerTab.description")}),t.jsx(Re,{}),t.jsxs(v,{form:n,layout:"vertical",onFinish:Es,disabled:r&&!g,children:[!he&&t.jsxs(t.Fragment,{children:[t.jsx(v.Item,{name:"provider",label:e("settings.providerTab.activeProvider"),rules:[{required:!0,message:e("settings.providerTab.selectProviderRequired")}],children:t.jsx(Q,{"data-testid":"provider-select",size:"large",onChange:y=>u(y),children:Object.keys(ht).map(y=>t.jsx(Q.Option,{value:y,children:ht[y]},y))})}),t.jsx(v.Item,{noStyle:!0,shouldUpdate:!0,children:()=>us(n.getFieldValue("provider")||d,{autoSave:!0,size:"middle",marginTop:0,dataTestId:"active-provider-reasoning-effort",label:e("settings.providerTab.activeProviderReasoningEffort"),helperText:e("settings.providerTab.reasoningEffortHelp")})}),t.jsx(Re,{})]}),t.jsxs("div",{style:{marginBottom:16},children:[t.jsx(O,{icon:t.jsx(Rt,{}),onClick:Oe,loading:I,children:e(I?"settings.providerTab.fetchingAllModels":"settings.providerTab.fetchAllModels")}),Y==="saving"&&t.jsx(es,{size:"small",style:{marginLeft:8}}),Y==="success"&&t.jsx(Xs,{style:{color:"var(--lotus-chart-secondary)",marginLeft:8}}),Y==="error"&&t.jsx(ve,{title:De,children:t.jsx(xa,{style:{color:"var(--lotus-chart-danger)",marginLeft:8}})})]}),Fs(),he?t.jsx(_o,{instances:B,defaultInstanceId:G,onInstancesChanged:ze}):t.jsx(Ss,{activeKey:C,onChange:y=>J(Array.isArray(y)?y.map(String):y?[String(y)]:[]),ghost:!0,style:{marginBottom:16},items:fs.map(y=>({key:y,label:Nt(y),children:As(y)}))}),t.jsx(Re,{}),t.jsx(A,{size:"middle",children:t.jsx(O,{"data-testid":"save-api-settings",type:"primary",htmlType:"submit",icon:t.jsx(_s,{}),loading:r||l,size:"large",children:e("settings.providerTab.saveAndApply")})})]}),t.jsx(ln,{open:m,onCancel:()=>x(!1),onComplete:p,onCopyCode:ie,completingAuth:L,copiedUserCode:N,deviceCodeInfo:w,timeRemaining:K,token:s})]})},{Text:Ka}=ce,Mo=({skill:e,disabled:s=!1,busy:a=!1,onToggleDisabled:n})=>{const{t:r}=te(),{token:i}=fe.useToken();return t.jsx(z,{title:t.jsxs(A,{size:i.marginXS,wrap:!0,style:{width:"100%",justifyContent:"space-between"},children:[t.jsxs(A,{size:i.marginXS,wrap:!0,children:[t.jsx("span",{children:e.name}),s&&t.jsx(re,{color:"default",children:r("components.skillManager.disabledTag")}),e.license&&t.jsxs(re,{color:"processing",children:["License: ",e.license]})]}),n&&t.jsx(me,{checked:!s,loading:a,onChange:l=>n(e.id,!l),checkedChildren:r("components.skillManager.switchEnabled"),unCheckedChildren:r("components.skillManager.switchDisabled")})]}),styles:{body:{padding:i.paddingMD}},style:{opacity:s?.72:1},children:t.jsxs(A,{direction:"vertical",size:i.marginXS,style:{width:"100%"},children:[t.jsx(Ka,{type:"secondary",children:e.description}),e.compatibility&&t.jsxs(Ka,{type:"secondary",children:["Compatibility: ",e.compatibility]}),e.tool_refs.length>0&&t.jsx(A,{size:i.marginXXS,wrap:!0,children:e.tool_refs.map(l=>t.jsx(re,{style:{background:i.colorFillSecondary,borderColor:i.colorBorderSecondary,color:i.colorText},children:l},l))})]})})},Eo=3e4,Do=()=>{const{t:e}=te(),{message:s}=Ft.useApp(),a=pt(P=>P.config),n=pt(P=>P.loadConfig),r=pt(P=>P.saveConfig),[i,l]=o.useState([]),[c,d]=o.useState(!1),[u,g]=o.useState(null),[j,h]=o.useState(null),[S,k]=o.useState(""),[_,F]=o.useState(new Date),M=o.useMemo(()=>{var P;return new Set((((P=a==null?void 0:a.skills)==null?void 0:P.disabled)??[]).map(K=>K.trim()).filter(Boolean))},[a]),w=o.useCallback(async(P=!0)=>{d(!0),g(null);try{const[K]=await Promise.all([kn.listSkills({includeDisabled:!0},P),n({force:P})]);l(K.skills),F(new Date)}catch(K){const Z=K instanceof Error?K.message:e("components.skillManager.loadFailed");g(Z)}finally{d(!1)}},[n,e]);o.useEffect(()=>{w(!0);const P=setInterval(()=>{w(!0)},Eo);return()=>clearInterval(P)},[w]),o.useEffect(()=>{const P=()=>{w(!0)};return window.addEventListener("focus",P),()=>window.removeEventListener("focus",P)},[w]);const D=o.useCallback(async()=>{await w(!0),s.success(e("components.skillManager.skillsRefreshed"))},[w,e]);o.useEffect(()=>{u&&(s.error(u),g(null))},[u]);const m=o.useCallback(async(P,K)=>{var Z;h(P);try{const N=await n({force:!0}),f=((Z=N==null?void 0:N.skills)==null?void 0:Z.disabled)??[],b=Array.from(new Set((K?[...f,P]:f.filter(E=>E!==P)).map(E=>E.trim()).filter(Boolean))).sort();await r({...N??{},skills:{...(N==null?void 0:N.skills)??{},disabled:b}}),s.success(e("components.skillManager.skillStateSaved"))}catch(N){s.error(N instanceof Error?N.message:e("components.skillManager.saveFailed"))}finally{h(null)}},[n,r,e]),x=i.filter(P=>{const K=S.trim().toLowerCase();return!(K&&![P.name,P.description,P.license??"",P.compatibility??"",...P.tool_refs].join(" ").toLowerCase().includes(K))}),L=()=>{const K=new Date().getTime()-_.getTime(),Z=Math.floor(K/1e3);if(Z<5)return e("components.skillManager.justNow");if(Z<60)return e("components.skillManager.secondsAgo",{count:Z});const N=Math.floor(Z/60);return N<60?e("components.skillManager.minutesAgo",{count:N}):_.toLocaleTimeString()};return t.jsx("div",{style:{padding:"24px"},children:t.jsxs(z,{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(O,{icon:t.jsx(Rt,{spin:c}),onClick:D,loading:c,size:"small",children:e("components.skillManager.refresh")}),t.jsx("span",{className:"lotus-settings-note",style:{fontSize:"12px",marginLeft:"auto"},children:e("components.skillManager.lastUpdated",{value:L()})})]}),children:[t.jsx("div",{className:"lotus-settings-note",style:{marginBottom:"16px"},children:e("components.skillManager.readOnlyHint")}),t.jsx("div",{className:"lotus-settings-note",style:{marginBottom:"16px"},children:e("components.skillManager.disabledHint")}),t.jsx(We,{style:{marginBottom:"24px"},children:t.jsx(H,{placeholder:e("components.skillManager.searchPlaceholder"),prefix:t.jsx(Jn,{}),value:S,onChange:P=>k(P.target.value),allowClear:!0})}),t.jsx(es,{spinning:c,children:x.length===0?t.jsx($e,{description:e(S?"components.skillManager.noMatch":"components.skillManager.noSkillsFound")}):t.jsx(Qe,{grid:{gutter:16,xs:1,sm:2,md:3,lg:3,xl:4},dataSource:x,renderItem:P=>t.jsx(Qe.Item,{children:t.jsx(Mo,{skill:P,disabled:M.has(P.id),busy:j===P.id,onToggleDisabled:m})})})})]})})},{Title:Po,Text:ys,Paragraph:Io}=ce,Qs="model_limits",wt={max_context_tokens:2e5,max_output_tokens:64e3,safety_margin:2e3};function Qt(e){if(typeof e!="number"||!Number.isFinite(e))return null;const s=Math.floor(e);return s>0?s:null}function Fo(e){const s=Array.isArray(e==null?void 0:e.model_limits)?e.model_limits[0]:void 0;return s?{max_context_tokens:Qt(s.max_context_tokens)??wt.max_context_tokens,max_output_tokens:Qt(s.max_output_tokens)??wt.max_output_tokens,safety_margin:Qt(s.safety_margin)??wt.safety_margin}:wt}function Ao(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=Qt(s.max_context_tokens??s.maxContextTokens),r=Qt(s.max_output_tokens??s.maxOutputTokens);if(n===null||r===null)return null;const i=s.safety_margin??s.safetyMargin,l=typeof i=="number"&&Number.isFinite(i)&&i>=0?Math.floor(i):void 0;return{model_pattern:a.trim(),max_context_tokens:n,max_output_tokens:r,safety_margin:l}}function Ro(e){const s=e==null?void 0:e[Qs];return Array.isArray(s)?s.map(a=>Ao(a)).filter(a=>a!==null):[]}function Wa(e,s,a){const n=new Map(s.map(l=>[l.model_pattern,l])),r=[],i=new Set;for(const l of s)i.has(l.model_pattern)||(i.add(l.model_pattern),r.push(l.model_pattern));for(const l of a){const c=l.trim();c&&!i.has(c)&&(i.add(c),r.push(c))}return r.map(l=>{const c=n.get(l);return{id:l,model_pattern:l,isCustom:!1,customized:!!c,max_context_tokens:(c==null?void 0:c.max_context_tokens)??e.max_context_tokens,max_output_tokens:(c==null?void 0:c.max_output_tokens)??e.max_output_tokens,safety_margin:c==null?void 0:c.safety_margin}})}function zo(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 i=r.toLowerCase();if(a.has(i))return s("settings.modelLimits.validation.duplicateModelPattern",{pattern:r});if(a.add(i),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 Ws=o.memo(function({value:s,min:a,max:n,step:r,disabled:i,ariaLabel:l,onCommit:c}){const[d,u]=o.useState(s);return o.useEffect(()=>{u(s)},[s]),t.jsx(Me,{"aria-label":l,value:d,min:a,max:n,step:r,disabled:i,onChange:g=>u(typeof g=="number"?g:null),onBlur:()=>{const g=typeof d=="number"&&Number.isFinite(d)?d:s;u(g),g!==s&&c(g)},style:{width:"100%"}})}),Oo=o.memo(function({value:s,placeholder:a,ariaLabel:n,onCommit:r}){const[i,l]=o.useState(s);return o.useEffect(()=>{l(s)},[s]),t.jsx(H,{"aria-label":n,value:i,placeholder:a,onChange:c=>l(c.target.value),onBlur:()=>{i!==s&&r(i)}})}),Lo=()=>{const{t:e}=te(),[s,a]=o.useState(wt),[n,r]=o.useState([]),[i,l]=o.useState(!1),[c,d]=At.useMessage(),u=o.useRef(!1),g=o.useRef(0),j=o.useCallback(async()=>{l(!0);try{const[m,x]=await Promise.all([Fe.getBambooConfig(),Fe.getModelLimitDefaults()]),L=Fo(x);a(L),r(Wa(L,Ro(m),da()))}catch(m){console.error("Failed to load model limits settings:",m),c.error(e("settings.modelLimits.loadFailed")),a(wt),r(Wa(wt,[],da()))}finally{l(!1)}},[c,e]);o.useEffect(()=>{u.current||(u.current=!0,j())},[j]);const h=o.useCallback((m,x)=>{r(L=>L.map(P=>P.id===m?{...P,...x}:P))},[]),S=o.useCallback(m=>{r(x=>x.map(L=>L.id===m?{...L,customized:!0}:L))},[]),k=o.useCallback(m=>{r(x=>{const L=x.find(P=>P.id===m);return L!=null&&L.isCustom?x.filter(P=>P.id!==m):x.map(P=>P.id===m?{...P,customized:!1,max_context_tokens:s.max_context_tokens,max_output_tokens:s.max_output_tokens,safety_margin:void 0}:P)})},[s]),_=o.useCallback(m=>{r(x=>{const L=x.find(P=>P.id===m);return L&&!L.isCustom&&L.model_pattern.trim()&&wn(L.model_pattern),x.filter(P=>P.id!==m)})},[]),F=o.useCallback(()=>{r(m=>[...m,{id:`custom-${g.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]),M=async()=>{const m=n.filter(L=>L.customized).map(L=>({model_pattern:L.model_pattern.trim(),max_context_tokens:L.max_context_tokens,max_output_tokens:L.max_output_tokens,...typeof L.safety_margin=="number"?{safety_margin:L.safety_margin}:{}})),x=zo(m,e);if(x){c.error(x);return}l(!0);try{await Fe.setBambooConfig({[Qs]:m}),c.success(e("settings.modelLimits.saveSuccess"))}catch(L){console.error("Failed to save model limits settings:",L),c.error(e("settings.modelLimits.saveFailed"))}finally{l(!1)}},w=async()=>{l(!0);try{await Fe.setBambooConfig({[Qs]:[]}),r(m=>m.filter(x=>!x.isCustom).map(x=>({...x,customized:!1,max_context_tokens:s.max_context_tokens,max_output_tokens:s.max_output_tokens,safety_margin:void 0}))),c.success(e("settings.modelLimits.resetSuccess"))}catch(m){console.error("Failed to reset model limits settings:",m),c.error(e("settings.modelLimits.resetFailed"))}finally{l(!1)}},D=o.useMemo(()=>[{title:e("settings.modelLimits.columns.model"),dataIndex:"model_pattern",key:"model_pattern",width:240,render:(m,x)=>x.isCustom?t.jsx(Oo,{value:m,ariaLabel:`model-${x.id}`,placeholder:e("settings.modelLimits.placeholders.model"),onCommit:L=>h(x.id,{model_pattern:L})}):t.jsx(ys,{strong:!0,children:m})},{title:e("settings.modelLimits.columns.contextWindow"),dataIndex:"max_context_tokens",key:"max_context_tokens",width:170,render:(m,x)=>t.jsx(Ws,{value:m,ariaLabel:`context-${x.id}`,min:1e3,max:5e6,step:1e3,disabled:!x.customized,onCommit:L=>h(x.id,{max_context_tokens:L})})},{title:e("settings.modelLimits.columns.maxOutput"),dataIndex:"max_output_tokens",key:"max_output_tokens",width:150,render:(m,x)=>t.jsx(Ws,{value:m,ariaLabel:`output-${x.id}`,min:1,max:5e6,step:256,disabled:!x.customized,onCommit:L=>h(x.id,{max_output_tokens:L})})},{title:e("settings.modelLimits.columns.safetyMargin"),dataIndex:"safety_margin",key:"safety_margin",width:150,render:(m,x)=>t.jsx(Ws,{value:m??s.safety_margin,ariaLabel:`safety-${x.id}`,min:0,max:1e6,step:100,disabled:!x.customized,onCommit:L=>h(x.id,{safety_margin:L})})},{title:e("settings.modelLimits.columns.status"),key:"status",width:150,render:(m,x)=>x.customized?t.jsx(re,{color:"blue",children:e("settings.modelLimits.badge.customized")}):t.jsx(ve,{title:e("settings.modelLimits.badge.defaultTooltip"),children:t.jsx(re,{children:e("settings.modelLimits.badge.default")})})},{title:e("settings.modelLimits.columns.actions"),key:"actions",width:200,render:(m,x)=>t.jsxs(A,{size:"small",children:[!x.customized&&t.jsx(O,{size:"small",type:"link",onClick:()=>S(x.id),children:e("settings.modelLimits.actions.customize")}),x.customized&&!x.isCustom&&t.jsx(O,{size:"small",onClick:()=>k(x.id),children:e("settings.modelLimits.actions.revert")}),t.jsx(O,{size:"small",type:"text",danger:!0,onClick:()=>_(x.id),children:e("settings.modelLimits.actions.remove")})]})}],[e,s.safety_margin,h,S,k,_]);return t.jsxs("div",{className:"model-limits-settings",children:[d,t.jsxs(z,{children:[t.jsx(Po,{level:4,children:e("settings.modelLimits.title")}),t.jsxs(Io,{type:"secondary",children:[e("settings.modelLimits.descriptionPrefix")," ",e("settings.modelLimits.descriptionSuffix")]}),t.jsx(Re,{}),t.jsxs(A,{direction:"vertical",size:"small",style:{width:"100%"},children:[t.jsx(ys,{strong:!0,children:e("settings.modelLimits.defaultsTitle")}),t.jsx(ys,{type:"secondary",children:e("settings.modelLimits.defaultsDescription")}),t.jsx(ys,{type:"secondary",children:e("settings.modelLimits.globalDefault",{context:s.max_context_tokens.toLocaleString(),output:s.max_output_tokens.toLocaleString()})})]}),t.jsx(ct,{dataSource:n,columns:D,rowKey:m=>m.id,pagination:!1,size:"small",style:{margin:"16px 0"},scroll:{x:1060},locale:{emptyText:t.jsx($e,{description:e("settings.modelLimits.emptyState")})}}),t.jsxs(A,{wrap:!0,children:[t.jsx(O,{icon:t.jsx(Ct,{}),onClick:F,children:e("settings.modelLimits.actions.addModel")}),t.jsx(O,{type:"primary",icon:t.jsx(_s,{}),onClick:()=>void M(),loading:i,children:e("settings.modelLimits.actions.save")}),t.jsx(O,{icon:t.jsx(Rt,{}),onClick:()=>void w(),loading:i,children:e("settings.modelLimits.actions.resetToDefaults")}),t.jsx(O,{onClick:()=>void j(),loading:i,children:e("settings.modelLimits.actions.reload")})]})]})]})},{Text:Gs}=ce,{useToken:No}=fe,Vo="bamboo_dark_mode",Zo=({themeMode:e,onThemeModeChange:s,locale:a,onLocaleChange:n,onBack:r})=>{const{t:i}=te(),{token:l}=No(),{deleteAllChats:c}=ir(),[d,u]=o.useState(!1),[g,j]=At.useMessage(),[h,S]=o.useState(""),[k,_]=o.useState(ua()),[F,M]=o.useState(ga()),[w,D]=o.useState(ma()),[m,x]=o.useState(pa()),L=Ze(C=>C.currentProvider),K=Ze(C=>C.getProviderType)(L)==="copilot",Z=Js(C=>C.activeTabKey),N=Js(C=>C.setActiveTabKey),f=Cn(C=>C.isAdvanced),b=l.paddingSM,E=(C,J)=>({key:C,label:t.jsx(Gs,{type:"secondary",style:{fontSize:11,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em",cursor:"default",userSelect:"none"},children:J}),disabled:!0,children:null}),I=(C,J)=>t.jsx("span",{"data-testid":`settings-tab-${C}`,children:J}),R=()=>{localStorage.clear(),g.success(i("settings.notifications.localStorageCleared"))},B=async()=>{u(!0);try{await c(),await Fe.resetSetupStatus(),await Fe.resetBambooConfig(),localStorage.clear(),g.success(i("settings.notifications.resetSuccessReloading")),setTimeout(()=>{window.location.reload()},1500)}catch(C){console.error("Failed to reset application:",C),g.error(C instanceof Error?C.message:i("settings.notifications.resetFailed")),u(!1)}},se=()=>{Dn(h),g.success(i("settings.notifications.promptEnhancementSaved"))},G=C=>{_(C),Fn(C)},ge=C=>{M(C),In(C)},he=C=>{D(C),Pn(C)},Ee=C=>{x(C),An(C),window.dispatchEvent(new Event("lotus-vdi-safe-mode-change")),g.success(C?i("settings.appTab.vdiSafeModeEnabled","Graphics compatibility mode enabled"):i("settings.appTab.vdiSafeModeDisabled","Graphics compatibility mode disabled"))};return o.useEffect(()=>{S(Mn()),_(ua()),M(ga()),D(ma()),x(pa())},[]),t.jsxs(W,{vertical:!0,role:"region","aria-label":i("settings.page.title"),style:{height:"100vh",overflow:"hidden",background:l.colorBgContainer},children:[j,t.jsxs(W,{align:"center",justify:"space-between",style:{padding:l.padding,paddingTop:l.padding+b,borderBottom:`1px solid ${l.colorBorderSecondary}`},children:[t.jsxs(W,{align:"center",gap:l.marginSM,children:[t.jsx(O,{icon:t.jsx(Xn,{}),onClick:r,"aria-label":i("settings.page.back"),children:i("settings.page.back")}),t.jsx(Gs,{strong:!0,"data-testid":"settings-page-title",children:i("settings.page.title")})]}),t.jsxs(Gs,{type:"secondary","data-testid":"settings-page-version",children:[i("settings.appTab.runningVersion","Running version"),": v",Ga]})]}),t.jsx(Yn.Content,{style:{flex:1,minHeight:0,overflow:"auto",padding:l.padding},children:t.jsx(vs,{tabPosition:"left",activeKey:Z,onChange:C=>N(C),items:[E("group-ai",i("settings.page.groups.ai")),{key:"provider",label:I("provider",i("settings.page.tabs.provider")),children:t.jsx(Co,{})},{key:"model-limits",label:I("model-limits",i("settings.page.tabs.modelLimits")),children:t.jsx(Lo,{})},{key:"prompts",label:I("prompts",i("settings.page.tabs.prompts")),children:t.jsx(vr,{promptEnhancement:h,onPromptEnhancementChange:S,mermaidEnhancementEnabled:k,taskEnhancementEnabled:F,showCopilotConclusionWithOptionsEnhancement:K,copilotConclusionWithOptionsEnhancementEnabled:w,onMermaidToggle:G,onTaskToggle:ge,onCopilotConclusionWithOptionsToggle:he,onSaveEnhancement:se})},E("group-tools",i("settings.page.groups.toolsAndExtensions")),{key:"skills",label:I("skills",i("settings.page.tabs.skills")),children:t.jsx(Do,{})},{key:"mcp",label:I("mcp",i("settings.page.tabs.mcp")),children:t.jsx(ci,{})},{key:"workflows",label:I("workflows",i("settings.page.tabs.workflows")),children:t.jsx(Ir,{})},{key:"hooks",label:I("hooks",i("settings.page.tabs.hooks")),children:t.jsx(so,{})},E("group-security",i("settings.page.groups.securityAndPrivacy")),{key:"masking",label:I("masking",i("settings.page.tabs.masking")),children:t.jsx(kr,{})},{key:"env-vars",label:I("env-vars",i("settings.page.tabs.envVars")),children:t.jsx(Mr,{})},E("group-monitoring",i("settings.page.groups.monitoring")),{key:"metrics",label:I("metrics",i("settings.page.tabs.metrics")),children:t.jsx(Zi,{})},{key:"sessions",label:I("sessions",i("settings.page.tabs.sessions")),children:t.jsx(fo,{})},E("group-system",i("settings.page.groups.system")),{key:"config",label:I("config",i("settings.page.tabs.config")),children:t.jsx(pr,{msgApi:g,locale:a,onLocaleChange:n})},{key:"schedules",label:I("schedules",i("settings.page.tabs.schedules")),children:t.jsx(ho,{})},{key:"notifications",label:I("notifications",i("settings.page.tabs.notifications","Notifications")),children:t.jsx(xo,{})},{key:"app",label:I("app",i("settings.page.tabs.app")),children:t.jsx(jr,{themeMode:e,onThemeModeChange:s,vdiSafeMode:m,onVdiSafeModeToggle:Ee,onClearLocalStorage:R,onResetApp:B,isResetting:d,darkModeKey:Vo})}].filter(C=>!(!f&&C.key&&En.has(C.key)||!f&&(C.key==="group-security"||C.key==="group-monitoring")))})})]})};export{Zo as SystemSettingsPage};
|