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