@bigduu/lotus 2026.5.13 → 2026.5.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-YqZv5PIH.js","./vendor-markdown-DZuK0SxV.js","./vendor-i18n-BNURlJ23.js","./vendor-antd-C8lKwvI6.js","./App-bVqmFSlk.js","./vendor-mermaid-C1Gk9PtT.js","./main-BEVjNwcv.js","./main-B6snAd4S.css","./App-DNZiQHSs.css"])))=>i.map(i=>d[i]);
2
- var On=Object.defineProperty;var Nn=(e,s,n)=>s in e?On(e,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[s]=n;var Vs=(e,s,n)=>Nn(e,typeof s!="symbol"?s+"":s,n);import{j as t}from"./vendor-markdown-DZuK0SxV.js";import{a as i,u as Z,R as $s,i as te}from"./vendor-i18n-BNURlJ23.js";import{z as Vn,u as Re,b as $n,F as qn,s as Bn,G as Is,j as $t,t as rt,H as Un,J as at,K as Se,L as Hn,M as Kn,N as Wn,O as Gn,P as wn,S as qt,Q as $e,y as qs,a as Ge,R as Cn,x as Mn,d as Jn,c as Cs,o as Xn,T as Bs,U as Yn,V as Zn,W as Pt,X as Qn,Y as ea,Z as ta,_ as Us,$ as Hs,a0 as Ks,a1 as Ws,f as sa,a2 as na,A as aa,a3 as ra,a4 as oa,a5 as ia,a6 as la,a7 as ca}from"./App-bVqmFSlk.js";import{C as F,S as I,A as ke,j as le,X as U,E as z,t as fe,N as k,K as Bt,av as ls,aw as ae,ax as ge,L as Ke,ay as Ne,az as ie,n as xe,aA as Fe,aB as he,aC as da,at as Pe,F as $,aD as Fs,aE as ua,U as cs,V as gs,ad as ga,aF as ma,M as Wt,aG as ms,Q as Rs,O as Ut,aH as Gs,l as ue,aI as et,W as ot,aj as Tt,J as jt,a9 as bt,aJ as pa,ac as ha,aK as Js,aL as _e,H as Ae,ai as En,aM as fa,aN as tt,aO as be,B as ya,aP as Xs,aQ as xa,aR as ba,m as Ms,z as va,aS as Ys,aT as es,aU as Ta,aV as ja,a4 as Sa,ao as _a,aW as ka}from"./vendor-antd-C8lKwvI6.js";import{_ as Es}from"./vendor-mermaid-C1Gk9PtT.js";import{r as wa}from"./onboardingStorage-BVcEpmTy.js";import"./main-BEVjNwcv.js";import{m as Vt}from"./MetricsService-PUxHq4VE.js";import{R as St,B as As,C as Gt,X as Jt,Y as Xt,T as _t,L as Ls,a as ds,b as Dn,c as vt,P as Ca,d as Ma,e as Ea}from"./vendor-charts-bhMup2Pu.js";function Da(e){return e instanceof Vn}function Pa(){const{chats:e,currentSessionId:s,currentChat:n,addMessage:a,selectSession:o,deleteSession:r,deleteSessions:l,deleteMessage:m,updateSession:c,persistSessionTitle:p,pinSession:d,unpinSession:b,loadChats:f}=Re($n(x=>({chats:x.chats,currentSessionId:x.currentSessionId,currentChat:qn(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}))),v=Re(Bn(s)),T=i.useMemo(()=>(n==null?void 0:n.messages)||[],[n]),u=i.useMemo(()=>e.filter(x=>x.pinned),[e]),M=i.useMemo(()=>e.filter(x=>!x.pinned),[e]),j=e.length;return{chats:e,currentSessionId:s,currentChat:n,isProcessing:v,baseMessages:T,pinnedChats:u,unpinnedChats:M,chatCount:j,addMessage:a,deleteMessage:m,selectSession:o,deleteSession:r,deleteSessions:l,pinSession:d,unpinSession:b,updateSession:c,persistSessionTitle:p,loadChats:f}}function Ia(e){const s=Re(f=>f.addChat),n=Re(f=>f.lastSelectedPromptId),a=Re(f=>f.systemPrompts),o=Is.getInstance(),r=i.useCallback(async(f,v)=>{var j,x;const T=a.find(E=>E.id===n),u=(T==null?void 0:T.id)||(a.length>0?((j=a.find(E=>E.id==="general_assistant"))==null?void 0:j.id)||a[0].id:""),M={title:f||"New Session",createdAt:Date.now(),messages:[],config:{systemPromptId:u,baseSystemPrompt:(T==null?void 0:T.content)||(a.length>0?((x=a.find(E=>E.id==="general_assistant"))==null?void 0:x.content)||a[0].content:""),lastUsedEnhancedPrompt:null,...$t.getState().isProviderModelRefEnabled()?{model_ref:$t.getState().selectedModelRef}:{}},...v};await s(M)},[s,n,a]),l=i.useCallback(async f=>{rt("[ChatOps]","[useChatOperations] createChatWithSystemPrompt started with prompt:",f);const v={title:`New Session - ${f.name}`,createdAt:Date.now(),messages:[],config:{systemPromptId:f.id,baseSystemPrompt:f.content,lastUsedEnhancedPrompt:null}};rt("[ChatOps]","[useChatOperations] Calling addChat with newChatData.config:",v.config),await s(v)},[s]),m=i.useCallback(f=>{const v=e.chats.find(T=>T.id===f);v&&(v.pinned?e.unpinSession(f):e.pinSession(f))},[e]),c=i.useCallback((f,v)=>{e.updateSession(f,{title:v})},[e]),p=i.useCallback(async()=>{await o.cleanupSessions("empty",!0),await Re.getState().loadChats()},[o]),d=i.useCallback(async()=>{await o.cleanupSessions("all",!0),await Re.getState().loadChats()},[o]),b=i.useCallback(async()=>{await o.cleanupSessions("all",!1),await Re.getState().loadChats()},[o]);return{createNewChat:r,createChatWithSystemPrompt:l,toggleChatPin:m,updateChatTitle:c,deleteEmptyChats:p,deleteAllUnpinnedChats:d,deleteAllChats:b}}function Fa(e,s){const n=i.useMemo(()=>e.baseMessages,[e.baseMessages]),a=i.useCallback(async()=>{var p;if(!e.currentSessionId||!e.currentChat)return;const o=[...e.baseMessages];if(o.length===0)return;const r=o[o.length-1];let l=o;if((r==null?void 0:r.role)==="assistant"){if(!(await e.deleteMessage(e.currentSessionId,r.id)).success)return;l=o.slice(0,-1)}const m=[...l].reverse().find(d=>d.role==="user");if(!m)return;const c="content"in m?m.content:m.displayText;typeof c=="string"&&await((p=s==null?void 0:s.onRetry)==null?void 0:p.call(s,c))},[e,s]);return{currentMessages:n,retryLastMessage:a}}const Ra=()=>{const e=Pa(),s=Ia(e),n=Un({sessionId:e.currentSessionId,addMessage:e.addMessage,updateSession:e.updateSession}),a=Fa(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:ts}=le,{useToken:Aa}=fe,La=({httpProxy:e,httpsProxy:s,onHttpProxyChange:n,onHttpsProxyChange:a,onReload:o,onSave:r,isLoading:l})=>{const{t:m}=Z(),{token:c}=Aa(),p=at(S=>S.proxyAuthStatus),d=at(S=>S.isLoadingProxyAuthStatus),b=at(S=>S.loadProxyAuthStatus),f=at(S=>S.applyProxyAuth),v=at(S=>S.clearProxyAuth),[T,u]=i.useState({username:"",password:""}),[M,j]=i.useState(!1);i.useEffect(()=>{b()},[b]);const x=async()=>{const S=T.username.trim();if(S){j(!0);try{await f({username:S,password:T.password}),u({username:"",password:""})}catch(P){console.error("Failed to apply proxy auth:",P)}finally{j(!1)}}},E=async()=>{j(!0);try{await v()}catch(S){console.error("Failed to clear proxy auth:",S)}finally{j(!1)}};return t.jsx(F,{size:"small",title:t.jsx(ts,{strong:!0,children:m("settings.networkCard.title")}),className:"lotus-settings-card",children:t.jsxs(I,{direction:"vertical",size:c.marginSM,style:{width:"100%"},children:[t.jsx(ke,{message:m("settings.networkCard.guideTip"),type:"info",showIcon:!0}),t.jsxs(I,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[t.jsx(ts,{type:"secondary",children:m("settings.networkCard.httpProxy")}),t.jsx(U,{"data-testid":"proxy-url",style:{width:"100%"},value:e,onChange:S=>n(S.target.value),placeholder:m("settings.networkCard.proxyPlaceholder"),disabled:l})]}),t.jsxs(I,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[t.jsx(ts,{type:"secondary",children:m("settings.networkCard.httpsProxy")}),t.jsx(U,{style:{width:"100%"},value:s,onChange:S=>a(S.target.value),placeholder:m("settings.networkCard.proxyPlaceholder"),disabled:l})]}),t.jsx(F,{size:"small",title:m("settings.networkCard.proxyAuthTitle"),className:"lotus-settings-card",style:{marginTop:c.marginSM},children:p!=null&&p.configured?t.jsxs(I,{direction:"vertical",style:{width:"100%"},children:[t.jsx(ke,{type:"success",message:m("settings.networkCard.proxyConfiguredForUser",{username:p.username??""}),showIcon:!0}),t.jsx(z,{onClick:E,loading:M||d,danger:!0,children:m("settings.networkCard.clearCredentials")})]}):t.jsxs(I,{direction:"vertical",size:c.marginXS,style:{width:"100%"},children:[t.jsx(U,{placeholder:m("settings.networkCard.username"),value:T.username,onChange:S=>u(P=>({...P,username:S.target.value}))}),t.jsx(U.Password,{placeholder:m("settings.networkCard.password"),value:T.password,onChange:S=>u(P=>({...P,password:S.target.value}))}),t.jsx(z,{type:"primary",onClick:x,loading:M||d,disabled:!T.username.trim(),children:m("settings.networkCard.apply")})]})}),t.jsx(ts,{type:"secondary",style:{fontSize:c.fontSizeSM},children:m("settings.networkCard.credentialsStorageNote")}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:c.marginSM},children:[t.jsx(z,{onClick:()=>Promise.resolve(o()).finally(()=>b({force:!0})),disabled:l,children:m("settings.networkCard.reload")}),t.jsx(z,{"data-testid":"save-proxy-settings",type:"primary",onClick:()=>Promise.resolve(r()).finally(()=>b({force:!0})),disabled:l,children:m("settings.networkCard.save")})]})]})})},{Text:za}=le,{useToken:Oa}=fe,Na=({msgApi:e})=>{const{t:s}=Z(),{token:n}=Oa(),[a]=k.useForm(),[o,r]=i.useState(!1),[l,m]=i.useState(!1),[c,p]=i.useState(!1),[d,b]=i.useState(!1),[f,v]=i.useState(null),T=c&&!d,u=i.useMemo(()=>s(c?d?"settings.configTab.accessPassword.helperLocalBypass":"settings.configTab.accessPassword.helperRemote":"settings.configTab.accessPassword.helperNotEnabled"),[d,c,s]),M=i.useCallback(async()=>{r(!0),v(null);try{const x=await Se.getAccessStatus();p(x.password_enabled),b(x.local_bypass)}catch(x){const E=x instanceof Error?x.message:s("settings.configTab.accessPassword.loadStatusFailed","Failed to load access status");v(E)}finally{r(!1)}},[s]);i.useEffect(()=>{M()},[M]);const j=async()=>{var x;try{const E=await a.validateFields();m(!0),await Se.updateAccessPassword({current_password:((x=E.currentPassword)==null?void 0:x.trim())||void 0,new_password:E.newPassword.trim()}),e.success(s(c?"settings.configTab.accessPassword.updated":"settings.configTab.accessPassword.enabled")),a.resetFields(),await M()}catch(E){if(E.errorFields)return;const S=E instanceof Error?E.message:s("settings.configTab.accessPassword.updateFailed","Failed to update access password");e.error(S)}finally{m(!1)}};return t.jsx(F,{size:"small",className:"lotus-settings-card",title:t.jsx(za,{strong:!0,children:s("settings.configTab.accessPasswordTitle")}),children:t.jsxs(I,{direction:"vertical",size:n.marginMD,style:{width:"100%"},children:[t.jsx(ke,{type:c?"info":"warning",showIcon:!0,message:s(c?"settings.configTab.accessPassword.statusEnabled":"settings.configTab.accessPassword.statusDisabled"),description:u}),f?t.jsx(ke,{type:"error",showIcon:!0,message:f}):null,t.jsxs(k,{form:a,layout:"vertical",disabled:o||l,children:[T?t.jsx(k.Item,{label:s("settings.configTab.accessPassword.currentPasswordLabel"),name:"currentPassword",rules:[{required:!0,message:s("settings.configTab.accessPassword.validation.currentPasswordRequired")}],children:t.jsx(U.Password,{autoComplete:"current-password"})}):null,t.jsx(k.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(U.Password,{autoComplete:"new-password"})}),t.jsx(k.Item,{label:s("settings.configTab.accessPassword.confirmPasswordLabel"),name:"confirmPassword",dependencies:["newPassword"],rules:[{required:!0,message:s("settings.configTab.accessPassword.validation.confirmPasswordRequired")},({getFieldValue:x})=>({validator(E,S){return!S||x("newPassword")===S?Promise.resolve():Promise.reject(new Error(s("settings.configTab.accessPassword.validation.passwordMismatch")))}})],children:t.jsx(U.Password,{autoComplete:"new-password"})}),t.jsx(z,{type:"primary",loading:l,onClick:()=>void j(),children:s(c?"settings.configTab.accessPassword.updateAction":"settings.configTab.accessPassword.enableAction")})]})]})})},{Text:ze}=le,{useToken:Va}=fe,Zs="http://127.0.0.1:9562/v1",Ot=e=>[...new Set(e.map(s=>s.trim()).filter(s=>s.length>0))].sort(),$a=e=>{var n;const s=(n=e.tools)==null?void 0:n.disabled;return Array.isArray(s)?Ot(s.filter(a=>typeof a=="string")):[]},qa=({msgApi:e,locale:s,onLocaleChange:n})=>{const{t:a}=Z(),{token:o}=Va(),[r,l]=i.useState({http_proxy:"",https_proxy:"",memory:{auto_dream_enabled:!1,background_model:""}}),[m,c]=i.useState(Zs),[p,d]=i.useState([]),[b,f]=i.useState([]),[v,T]=i.useState([]),[u,M]=i.useState(!1),[j,x]=i.useState(!1),E=i.useCallback(async()=>{var A,H;M(!0);try{const[V,oe]=await Promise.all([Se.getBambooConfig(),Se.getBambooTools()]);l({http_proxy:V.http_proxy||"",https_proxy:V.https_proxy||"",memory:{auto_dream_enabled:((A=V.memory)==null?void 0:A.auto_dream_enabled)??!1,background_model:((H=V.memory)==null?void 0:H.background_model)||""}});const ce=$a(V);f(ce),T(ce),d(Ot(oe.tools||[]))}catch(V){console.error("Failed to load config:",V),e.error(a("settings.configTab.loadConfigFailed"))}finally{M(!1)}},[e,a]);i.useEffect(()=>{E()},[E]);const S=A=>{l(H=>({...H,http_proxy:A}))},P=A=>{l(H=>({...H,https_proxy:A}))},ee=A=>{l(H=>({...H,memory:{...H.memory,auto_dream_enabled:A}}))},R=A=>{l(H=>({...H,memory:{...H.memory,background_model:A}}))},q=async()=>{var A,H;M(!0);try{const V=await Se.validateBambooConfigPatch(r);if(!V.valid){const ce=((H=(A=V.errors)==null?void 0:A.proxy)==null?void 0:H[0])??Object.values(V.errors||{}).flat().filter(Boolean)[0];e.error((ce==null?void 0:ce.message)||a("settings.configTab.invalidConfig"));return}await Se.setBambooConfig(r),e.success(a("settings.configTab.saveConfigSuccess"))}catch(V){console.error("Failed to save config:",V);const oe=V instanceof Error&&V.message.trim()?V.message:a("settings.configTab.saveConfigFailed");e.error(oe)}finally{M(!1)}},G=async()=>{e.success(a("settings.configTab.backendSaved"))},h=()=>{c(Zs),e.success(a("settings.configTab.backendResetDefault"))},y=(A,H)=>{f(V=>{const oe=new Set(V);return H?oe.delete(A):oe.add(A),Ot([...oe])})},D=async()=>{x(!0);try{const A=await Se.getBambooTools();d(Ot(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)}},_=async()=>{x(!0);try{const A=Ot(b);await Se.setBambooConfig({tools:{disabled:A}}),f(A),T(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)}},O=JSON.stringify(b)!==JSON.stringify(v),X=new Set(b);return t.jsx(Bt,{spinning:u,tip:a("settings.common.loading"),children:t.jsx(ls,{items:[{key:"general",label:a("settings.configTab.tabs.general"),children:t.jsxs(I,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[t.jsx(ke,{message:a("settings.configTab.providerMovedTitle"),description:a("settings.configTab.providerMovedDescription"),type:"info",showIcon:!0,closable:!0}),t.jsx(La,{httpProxy:r.http_proxy,httpsProxy:r.https_proxy,onHttpProxyChange:S,onHttpsProxyChange:P,onReload:E,onSave:q,isLoading:u}),t.jsx(F,{size:"small",className:"lotus-settings-card",title:t.jsx(ze,{strong:!0,children:a("settings.configTab.language")}),children:t.jsx(ae,{value:s,style:{width:260},options:[{label:a("settings.configTab.languageEnglish"),value:"en-US"},{label:a("settings.configTab.languageChinese"),value:"zh-CN"},{label:a("settings.configTab.languageTraditionalChinese"),value:"zh-TW"},{label:a("settings.configTab.languageFrench"),value:"fr-FR"},{label:a("settings.configTab.languageJapanese"),value:"ja-JP"},{label:a("settings.configTab.languageHindi"),value:"hi-IN"}],onChange:A=>n(A)})}),t.jsx(F,{size:"small",className:"lotus-settings-card",title:t.jsx(ze,{strong:!0,children:a("settings.configTab.memoryTitle")}),children:t.jsxs(I,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[t.jsx(ze,{type:"secondary",children:a("settings.configTab.memoryDescription")}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:o.marginMD,flexWrap:"wrap"},children:[t.jsxs("div",{children:[t.jsx(ze,{strong:!0,children:a("settings.configTab.autoDreamEnabled")}),t.jsx("div",{children:t.jsx(ze,{type:"secondary",style:{fontSize:o.fontSizeSM},children:a("settings.configTab.autoDreamEnabledHint")})})]}),t.jsx(ge,{"data-testid":"auto-dream-toggle",checked:r.memory.auto_dream_enabled,onChange:ee})]}),t.jsxs(I,{direction:"vertical",size:o.marginXXS,style:{width:"100%"},children:[t.jsx(ze,{strong:!0,children:a("settings.configTab.backgroundModel")}),t.jsx(U,{"data-testid":"auto-dream-background-model-input",value:r.memory.background_model,onChange:A=>R(A.target.value),placeholder:a("settings.configTab.backgroundModelPlaceholder")}),t.jsx(ze,{type:"secondary",style:{fontSize:o.fontSizeSM},children:a("settings.configTab.backgroundModelHint")})]}),t.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:t.jsx(z,{"data-testid":"save-memory-settings",type:"primary",onClick:q,loading:u,children:a("settings.configTab.save")})})]})}),t.jsx(F,{size:"small",title:t.jsx(ze,{strong:!0,children:a("settings.configTab.backendApiBaseUrlTitle")}),children:t.jsxs(I,{direction:"vertical",size:o.marginSM,style:{width:"100%"},children:[t.jsx(I,{direction:"vertical",size:o.marginXXS,style:{width:"100%"},children:t.jsx(U,{style:{width:"100%"},value:m,onChange:A=>c(A.target.value),placeholder:a("settings.configTab.backendApiPlaceholder")})}),t.jsx(ze,{type:"secondary",style:{fontSize:o.fontSizeSM},children:a("settings.configTab.backendApiHint")}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:o.marginSM},children:[t.jsx(z,{"data-testid":"reset-to-defaults",onClick:h,children:a("settings.configTab.resetToDefault")}),t.jsx(z,{"data-testid":"save-api-settings",type:"primary",onClick:G,children:a("settings.configTab.save")})]})]})}),t.jsx(Na,{msgApi:e})]})},{key:"tools",label:a("settings.configTab.tabs.tools"),children:t.jsx(F,{size:"small",title:t.jsx(ze,{strong:!0,children:a("settings.configTab.toolsTitle")}),children:t.jsxs(I,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[t.jsx(ze,{type:"secondary",children:a("settings.configTab.toolsDescription")}),p.length===0?t.jsx(ke,{type:"info",showIcon:!0,message:a("settings.configTab.toolsEmpty")}):t.jsx(Ke,{bordered:!0,dataSource:p,renderItem:A=>t.jsx(Ke.Item,{actions:[t.jsx(ge,{checked:!X.has(A),onChange:H=>y(A,H)},`${A}-switch`)],children:t.jsx(ze,{code:!0,children:A})})}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:o.marginSM},children:[t.jsx(z,{onClick:D,loading:j,children:a("settings.configTab.reloadTools")}),t.jsx(z,{type:"primary",onClick:_,loading:j,disabled:!O,children:a("settings.configTab.save")})]})]})})}]})})},{Title:Ba,Text:ys}=le,{useToken:Ua}=fe,Ha=()=>{const{t:e}=Z(),{token:s}=Ua(),n=Hn(),a=Kn(),o=Wn(),[r]=k.useForm(),l=$s.useRef(n);$s.useEffect(()=>{l.current!==n&&(r.setFieldsValue(n),l.current=n)},[n,r]);const m=p=>{l.current={...l.current,...p},a(p)},c=()=>{o(),r.resetFields()};return t.jsxs("div",{style:{padding:"24px",maxWidth:"1200px",margin:"0 auto"},children:[t.jsx(Ba,{level:3,style:{marginBottom:"8px"},children:e("settings.mermaidTab.title")}),t.jsx(ys,{type:"secondary",style:{display:"block",marginBottom:"24px"},children:e("settings.mermaidTab.description")}),t.jsxs(k,{form:r,layout:"vertical",initialValues:n,onValuesChange:m,children:[t.jsxs(F,{title:e("settings.mermaidTab.themeCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:[t.jsx(Ne,{gutter:16,children:t.jsx(ie,{span:24,children:t.jsx(k.Item,{name:"theme",label:t.jsxs(I,{children:[e("settings.mermaidTab.themeLabel"),t.jsx(xe,{title:e("settings.mermaidTab.themeTooltip"),children:t.jsx(Fe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsxs(ae,{children:[t.jsx(ae.Option,{value:"default",children:e("settings.mermaidTab.themeOptions.default")}),t.jsx(ae.Option,{value:"neutral",children:e("settings.mermaidTab.themeOptions.neutral")}),t.jsx(ae.Option,{value:"dark",children:e("settings.mermaidTab.themeOptions.dark")}),t.jsx(ae.Option,{value:"forest",children:e("settings.mermaidTab.themeOptions.forest")}),t.jsx(ae.Option,{value:"base",children:e("settings.mermaidTab.themeOptions.base")})]})})})}),t.jsxs(ys,{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(F,{title:e("settings.mermaidTab.globalCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:[t.jsxs(Ne,{gutter:16,children:[t.jsx(ie,{span:12,children:t.jsx(k.Item,{name:"fontSize",label:t.jsxs(I,{children:[e("settings.mermaidTab.fontSizeLabel"),t.jsx(xe,{title:e("settings.mermaidTab.fontSizeTooltip"),children:t.jsx(Fe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:10,max:32,step:1,style:{width:"100%"},addonAfter:"px"})})}),t.jsx(ie,{span:12,children:t.jsx(k.Item,{name:"defaultScale",label:t.jsxs(I,{children:[e("settings.mermaidTab.defaultZoomLabel"),t.jsx(xe,{title:e("settings.mermaidTab.defaultZoomTooltip"),children:t.jsx(Fe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:.1,max:3,step:.1,style:{width:"100%"}})})})]}),t.jsx(k.Item,{name:"useMaxWidth",label:t.jsxs(I,{children:[e("settings.mermaidTab.responsiveWidthLabel"),t.jsx(xe,{title:e("settings.mermaidTab.responsiveWidthTooltip"),children:t.jsx(Fe,{style:{color:s.colorTextSecondary}})})]}),valuePropName:"checked",children:t.jsx(ge,{})})]}),t.jsx(F,{title:e("settings.mermaidTab.flowchartCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsxs(Ne,{gutter:16,children:[t.jsx(ie,{span:8,children:t.jsx(k.Item,{name:"flowchartNodeSpacing",label:t.jsxs(I,{children:[e("settings.mermaidTab.flowchartNodeSpacingLabel"),t.jsx(xe,{title:e("settings.mermaidTab.flowchartNodeSpacingTooltip"),children:t.jsx(Fe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:20,max:200,step:10,style:{width:"100%"}})})}),t.jsx(ie,{span:8,children:t.jsx(k.Item,{name:"flowchartRankSpacing",label:t.jsxs(I,{children:[e("settings.mermaidTab.flowchartRankSpacingLabel"),t.jsx(xe,{title:e("settings.mermaidTab.flowchartRankSpacingTooltip"),children:t.jsx(Fe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:20,max:200,step:10,style:{width:"100%"}})})}),t.jsx(ie,{span:8,children:t.jsx(k.Item,{name:"flowchartCurve",label:t.jsxs(I,{children:[e("settings.mermaidTab.flowchartCurveTypeLabel"),t.jsx(xe,{title:e("settings.mermaidTab.flowchartCurveTypeTooltip"),children:t.jsx(Fe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsxs(ae,{children:[t.jsx(ae.Option,{value:"basis",children:e("settings.mermaidTab.flowchartCurveOptions.basis")}),t.jsx(ae.Option,{value:"linear",children:e("settings.mermaidTab.flowchartCurveOptions.linear")}),t.jsx(ae.Option,{value:"cardinal",children:e("settings.mermaidTab.flowchartCurveOptions.cardinal")})]})})})]})}),t.jsx(F,{title:e("settings.mermaidTab.sequenceCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsxs(Ne,{gutter:16,children:[t.jsx(ie,{span:6,children:t.jsx(k.Item,{name:"sequenceActorMargin",label:t.jsxs(I,{children:[e("settings.mermaidTab.sequenceActorMarginLabel"),t.jsx(xe,{title:e("settings.mermaidTab.sequenceActorMarginTooltip"),children:t.jsx(Fe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:20,max:200,step:10,style:{width:"100%"}})})}),t.jsx(ie,{span:6,children:t.jsx(k.Item,{name:"sequenceMessageMargin",label:t.jsxs(I,{children:[e("settings.mermaidTab.sequenceMessageMarginLabel"),t.jsx(xe,{title:e("settings.mermaidTab.sequenceMessageMarginTooltip"),children:t.jsx(Fe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:10,max:100,step:5,style:{width:"100%"}})})}),t.jsx(ie,{span:6,children:t.jsx(k.Item,{name:"sequenceWidth",label:t.jsxs(I,{children:[e("settings.mermaidTab.sequenceActorWidthLabel"),t.jsx(xe,{title:e("settings.mermaidTab.sequenceActorWidthTooltip"),children:t.jsx(Fe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:100,max:300,step:10,style:{width:"100%"}})})}),t.jsx(ie,{span:6,children:t.jsx(k.Item,{name:"sequenceHeight",label:t.jsxs(I,{children:[e("settings.mermaidTab.sequenceActorHeightLabel"),t.jsx(xe,{title:e("settings.mermaidTab.sequenceActorHeightTooltip"),children:t.jsx(Fe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:40,max:150,step:5,style:{width:"100%"}})})})]})}),t.jsx(F,{title:e("settings.mermaidTab.ganttCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsxs(Ne,{gutter:16,children:[t.jsx(ie,{span:12,children:t.jsx(k.Item,{name:"ganttBarHeight",label:t.jsxs(I,{children:[e("settings.mermaidTab.ganttBarHeightLabel"),t.jsx(xe,{title:e("settings.mermaidTab.ganttBarHeightTooltip"),children:t.jsx(Fe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:10,max:50,step:5,style:{width:"100%"},addonAfter:"px"})})}),t.jsx(ie,{span:12,children:t.jsx(k.Item,{name:"ganttTopPadding",label:t.jsxs(I,{children:[e("settings.mermaidTab.ganttTopPaddingLabel"),t.jsx(xe,{title:e("settings.mermaidTab.ganttTopPaddingTooltip"),children:t.jsx(Fe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:20,max:100,step:10,style:{width:"100%"}})})})]})}),t.jsx(I,{children:t.jsx(z,{icon:t.jsx(da,{}),onClick:c,children:e("settings.mermaidTab.resetToDefaults")})}),t.jsx(Pe,{}),t.jsx(F,{title:e("settings.mermaidTab.previewTitle"),styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsx(ys,{type:"secondary",children:e("settings.mermaidTab.previewDescription")})})]})]})},Ka=i.lazy(()=>Es(()=>import("./index-YqZv5PIH.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8]),import.meta.url)),{Text:ct}=le,{useToken:Wa}=fe,Ga=({promptEnhancement:e,onPromptEnhancementChange:s,mermaidEnhancementEnabled:n,taskEnhancementEnabled:a,showCopilotConclusionWithOptionsEnhancement:o,copilotConclusionWithOptionsEnhancementEnabled:r,onMermaidToggle:l,onTaskToggle:m,onCopilotConclusionWithOptionsToggle:c,onSaveEnhancement:p})=>{const{t:d}=Z(),{token:b}=Wa(),f=b.marginLG;return t.jsxs($,{vertical:!0,gap:f,children:[t.jsx(F,{size:"small",className:"lotus-settings-card",children:t.jsx(i.Suspense,{fallback:t.jsx(Bt,{size:"small"}),children:t.jsx(Ka,{})})}),t.jsx(F,{size:"small",className:"lotus-settings-card",children:t.jsxs(I,{direction:"vertical",size:b.marginXS,style:{width:"100%"},children:[t.jsx(ct,{strong:!0,children:d("settings.promptsTab.title")}),t.jsxs($,{align:"center",gap:b.marginSM,children:[t.jsx(ct,{strong:!0,children:d("settings.promptsTab.mermaidEnhancement")}),t.jsx(ge,{checked:n,onChange:l})]}),t.jsxs($,{align:"center",gap:b.marginSM,children:[t.jsx(ct,{strong:!0,children:d("settings.promptsTab.taskListRules")}),t.jsx(ge,{checked:a,onChange:m})]}),o&&t.jsxs(I,{direction:"vertical",size:b.marginXXS,style:{width:"100%"},children:[t.jsxs($,{align:"center",gap:b.marginSM,children:[t.jsx(ct,{strong:!0,children:d("settings.promptsTab.copilotConclusionWithOptionsBeforeFinish")}),t.jsx(ge,{checked:r,onChange:c})]}),t.jsx(ct,{type:"secondary",style:{fontSize:b.fontSizeSM},children:d("settings.promptsTab.copilotConclusionWithOptionsBeforeFinishDescription",{defaultValue:Gn()})})]}),t.jsx(U.TextArea,{rows:6,placeholder:d("settings.promptsTab.enhancementPlaceholder"),value:e,onChange:v=>s(v.target.value)}),t.jsx($,{justify:"flex-end",children:t.jsx(z,{type:"primary",onClick:p,children:d("settings.promptsTab.saveEnhancement")})}),t.jsx(ct,{type:"secondary",style:{fontSize:b.fontSizeSM},children:d("settings.promptsTab.description")})]})}),n&&t.jsx(Fs,{size:"small",items:[{key:"mermaid",label:t.jsx(ct,{strong:!0,children:d("settings.mermaidTab.title")}),children:t.jsx(Ha,{})}]})]})},{Text:nt}=le,{useToken:Ja}=fe,Xa=({themeMode:e,onThemeModeChange:s,vdiSafeMode:n,onVdiSafeModeToggle:a,onClearLocalStorage:o,onResetApp:r,isResetting:l,darkModeKey:m})=>{const{t:c}=Z(),{token:p}=Ja();return t.jsx(F,{size:"small",className:"lotus-settings-card",children:t.jsxs(I,{direction:"vertical",size:p.marginSM,style:{width:"100%"},children:[t.jsxs($,{align:"center",justify:"space-between",gap:p.marginSM,children:[t.jsx(nt,{strong:!0,children:c("settings.appTab.runningVersion","Running version")}),t.jsxs(nt,{code:!0,"data-testid":"settings-app-version",children:["v",wn]})]}),t.jsx(nt,{type:"secondary",style:{fontSize:p.fontSizeSM},children:c("settings.appTab.runningVersionDesc","This is the currently running Lotus frontend version.")}),t.jsxs($,{align:"center",gap:p.marginSM,children:[t.jsx(nt,{strong:!0,children:c("settings.appTab.darkMode")}),t.jsx(ge,{"data-testid":"dark-mode-toggle",checked:e==="dark",onChange:d=>{const b=d?"dark":"light";s(b),localStorage.setItem(m,b)}})]}),t.jsxs($,{align:"center",gap:p.marginSM,children:[t.jsx(nt,{strong:!0,children:c("settings.appTab.vdiSafeMode","Graphics compatibility mode")}),t.jsx(ge,{"data-testid":"vdi-safe-mode-toggle",checked:n,onChange:a})]}),t.jsx(nt,{type:"secondary",style:{fontSize:p.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(z,{block:!0,icon:t.jsx(ua,{}),onClick:()=>{wa(),window.location.reload()},children:c("settings.appTab.resetStepReplayGuide")}),t.jsx(cs,{title:c("settings.appTab.clearLocalStorageTitle"),description:c("settings.appTab.clearLocalStorageDescription"),onConfirm:o,okText:c("settings.appTab.confirmClear"),cancelText:c("settings.appTab.cancel"),placement:"top",children:t.jsx(z,{danger:!0,block:!0,icon:t.jsx(gs,{}),children:c("settings.appTab.clearLocalStorageButton")})}),t.jsx(Pe,{style:{margin:`${p.marginSM}px 0`}}),t.jsxs($,{align:"center",gap:p.marginSM,children:[t.jsx(ga,{style:{color:p.colorError}}),t.jsx(nt,{strong:!0,style:{color:p.colorError},children:c("settings.appTab.dangerZone")})]}),t.jsx(nt,{type:"secondary",style:{fontSize:p.fontSizeSM},children:c("settings.appTab.dangerDescription")}),t.jsx(cs,{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:r,okText:c("settings.appTab.resetConfirm"),cancelText:c("settings.appTab.cancel"),placement:"top",okButtonProps:{danger:!0},children:t.jsx(z,{"data-testid":"reset-to-defaults",danger:!0,block:!0,type:"primary",icon:t.jsx(ma,{}),loading:l,children:c("settings.appTab.resetButton")})})]})})},{Text:dt}=le,{useToken:Ya}=fe,Qs=[{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,}"}],Za=(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:te.t("settings.keywordMaskingTab.invalidRegexPattern")}}},Qa=()=>{const{t:e}=Z(),{message:s}=Wt.useApp(),{token:n}=Ya(),[a,o]=i.useState([]),[r,l]=i.useState(!1),[m,c]=i.useState(null),[p,d]=i.useState(""),[b,f]=i.useState("exact"),[v,T]=i.useState(!0),[u,M]=i.useState(),[j,x]=i.useState("My token is sk-123"),E=i.useCallback(async()=>{try{l(!0);const _=await qt.getInstance().getKeywordMaskingConfig();o(_.entries)}catch(D){s.error(e("settings.keywordMaskingTab.loadFailed")),console.error(D)}finally{l(!1)}},[e]);i.useEffect(()=>{E()},[E]);const S=async D=>{try{const _=qt.getInstance(),O=await _.validateKeywordEntries(D);if(!O.valid&&O.errors){const A=O.errors.map(H=>`Entry ${H.index+1}: ${H.message}`).join("; ");return s.error(`${e("settings.keywordMaskingTab.validationFailedPrefix")}: ${A}`),!1}const X=await _.updateKeywordMaskingConfig(D);return o(X.entries),s.success(e("settings.keywordMaskingTab.saveSuccess")),!0}catch(_){return s.error(_ instanceof Error?_.message:e("settings.keywordMaskingTab.saveFailed")),!1}},P=async()=>{const D={pattern:"",match_type:"exact",enabled:!0},_=[...a,D];o(_),c(_.length-1),d(""),f("exact"),T(!0),M(void 0)},ee=D=>{const _=a[D];c(D),d(_.pattern),f(_.match_type),T(_.enabled),M(void 0)},R=async()=>{if(m===null)return;if(!p.trim()){s.error(e("settings.keywordMaskingTab.patternRequired"));return}const D=[...a];D[m]={pattern:p.trim(),match_type:b,enabled:v},await S(D)&&c(null)},q=()=>{var D;m!==null&&!((D=a[m])!=null&&D.pattern)&&o(a.filter((_,O)=>O!==m)),c(null)},G=async D=>{const _=a.filter((O,X)=>X!==D);await S(_)},h=async(D,_)=>{const O=[...a];O[D]={...O[D],enabled:_},await S(O)},y=Za(j,p,b);return t.jsx(F,{className:"lotus-settings-card",title:e("settings.keywordMaskingTab.title"),extra:t.jsx(z,{"data-testid":"add-keyword",type:"primary",icon:t.jsx(Ut,{}),onClick:P,loading:r,children:e("settings.keywordMaskingTab.addKeyword")}),children:t.jsxs(I,{direction:"vertical",style:{width:"100%"},size:"large",children:[t.jsx(dt,{type:"secondary",children:e("settings.keywordMaskingTab.description")}),t.jsx(Ke,{loading:r,dataSource:a,locale:{emptyText:e("settings.keywordMaskingTab.empty")},renderItem:(D,_)=>t.jsx(Ke.Item,{style:{backgroundColor:n.colorFillAlter,marginBottom:8,borderRadius:n.borderRadius,padding:12},actions:m===_?[t.jsx(z,{"data-testid":"save-keyword",type:"primary",icon:t.jsx(ms,{}),onClick:R,"aria-label":e("settings.keywordMaskingTab.save")},"save"),t.jsx(z,{onClick:q,children:e("settings.keywordMaskingTab.cancel")},"cancel")]:[t.jsx(z,{icon:t.jsx(Rs,{}),onClick:()=>ee(_),"aria-label":e("settings.keywordMaskingTab.edit")},"edit"),t.jsx(z,{"data-testid":`delete-keyword-${_}`,danger:!0,icon:t.jsx(gs,{}),onClick:()=>G(_),"aria-label":e("settings.keywordMaskingTab.delete")},"delete")],children:t.jsx($,{vertical:!0,style:{width:"100%"},gap:8,children:m===_?t.jsxs(t.Fragment,{children:[t.jsx(U,{"data-testid":"keyword-pattern-input",placeholder:e("settings.keywordMaskingTab.patternPlaceholder"),value:p,onChange:O=>d(O.target.value),autoFocus:!0}),t.jsxs($,{gap:8,align:"center",wrap:"wrap",children:[t.jsx(ae,{"data-testid":"keyword-examples-select","aria-label":e("settings.keywordMaskingTab.examples"),placeholder:e("settings.keywordMaskingTab.examples"),value:u,onChange:O=>{M(O);const X=Qs.find(A=>A.value===O);X&&(d(X.pattern),f(X.match_type))},options:Qs.map(O=>({value:O.value,label:e(O.labelKey)})),style:{minWidth:220}}),t.jsx(ae,{value:b,onChange:f,options:[{value:"exact",label:e("settings.keywordMaskingTab.exactMatch")},{value:"regex",label:e("settings.keywordMaskingTab.regexPattern")}],style:{width:150}}),t.jsx(ge,{checked:v,onChange:T})]}),t.jsxs($,{vertical:!0,gap:6,children:[t.jsx(dt,{type:"secondary",children:e("settings.keywordMaskingTab.sampleText")}),t.jsx(U,{placeholder:e("settings.keywordMaskingTab.sampleTextPlaceholder"),value:j,onChange:O=>x(O.target.value)}),t.jsx(dt,{type:"secondary",children:e("settings.keywordMaskingTab.maskedPreview")}),t.jsx(U,{readOnly:!0,value:y.masked,status:y.error?"error":void 0}),y.error&&t.jsx(dt,{type:"danger",children:y.error})]})]}):t.jsxs($,{justify:"space-between",align:"center",children:[t.jsxs($,{vertical:!0,gap:4,children:[t.jsx(dt,{strong:!0,children:D.pattern||e("settings.keywordMaskingTab.emptyPattern")}),t.jsxs($,{gap:8,children:[t.jsx(dt,{type:"secondary",style:{fontSize:12},children:D.match_type==="regex"?e("settings.keywordMaskingTab.regexPattern"):e("settings.keywordMaskingTab.exactMatch")}),!D.enabled&&t.jsx(dt,{type:"warning",style:{fontSize:12},children:e("settings.keywordMaskingTab.disabled")})]})]}),t.jsx(ge,{checked:D.enabled,onChange:O=>h(_,O),size:"small"})]})})})})]})})},{Text:yt,Paragraph:er}=le,tr=/^[A-Za-z_][A-Za-z0-9_]*$/,sr=()=>{const{t:e}=Z(),{message:s}=Wt.useApp(),[n,a]=i.useState([]),[o,r]=i.useState(!1),[l,m]=i.useState(!1),[c,p]=i.useState(null),[d]=k.useForm(),b=i.useCallback(async()=>{r(!0);try{const x=await $e.getEnvVars();a(x.entries)}catch{s.error(e("settings.envVars.fetchError","Failed to load environment variables"))}finally{r(!1)}},[e]);i.useEffect(()=>{b()},[b]);const f=async x=>{var S;const E={name:x.name.trim(),value:x.value,secret:x.secret??!1,description:((S=x.description)==null?void 0:S.trim())||void 0};try{const P=await $e.upsertEnvVar(E);a(P.entries),s.success(c?e("settings.envVars.updated","Variable updated"):e("settings.envVars.created","Variable created")),M()}catch(P){s.error((P instanceof Error?P.message:void 0)||e("settings.envVars.saveError","Failed to save variable"))}},v=async x=>{try{const E=await $e.deleteEnvVar(x);a(E.entries),s.success(e("settings.envVars.deleted","Variable deleted"))}catch(E){s.error((E instanceof Error?E.message:void 0)||e("settings.envVars.deleteError","Failed to delete variable"))}},T=()=>{p(null),d.resetFields(),d.setFieldsValue({secret:!1}),m(!0)},u=x=>{p(x.name),d.setFieldsValue({name:x.name,value:"",secret:x.secret,description:x.description??""}),m(!0)},M=()=>{m(!1),p(null),d.resetFields()},j=[{title:e("settings.envVars.name","Name"),dataIndex:"name",key:"name",render:x=>t.jsx(yt,{code:!0,children:x})},{title:e("settings.envVars.value","Value"),dataIndex:"value",key:"value",render:(x,E)=>E.secret?t.jsxs(yt,{type:"secondary",children:[t.jsx(Gs,{style:{marginRight:4}}),E.has_value?"••••••••":e("settings.envVars.notSet","(not set)")]}):t.jsx(yt,{children:x||t.jsx(yt,{type:"secondary",children:e("settings.envVars.empty","(empty)")})})},{title:e("settings.envVars.type","Type"),key:"secret",width:100,render:(x,E)=>E.secret?t.jsx(ue,{color:"warning",icon:t.jsx(Gs,{}),children:e("settings.envVars.secret","Secret")}):t.jsx(ue,{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(yt,{type:"secondary",children:x}):t.jsx(yt,{type:"secondary",italic:!0,children:"—"})},{title:e("settings.envVars.actions","Actions"),key:"actions",width:120,render:(x,E)=>t.jsxs(I,{size:"small",children:[t.jsx(z,{type:"text",size:"small",icon:t.jsx(Rs,{}),onClick:()=>u(E),"aria-label":e("settings.envVars.edit","Edit")}),t.jsx(cs,{title:e("settings.envVars.deleteConfirm","Delete this variable?"),onConfirm:()=>v(E.name),okText:e("settings.envVars.yes","Yes"),cancelText:e("settings.envVars.no","No"),children:t.jsx(z,{type:"text",size:"small",danger:!0,icon:t.jsx(gs,{}),"aria-label":e("settings.envVars.delete","Delete")})})]})}];return t.jsxs("div",{style:{maxWidth:900},children:[t.jsxs(F,{className:"lotus-settings-card",title:e("settings.envVars.title","Environment Variables"),extra:t.jsx(z,{type:"primary",icon:t.jsx(Ut,{}),onClick:T,children:e("settings.envVars.addButton","Add Variable")}),children:[t.jsx(er,{type:"secondary",style:{marginBottom:16},children:e("settings.envVars.description","Variables are injected into Bash tool processes. Secret variables are encrypted at rest.")}),t.jsx(et,{dataSource:n,columns:j,rowKey:"name",size:"small",pagination:!1,loading:o,locale:{emptyText:e("settings.envVars.noVars","No environment variables configured")}})]}),t.jsx(ot,{title:c?e("settings.envVars.editTitle","Edit Variable"):e("settings.envVars.addTitle","Add Environment Variable"),open:l,onCancel:M,onOk:()=>d.submit(),okText:e("settings.envVars.save","Save"),cancelText:e("settings.envVars.cancel","Cancel"),destroyOnClose:!0,children:t.jsxs(k,{form:d,layout:"vertical",onFinish:f,initialValues:{secret:!1},children:[t.jsx(k.Item,{name:"name",label:e("settings.envVars.name","Name"),rules:[{required:!0,message:e("settings.envVars.nameRequired","Variable name is required")},{pattern:tr,message:e("settings.envVars.nameInvalid","Must start with a letter or underscore, followed by letters, digits, or underscores")}],children:t.jsx(U,{placeholder:"GITHUB_TOKEN",disabled:c!==null,autoFocus:c===null})}),t.jsx(k.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(U.Password,{placeholder:c?e("settings.envVars.valuePlaceholderEdit","Enter new value or leave empty"):e("settings.envVars.valuePlaceholder","Enter value"),visibilityToggle:!0})}),t.jsx(k.Item,{name:"secret",label:e("settings.envVars.secret","Secret"),valuePropName:"checked",extra:e("settings.envVars.secretHint","Secret variables are encrypted on disk and masked in the UI"),children:t.jsx(ge,{})}),t.jsx(k.Item,{name:"description",label:e("settings.envVars.descriptionField","Description"),children:t.jsx(U,{placeholder:e("settings.envVars.descriptionPlaceholder","Optional description")})})]})})]})},ht=class ht{constructor(){}static getInstance(){return ht.instance||(ht.instance=new ht),ht.instance}async listWorkflows(){try{rt("[WorkflowManager]","[WorkflowManagerService] Listing workflows");const s=await qs.get("bamboo/workflows"),n=Array.isArray(s)?s:[];return rt("[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{rt("[WorkflowManager]","[WorkflowManagerService] Getting workflow: "+s);const n=await qs.get("bamboo/workflows/"+encodeURIComponent(s)),a=n!=null&&n.name?String(n.name):s,o={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 rt("[WorkflowManager]","[WorkflowManagerService] Got workflow:",n),{name:a,content:String((n==null?void 0:n.content)||""),metadata:o}}catch(n){throw console.error("[WorkflowManagerService] Failed to get workflow "+s+":",n),Da(n)&&n.status===404?new Error("Workflow '"+s+"' not found"):n instanceof Error&&n.message.includes("404")?new Error("Workflow '"+s+"' not found"):n}}};Vs(ht,"instance");let Ds=ht;const{Text:xs}=le,{TextArea:nr}=U,{useToken:ar}=fe,rr=e=>!(!e||e.includes("/")||e.includes("\\")||e.includes("..")),or=()=>{const{t:e}=Z(),{token:s}=ar(),[n,a]=Tt.useMessage(),[o,r]=i.useState([]),[l,m]=i.useState(!1),[c,p]=i.useState(!1),[d,b]=i.useState(!1),[f,v]=i.useState(null),[T,u]=i.useState(""),[M,j]=i.useState(""),[x,E]=i.useState(!1),S=i.useMemo(()=>Ds.getInstance(),[]),P=i.useCallback(async()=>{m(!0);try{const h=await S.listWorkflows();return r(h),h}catch{return n.error(e("settings.workflowsTab.loadFailed")),[]}finally{m(!1)}},[n,e,S]);i.useEffect(()=>{P()},[P]);const ee=i.useCallback(async h=>{v(h),u(h.name),E(!1),p(!0);try{const y=await S.getWorkflow(h.name);j(y.content??"")}catch{n.error(e("settings.workflowsTab.loadContentFailed")),j("")}finally{p(!1)}},[n,e,S]),R=()=>{v(null),u(""),j(""),E(!1)},q=i.useCallback(async()=>{if(!rr(T)){n.error(e("settings.workflowsTab.invalidName"));return}const h=o.some(y=>y.name===T);if(!f&&h){n.error(e("settings.workflowsTab.nameAlreadyExists"));return}b(!0);try{await qt.getInstance().saveWorkflow(T,M),n.success(e("settings.workflowsTab.saved")),E(!1);const _=(await P()).find(O=>O.name===T);_&&v(_)}catch(y){n.error(y instanceof Error?y.message:e("settings.workflowsTab.saveFailed"))}finally{b(!1)}},[M,T,P,n,f,e,o]),G=i.useCallback(async h=>{try{await qt.getInstance().deleteWorkflow(h.name),n.success(e("settings.workflowsTab.deleted")),(f==null?void 0:f.name)===h.name&&R(),await P()}catch(y){n.error(y instanceof Error?y.message:e("settings.workflowsTab.deleteFailed"))}},[P,n,f,e]);return t.jsxs("div",{style:{padding:"24px"},children:[a,t.jsxs(F,{title:e("settings.workflowsTab.title"),extra:t.jsxs(I,{children:[t.jsx(z,{icon:t.jsx(jt,{}),onClick:P,loading:l,children:e("settings.workflowsTab.refresh")}),t.jsx(z,{"data-testid":"create-workflow",icon:t.jsx(Ut,{}),onClick:R,children:e("settings.workflowsTab.newWorkflow")}),t.jsx(z,{"data-testid":"save-workflow",type:"primary",icon:t.jsx(ms,{}),onClick:q,loading:d,disabled:!x,children:e("settings.workflowsTab.save")})]}),children:[t.jsx(xs,{type:"secondary",children:e("settings.workflowsTab.description")}),t.jsxs($,{gap:s.marginLG,style:{marginTop:s.marginLG},children:[t.jsx("div",{style:{width:320,flexShrink:0},children:t.jsx(Ke,{loading:l,dataSource:o,locale:{emptyText:e("settings.workflowsTab.empty")},renderItem:h=>t.jsx(Ke.Item,{style:{cursor:"pointer",backgroundColor:(f==null?void 0:f.name)===h.name?s.colorFillSecondary:"transparent",borderRadius:s.borderRadius,padding:s.paddingSM},onClick:()=>ee(h),actions:[t.jsx(z,{"data-testid":`delete-workflow-${h.name}`,type:"text",danger:!0,size:"small",icon:t.jsx(gs,{}),onClick:y=>{y.stopPropagation(),G(h)},"aria-label":e("settings.workflowsTab.delete")},"delete")],children:t.jsxs(I,{direction:"vertical",size:0,children:[t.jsxs(xs,{strong:!0,children:["/",h.name]}),t.jsx(xs,{type:"secondary",style:{fontSize:12},children:h.filename})]})})})}),t.jsx("div",{style:{flex:1},children:t.jsxs(I,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(U,{"data-testid":"workflow-name",placeholder:e("settings.workflowsTab.namePlaceholder"),value:T,onChange:h=>{u(h.target.value),E(!0)},disabled:!!f,prefix:t.jsx(Rs,{})}),t.jsx(nr,{"data-testid":"workflow-content",placeholder:e("settings.workflowsTab.contentPlaceholder"),value:M,onChange:h=>{j(h.target.value),E(!0)},autoSize:{minRows:12},disabled:c})]})})]})]})]})};var N=(e=>(e.Connecting="connecting",e.Ready="ready",e.Degraded="degraded",e.Stopped="stopped",e.Error="error",e))(N||{});const Yt=6e4,Zt=3e4,Ht=2e4,us=1e4,ps=e=>({id:e,enabled:!0,transport:{type:"stdio",command:"",args:[],env:{},startup_timeout_ms:Ht},request_timeout_ms:Yt,healthcheck_interval_ms:Zt,allowed_tools:[],denied_tools:[]}),ir=()=>({status:"stopped",tool_count:0,restart_count:0}),lr=e=>{switch(typeof e=="string"?e.trim().toLowerCase():""){case N.Connecting:return N.Connecting;case N.Ready:return N.Ready;case N.Degraded:return N.Degraded;case N.Error:return N.Error;case N.Stopped:default:return N.Stopped}},Ze=(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},cr=(e,s)=>{if(!e||typeof e!="object")return s;const n=e;if(n.type==="sse"){const r=Array.isArray(n.headers)?n.headers.map(l=>{if(!l||typeof l!="object")return null;const m=l;return typeof m.name!="string"||typeof m.value!="string"?null:{name:m.name,value:m.value}}).filter(l=>!!l):[];return{type:"sse",url:typeof n.url=="string"?n.url:"",headers:r,connect_timeout_ms:Ze(n.connect_timeout_ms,us)}}const a=Array.isArray(n.args)?n.args.filter(r=>typeof r=="string"):[],o=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:o.reduce((r,[l,m])=>(typeof m=="string"&&(r[l]=m),r),{}),startup_timeout_ms:Ze(n.startup_timeout_ms,Ht)}},dr=(e,s)=>{const n=ps(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:Ze(a.request_timeout_ms,Yt),healthcheck_interval_ms:Ze(a.healthcheck_interval_ms,Zt),allowed_tools:Array.isArray(a.allowed_tools)?a.allowed_tools.filter(r=>typeof r=="string"):[],denied_tools:Array.isArray(a.denied_tools)?a.denied_tools.filter(r=>typeof r=="string"):[],reconnect:a.reconnect&&typeof a.reconnect=="object"?{enabled:typeof a.reconnect.enabled=="boolean"?a.reconnect.enabled:!0,initial_backoff_ms:Ze(a.reconnect.initial_backoff_ms,1e3),max_backoff_ms:Ze(a.reconnect.max_backoff_ms,3e4),max_attempts:Ze(a.reconnect.max_attempts,0)}:void 0,transport:cr(a.transport,n.transport)}},ur=e=>{const s=ir(),a=e.runtime??{},o=a.status??e.status;return{status:lr(o),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:Ze(a.tool_count??e.tool_count,s.tool_count),restart_count:Ze(a.restart_count??e.restart_count,s.restart_count),last_ping_at:typeof a.last_ping_at=="string"?a.last_ping_at:void 0}},gr=e=>{const s=dr(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:ur(e)}},mr=(e,s)=>`mcp__${e}__${s}`,pr=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),o=s.slice(n+2);return!a||!o?null:{server_id:a,original_name:o}},hr=(e,s,n=0)=>{if(!e||typeof e!="object")return null;const a=e,o=typeof a.alias=="string"?a.alias:typeof a.name=="string"&&a.name.startsWith("mcp__")?a.name:void 0,r=o&&typeof o=="string"?pr(o):null,l=(typeof a.server_id=="string"?a.server_id:void 0)??(typeof a.serverId=="string"?a.serverId:void 0)??(r==null?void 0:r.server_id)??s??"",m=(typeof a.original_name=="string"?a.original_name:void 0)??(typeof a.originalName=="string"?a.originalName:void 0)??(r==null?void 0:r.original_name)??(typeof a.name=="string"?a.name:void 0)??"",c=o??(l&&m?mr(l,m):""),p=typeof a.description=="string"?a.description:"",d=a,b="parameters"in d?d.parameters:"inputSchema"in d?d.inputSchema:"input_schema"in d?d.input_schema:void 0,f=c||m||`mcp_tool_${n}`;return{alias:f,server_id:l||"unknown",original_name:m||f,description:p,parameters:b}};class fr{async getServers(){const s=await Ge.get("mcp/servers");return Array.isArray(s.servers)?s.servers.map(gr):[]}async addServer(s){return Ge.post("mcp/servers",s)}async updateServer(s,n){const a={...n,id:s};return Ge.put(`mcp/servers/${s}`,a)}async deleteServer(s){return Ge.delete(`mcp/servers/${s}`)}async connectServer(s){return Ge.post(`mcp/servers/${s}/connect`)}async disconnectServer(s){return Ge.post(`mcp/servers/${s}/disconnect`)}async refreshTools(s){return Ge.post(`mcp/servers/${s}/refresh`)}async getTools(s){const n=s?`mcp/servers/${s}/tools`:"mcp/tools",a=await Ge.get(n);return(Array.isArray(a.tools)?a.tools:[]).map((r,l)=>hr(r,s,l)).filter(r=>!!r)}async importServers(s){return Ge.post("mcp/servers/import",s)}}const Pn=new fr,yr=5e3,Je=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,en=(e,s)=>`${e}:${s}`,xr=(e={})=>{const{service:s=Pn,autoRefreshMs:n=yr,autoRefreshEnabled:a=!0}=e,[o,r]=i.useState([]),[l,m]=i.useState(null),[c,p]=i.useState({}),[d,b]=i.useState({}),[f,v]=i.useState({}),[T,u]=i.useState(!1),[M,j]=i.useState(!1),[x,E]=i.useState(!1),[S,P]=i.useState(null),ee=i.useRef({}),R=i.useCallback(L=>{const W=new Set(L.map(se=>se.id)),Q=L.map(se=>{const qe=ee.current[se.id]??se.config,Ie={...qe,id:se.id,name:qe.name??se.name};return ee.current[se.id]=Ie,{...se,name:se.name||Ie.name||se.id,enabled:se.enabled??Ie.enabled,config:Ie}});return Object.keys(ee.current).forEach(se=>{W.has(se)||delete ee.current[se]}),Q},[]),q=i.useCallback(async({silent:L=!1}={})=>{L||u(!0);try{const W=await s.getServers(),Q=R(W);r(Q),m(se=>{var we;return se&&Q.some(qe=>qe.id===se)?se:((we=Q[0])==null?void 0:we.id)??null}),P(null)}catch(W){throw P(Je(W,"Failed to load MCP servers")),W}finally{L||u(!1)}},[R,s]),G=i.useCallback(async(L,W=!1)=>{if(!L)return[];if(!W&&c[L])return c[L];b(Q=>({...Q,[L]:!0}));try{const Q=await s.getTools(L);return p(se=>({...se,[L]:Q})),P(null),Q}catch(Q){throw P(Je(Q,"Failed to load MCP tools")),Q}finally{b(Q=>({...Q,[L]:!1}))}},[s,c]),h=i.useCallback((L,W,Q)=>{const se=en(L,W);v(we=>({...we,[se]:Q}))},[]),y=i.useCallback(async L=>{j(!0);try{await s.addServer(L),ee.current[L.id]=L,await q()}catch(W){throw P(Je(W,"Failed to add MCP server")),W}finally{j(!1)}},[q,s]),D=i.useCallback(async(L,W)=>{j(!0);try{const Q={...W,id:L};await s.updateServer(L,Q),ee.current[L]=Q,await q()}catch(Q){throw P(Je(Q,"Failed to update MCP server")),Q}finally{j(!1)}},[q,s]),_=i.useCallback(async L=>{h(L,"delete",!0);try{await s.deleteServer(L),p(W=>{const Q={...W};return delete Q[L],Q}),delete ee.current[L],await q()}catch(W){throw P(Je(W,"Failed to delete MCP server")),W}finally{h(L,"delete",!1)}},[q,s,h]),O=i.useCallback(async L=>{h(L,"connect",!0);try{await s.connectServer(L),await q({silent:!0})}catch(W){throw P(Je(W,"Failed to connect MCP server")),W}finally{h(L,"connect",!1)}},[q,s,h]),X=i.useCallback(async L=>{h(L,"disconnect",!0);try{await s.disconnectServer(L),await q({silent:!0})}catch(W){throw P(Je(W,"Failed to disconnect MCP server")),W}finally{h(L,"disconnect",!1)}},[q,s,h]),A=i.useCallback(async L=>{h(L,"refresh",!0);try{await s.refreshTools(L),await G(L,!0),await q({silent:!0})}catch(W){throw P(Je(W,"Failed to refresh MCP tools")),W}finally{h(L,"refresh",!1)}},[G,q,s,h]),H=i.useCallback(async()=>{E(!0);try{const L=o.map(W=>W.id);await Promise.all(L.map(async W=>{try{await s.refreshTools(W)}catch{}})),await q(),l&&await G(l,!0)}catch(L){throw P(Je(L,"Failed to refresh MCP status")),L}finally{E(!1)}},[G,q,l,o,s]),V=i.useCallback(L=>{m(L)},[]),oe=i.useCallback((L,W)=>!!f[en(L,W)],[f]),ce=i.useMemo(()=>l?c[l]??[]:[],[l,c]),K=i.useMemo(()=>l?!!d[l]:!1,[l,d]);return i.useEffect(()=>{q().catch(()=>{})},[q]),i.useEffect(()=>{if(!a||n<=0)return;const L=window.setInterval(()=>{q({silent:!0}).catch(()=>{})},n);return()=>{window.clearInterval(L)}},[a,n,q]),i.useEffect(()=>{l&&G(l).catch(()=>{})},[G,l]),{servers:o,selectedServerId:l,selectedServerTools:ce,isLoadingServers:T,isMutatingConfig:M,isRefreshingAll:x,isSelectedServerToolsLoading:K,error:S,setSelectedServerId:V,refreshServers:q,addServer:y,updateServer:D,deleteServer:_,connectServer:O,disconnectServer:X,refreshServerTools:A,refreshAll:H,isServerActionLoading:oe}},br={[N.Connecting]:"blue",[N.Ready]:"green",[N.Degraded]:"orange",[N.Stopped]:"default",[N.Error]:"red"},vr=e=>e===N.Connecting||e===N.Ready||e===N.Degraded,Tr=e=>{if(!e)return;const s=e.replace(/\s+/g," ").trim();if(s)return s.length>180?`${s.slice(0,180)}...`:s},jr=({servers:e,loading:s=!1,selectedServerId:n,onSelectServer:a,onEditServer:o,onDeleteServer:r,onConnectServer:l,onDisconnectServer:m,onRefreshTools:c,isServerActionLoading:p})=>{const{t:d}=Z(),{token:b}=fe.useToken(),f=i.useMemo(()=>({[N.Connecting]:d("settings.mcpTab.statusHelp.connecting"),[N.Ready]:d("settings.mcpTab.statusHelp.ready"),[N.Degraded]:d("settings.mcpTab.statusHelp.degraded"),[N.Stopped]:d("settings.mcpTab.statusHelp.stopped"),[N.Error]:d("settings.mcpTab.statusHelp.error")}),[d]),v=i.useMemo(()=>[{key:"name",title:d("settings.mcpServerTable.columns.name"),render:(T,u)=>u.name||u.id},{key:"transport",title:d("settings.mcpServerTable.columns.transportType"),render:(T,u)=>u.config.transport.type==="sse"?d("settings.mcpServerTable.transportOptions.sse"):d("settings.mcpServerTable.transportOptions.stdio"),width:140},{key:"status",title:d("settings.mcpServerTable.columns.status"),render:(T,u)=>{var S,P;const M=((S=u.runtime)==null?void 0:S.status)??N.Stopped,j=Tr((P=u.runtime)==null?void 0:P.last_error),x=f[M],E={[N.Connecting]:d("settings.mcpTab.status.connecting"),[N.Ready]:d("settings.mcpTab.status.ready"),[N.Degraded]:d("settings.mcpTab.status.degraded"),[N.Stopped]:d("settings.mcpTab.status.stopped"),[N.Error]:d("settings.mcpTab.status.error")};return t.jsx(xe,{title:j?`${x} ${d("settings.mcpTab.statusLastError",{error:j})}`:x,children:t.jsx(ue,{color:M===N.Stopped?void 0:br[M],style:{marginInlineEnd:0,cursor:"help",...M===N.Stopped?{background:b.colorFillSecondary,borderColor:b.colorBorderSecondary,color:b.colorTextSecondary}:void 0},children:E[M]})})},width:120},{key:"toolCount",title:d("settings.mcpServerTable.columns.toolCount"),render:(T,u)=>{var M;return((M=u.runtime)==null?void 0:M.tool_count)??0},width:100},{key:"actions",title:d("settings.mcpServerTable.columns.actions"),width:360,render:(T,u)=>{var x;const M=((x=u.runtime)==null?void 0:x.status)??N.Stopped,j=vr(M);return t.jsxs(I,{size:b.marginXS,children:[t.jsx(z,{size:"small",onClick:E=>{E.stopPropagation(),o==null||o(u)},children:d("settings.mcpServerTable.actions.edit")}),t.jsx(cs,{title:d("settings.mcpServerTable.deleteTitle"),description:d("settings.mcpServerTable.deleteDescription",{name:u.name||u.id}),onConfirm:()=>r==null?void 0:r(u),okText:d("settings.mcpServerTable.actions.delete"),okButtonProps:{danger:!0,loading:p==null?void 0:p(u.id,"delete")},children:t.jsx(z,{size:"small",danger:!0,loading:p==null?void 0:p(u.id,"delete"),onClick:E=>E.stopPropagation(),children:d("settings.mcpServerTable.actions.delete")})}),j?t.jsx(z,{size:"small",onClick:E=>{E.stopPropagation(),m==null||m(u)},loading:p==null?void 0:p(u.id,"disconnect"),children:d("settings.mcpServerTable.actions.disconnect")}):t.jsx(z,{size:"small",type:"primary",ghost:!0,onClick:E=>{E.stopPropagation(),l==null||l(u)},loading:p==null?void 0:p(u.id,"connect"),children:d("settings.mcpServerTable.actions.connect")}),t.jsx(z,{size:"small",onClick:E=>{E.stopPropagation(),c==null||c(u)},loading:p==null?void 0:p(u.id,"refresh"),children:d("settings.mcpServerTable.actions.refreshTools")})]})}}],[p,l,r,m,o,c,f,d,b.colorBorderSecondary,b.colorFillSecondary,b.colorTextSecondary,b.marginXS]);return t.jsx(et,{rowKey:"id",columns:v,dataSource:e,loading:s,pagination:!1,locale:{emptyText:d("settings.mcpServerTable.empty")},onRow:T=>({onClick:()=>a==null?void 0:a(T.id),style:{cursor:a?"pointer":"default",backgroundColor:n===T.id?b.colorFillSecondary:void 0}})})},{Text:tn}=le,{TextArea:Sr}=U,sn=e=>{const s=e??ps(""),n=s.transport,a=n.type==="stdio"?Object.entries(n.env??{}).map(([r,l])=>({key:r,value:l})):[],o=n.type==="sse"?n.headers.map(r=>({name:r.name,value:r.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:o,requestTimeoutMs:s.request_timeout_ms||Yt,healthcheckIntervalMs:s.healthcheck_interval_ms||Zt,allowedTools:s.allowed_tools||[],deniedTools:s.denied_tools||[]}},_r=e=>e.reduce((s,n)=>{var o;const a=(o=n.key)==null?void 0:o.trim();return a&&(s[a]=n.value??""),s},{}),kr=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??""}}),nn=(e,s,n)=>{var d,b,f;const a=s==="edit"&&(n==null?void 0:n.id)||e.id,o=(d=e.name)==null?void 0:d.trim(),r=typeof e.requestTimeoutMs=="number"?e.requestTimeoutMs:(n==null?void 0:n.request_timeout_ms)??Yt,l=typeof e.healthcheckIntervalMs=="number"?e.healthcheckIntervalMs:(n==null?void 0:n.healthcheck_interval_ms)??Zt,m=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)??[],p=e.transportType==="sse"?{type:"sse",url:((b=e.url)==null?void 0:b.trim())||"",headers:kr(e.headerEntries||[]),connect_timeout_ms:(n==null?void 0:n.transport.type)==="sse"?n.transport.connect_timeout_ms??us:us}:{type:"stdio",command:((f=e.command)==null?void 0:f.trim())||"",args:e.args||[],env:_r(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??Ht:Ht};return{id:a,name:o||void 0,enabled:e.enabled,transport:p,request_timeout_ms:r,healthcheck_interval_ms:l,allowed_tools:m,denied_tools:c,reconnect:n==null?void 0:n.reconnect}},an=e=>JSON.stringify(e||ps(""),null,2),bs=(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 o=typeof a.id=="string"?a.id:"";if(!o.trim())return{valid:!1,error:s("settings.mcpServerForm.missingIdField")};if(a.transport&&typeof a.transport=="object"){const b=a;return!b.transport||typeof b.transport!="object"?{valid:!1,error:s("settings.mcpServerForm.missingTransportField")}:{valid:!0,config:b}}const r=typeof a.enabled=="boolean"?a.enabled:typeof a.disabled=="boolean"?!a.disabled:!0,l=typeof a.request_timeout_ms=="number"?a.request_timeout_ms:Yt,m=typeof a.healthcheck_interval_ms=="number"?a.healthcheck_interval_ms:Zt,c=Array.isArray(a.allowed_tools)?a.allowed_tools.filter(b=>typeof b=="string"):[],p=Array.isArray(a.denied_tools)?a.denied_tools.filter(b=>typeof b=="string"):[],d=typeof a.name=="string"?a.name:void 0;if(typeof a.url=="string"){const b=a.headers,f=Array.isArray(b)?b.map(T=>{if(!T||typeof T!="object")return null;const u=T,M=typeof u.name=="string"?u.name:"",j=typeof u.value=="string"?u.value:"";return M.trim()?{name:M,value:j}:null}).filter(T=>!!T):b&&typeof b=="object"?Object.entries(b).filter(([T])=>T.trim()).map(([T,u])=>({name:T,value:typeof u=="string"?u:""})):[],v=typeof a.connect_timeout_ms=="number"?a.connect_timeout_ms:us;return{valid:!0,config:{id:o,name:d,enabled:r,transport:{type:"sse",url:a.url,headers:f,connect_timeout_ms:v},request_timeout_ms:l,healthcheck_interval_ms:m,allowed_tools:c,denied_tools:p,reconnect:void 0}}}if(typeof a.command=="string"){const b=Array.isArray(a.args)?a.args.filter(u=>typeof u=="string"):[],f=a.env,v=f&&typeof f=="object"?Object.entries(f).reduce((u,[M,j])=>(typeof j=="string"&&(u[M]=j),u),{}):{},T=typeof a.startup_timeout_ms=="number"?a.startup_timeout_ms:Ht;return{valid:!0,config:{id:o,name:d,enabled:r,transport:{type:"stdio",command:a.command,args:b,cwd:typeof a.cwd=="string"?a.cwd:void 0,env:v,startup_timeout_ms:T},request_timeout_ms:l,healthcheck_interval_ms:m,allowed_tools:c,denied_tools:p,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")})}}},wr=({open:e,mode:s,initialConfig:n,confirmLoading:a=!1,onCancel:o,onSubmit:r})=>{const{t:l}=Z(),[m]=k.useForm(),[c,p]=i.useState("form"),[d,b]=i.useState(""),[f,v]=i.useState(null),T=i.useMemo(()=>sn(n),[n]),u=k.useWatch("transportType",m)??"stdio";i.useEffect(()=>{e&&(m.setFieldsValue(T),b(an(n)),v(null),p("form"))},[m,T,n,e]);const M=()=>{m.resetFields(),b(""),v(null),o()},j=async()=>{if(c==="json"){const S=bs(d,l);if(!S.valid){v(S.error);return}v(null);try{await r(S.config),b("")}catch(P){console.error("MCP server JSON submission error:",P)}return}try{const S=await m.validateFields(),P=nn(S,s,n);await r(P),m.resetFields()}catch(S){console.error("MCP server form submission error:",S)}},x=S=>{b(S),f&&bs(S,l).valid&&v(null)},E=S=>{if(S==="json")try{const P=m.getFieldsValue(),ee=nn(P,s,n);b(JSON.stringify(ee,null,2))}catch{b(an(n))}else{const P=bs(d,l);P.valid&&m.setFieldsValue(sn(P.config))}p(S),v(null)};return t.jsxs(ot,{title:l(s==="edit"?"settings.mcpServerForm.editTitle":"settings.mcpServerForm.addTitle"),open:e,onCancel:M,onOk:()=>{j()},okText:l("settings.mcpServerForm.save"),destroyOnClose:!0,forceRender:!0,confirmLoading:a,width:720,children:[t.jsx("div",{style:{marginBottom:16},children:t.jsxs(bt.Group,{value:c,onChange:S=>E(S.target.value),optionType:"button",buttonStyle:"solid",children:[t.jsxs(bt.Button,{value:"form",children:[t.jsx(pa,{})," ",l("settings.mcpServerForm.modeForm")]}),t.jsxs(bt.Button,{value:"json",children:[t.jsx(ha,{})," ",l("settings.mcpServerForm.modeJson")]})]})}),c==="json"&&f&&t.jsx(ke,{type:"error",message:l("settings.mcpServerForm.jsonError"),description:f,showIcon:!0,style:{marginBottom:16},closable:!0,onClose:()=>v(null)}),c==="json"?t.jsx(Sr,{value:d,onChange:S=>x(S.target.value),rows:20,style:{fontFamily:"monospace",fontSize:13},placeholder:JSON.stringify(ps("example-server"),null,2)}):t.jsxs(k,{layout:"vertical",form:m,preserve:!0,initialValues:T,children:[t.jsx(k.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(U,{placeholder:"filesystem",disabled:s==="edit",autoComplete:"off"})}),t.jsx(k.Item,{name:"name",label:l("settings.mcpServerForm.displayName"),children:t.jsx(U,{placeholder:"Filesystem MCP",autoComplete:"off"})}),t.jsx(k.Item,{name:"enabled",label:l("settings.mcpServerForm.enabled"),valuePropName:"checked",extra:l("settings.mcpServerForm.enabledHelp"),children:t.jsx(ge,{})}),t.jsx(k.Item,{name:"transportType",label:l("settings.mcpServerForm.transportType"),rules:[{required:!0,message:l("settings.mcpServerForm.transportTypeRequired")}],children:t.jsx(ae,{options:[{label:l("settings.mcpServerForm.transportOptions.stdio"),value:"stdio"},{label:l("settings.mcpServerForm.transportOptions.sse"),value:"sse"}]})}),u==="stdio"?t.jsxs(t.Fragment,{children:[t.jsx(k.Item,{name:"command",label:l("settings.mcpServerForm.command"),rules:[{required:!0,message:l("settings.mcpServerForm.commandRequired")}],children:t.jsx(U,{placeholder:"npx",autoComplete:"off"})}),t.jsx(k.Item,{name:"args",label:l("settings.mcpServerForm.arguments"),children:t.jsx(ae,{mode:"tags",tokenSeparators:[","],placeholder:l("settings.mcpServerForm.argumentsPlaceholder"),open:!1})}),t.jsx(k.List,{name:"envEntries",children:(S,{add:P,remove:ee})=>t.jsxs(I,{direction:"vertical",style:{width:"100%"},children:[t.jsxs(I,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[t.jsx(tn,{strong:!0,children:l("settings.mcpServerForm.envVars")}),t.jsx(z,{icon:t.jsx(Ut,{}),onClick:()=>P({key:"",value:""}),type:"dashed",children:l("settings.mcpServerForm.addEnv")})]}),S.map(R=>t.jsxs(I,{align:"baseline",style:{display:"flex"},children:[t.jsx(k.Item,{...R,name:[R.name,"key"],rules:[{required:!0,message:l("settings.mcpServerForm.keyRequired")}],children:t.jsx(U,{placeholder:"MCP_ROOT",autoComplete:"off"})}),t.jsx(k.Item,{...R,name:[R.name,"value"],children:t.jsx(U,{placeholder:"/Users/me/workspace",autoComplete:"off"})}),t.jsx(z,{danger:!0,type:"text",icon:t.jsx(Js,{}),onClick:()=>ee(R.name),"aria-label":l("settings.mcpServerForm.removeEnv","Remove environment variable")})]},R.key))]})})]}):t.jsxs(t.Fragment,{children:[t.jsx(k.Item,{name:"url",label:l("settings.mcpServerForm.sseUrl"),rules:[{required:!0,message:l("settings.mcpServerForm.sseUrlRequired")},{validator:async(S,P)=>{if(P)try{new URL(P)}catch{throw new Error(l("settings.mcpServerForm.validUrlRequired"))}}}],children:t.jsx(U,{placeholder:"http://localhost:4000/sse",autoComplete:"off"})}),t.jsx(k.List,{name:"headerEntries",children:(S,{add:P,remove:ee})=>t.jsxs(I,{direction:"vertical",style:{width:"100%"},children:[t.jsxs(I,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[t.jsx(tn,{strong:!0,children:l("settings.mcpServerForm.headers")}),t.jsx(z,{icon:t.jsx(Ut,{}),onClick:()=>P({name:"",value:""}),type:"dashed",children:l("settings.mcpServerForm.addHeader")})]}),S.map(R=>t.jsxs(I,{align:"baseline",style:{display:"flex"},children:[t.jsx(k.Item,{...R,name:[R.name,"name"],rules:[{required:!0,message:l("settings.mcpServerForm.headerNameRequired")}],children:t.jsx(U,{placeholder:"Authorization",autoComplete:"off"})}),t.jsx(k.Item,{...R,name:[R.name,"value"],children:t.jsx(U,{placeholder:"Bearer token",autoComplete:"off"})}),t.jsx(z,{danger:!0,type:"text",icon:t.jsx(Js,{}),onClick:()=>ee(R.name),"aria-label":l("settings.mcpServerForm.removeHeader","Remove header")})]},R.key))]})})]})]})]})},is=e=>!!e&&typeof e=="object"&&!Array.isArray(e),ut=(e,s)=>{const n=e[s];return typeof n=="string"?n:void 0},rn=(e,s)=>{const n=e[s];return typeof n=="boolean"?n:void 0},Cr=(e,s)=>{const n=e[s];return Array.isArray(n)?n:void 0},Nt=e=>{if(!is(e))return"any";const s=e.type;if(typeof s=="string"){if(s==="array"){const r=e.items;return`array<${Nt(r)}>`}return s==="object"?"object":s}if(Array.isArray(s)){const r=s.filter(l=>typeof l=="string").map(l=>l==="array"?"array<any>":l);return r.length>0?r.join(" | "):"any"}const n=Array.isArray(e.oneOf)?e.oneOf:null;if(n)return n.map(Nt).join(" | ")||"any";const a=Array.isArray(e.anyOf)?e.anyOf:null;if(a)return a.map(Nt).join(" | ")||"any";const o=Array.isArray(e.allOf)?e.allOf:null;return o&&o.map(Nt).join(" & ")||"any"},Mr=e=>{if(!is(e))return null;const s=e.properties;if(!is(s))return{schemaUri:ut(e,"$schema"),title:ut(e,"title"),description:ut(e,"description"),additionalProperties:rn(e,"additionalProperties"),fields:[]};const n=new Set((Cr(e,"required")??[]).filter(o=>typeof o=="string").map(o=>o)),a=Object.entries(s).map(([o,r])=>{const l=is(r)?r:void 0;return{name:o,type:Nt(r),required:n.has(o),description:l?ut(l,"description"):void 0,defaultValue:l?l.default:void 0,enumValues:l&&Array.isArray(l.enum)?l.enum:void 0}});return a.sort((o,r)=>o.required!==r.required?o.required?-1:1:o.name.localeCompare(r.name)),{schemaUri:ut(e,"$schema"),title:ut(e,"title"),description:ut(e,"description"),additionalProperties:rn(e,"additionalProperties"),fields:a}},{Text:Ue}=le,Er=e=>e===void 0?"":e===null?"null":typeof e=="string"?e:Cn(e,0),Dr=({schema:e})=>{const{token:s}=fe.useToken(),{t:n}=Z(),a=i.useMemo(()=>Mr(e),[e]);if(!a)return t.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:Cn(e,2)});const o=[{title:n("components.jsonSchema.field"),dataIndex:"name",key:"name",width:180,render:l=>t.jsx(Ue,{code:!0,children:l})},{title:n("components.jsonSchema.type"),dataIndex:"type",key:"type",width:140,render:l=>t.jsx(Ue,{children:l})},{title:n("components.jsonSchema.required"),dataIndex:"required",key:"required",width:110,render:l=>l?t.jsx(Ue,{strong:!0,style:{color:s.colorError},children:n("components.jsonSchema.yes")}):t.jsx(Ue,{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(Ue,{type:"secondary",children:"-"}):t.jsx(Ue,{children:Er(l)})},{title:n("components.jsonSchema.description"),dataIndex:"description",key:"description",render:l=>l?t.jsx(Ue,{style:{whiteSpace:"pre-wrap"},children:l}):t.jsx(Ue,{type:"secondary",children:"-"})}],r=(a.fields??[]).map(l=>({...l,key:l.name}));return t.jsxs("div",{style:{width:"100%"},children:[t.jsx(_e,{size:"small",column:1,items:[a.schemaUri?{key:"schema",label:"$schema",children:t.jsx(Ue,{code:!0,children:a.schemaUri})}:null,typeof a.additionalProperties=="boolean"?{key:"additionalProperties",label:"additionalProperties",children:t.jsx(Ue,{children:a.additionalProperties?"true":"false"})}:null].filter(Boolean)}),t.jsx(et,{size:"small",pagination:!1,columns:o,dataSource:r,locale:{emptyText:n("components.jsonSchema.noProperties")},style:{marginTop:s.marginSM}})]})},{Text:It}=le,Pr=(e,s)=>`mcp__${e}__${s}`,Ir=({server:e,tools:s,loading:n=!1})=>{const{t:a}=Z();return t.jsx(F,{title:a("settings.mcpToolList.title"),size:"small",children:e?t.jsx(Ke,{loading:n,dataSource:s,locale:{emptyText:a("settings.mcpToolList.empty")},renderItem:o=>{const r=Pr(o.server_id,o.original_name);return t.jsx(Ke.Item,{children:t.jsxs(I,{direction:"vertical",size:2,style:{width:"100%"},children:[t.jsx(It,{strong:!0,children:o.original_name}),t.jsx(It,{type:"secondary",children:o.description||a("settings.mcpToolList.noDescription")}),t.jsx(It,{code:!0,children:o.alias}),t.jsxs(It,{type:"secondary",children:[a("settings.mcpToolList.aliasMapping"),": ",t.jsx(It,{code:!0,children:r})]}),o.parameters!==void 0&&t.jsx(Fs,{size:"small",items:[{key:"schema",label:a("settings.mcpToolList.parametersSchema"),children:t.jsx(Dr,{schema:o.parameters})}]})]})})}}):t.jsx(Ae,{image:Ae.PRESENTED_IMAGE_SIMPLE,description:a("settings.mcpToolList.selectServerHint")})})},{Text:Ft}=le,{useToken:Fr}=fe,{TextArea:Rr}=U,on={[N.Connecting]:"processing",[N.Ready]:"success",[N.Degraded]:"warning",[N.Stopped]:"default",[N.Error]:"error"},Ar=()=>({[N.Connecting]:0,[N.Ready]:0,[N.Degraded]:0,[N.Stopped]:0,[N.Error]:0}),gt=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,Lr=e=>{var n,a,o;const s={};for(const r of e){const l=(n=r.id)==null?void 0:n.trim();if(!l)continue;const c=!(r.enabled??r.config.enabled),p=r.config.transport;if(p.type==="sse"){const b={};for(const v of p.headers??[]){const T=(a=v.name)==null?void 0:a.trim();T&&(b[T]=v.value??"")}const f={url:p.url};c&&(f.disabled=!0),Object.keys(b).length&&(f.headers=b),s[l]=f;continue}const d={command:p.command};c&&(d.disabled=!0),(o=p.args)!=null&&o.length&&(d.args=p.args),p.cwd&&(d.cwd=p.cwd),p.env&&Object.keys(p.env).length&&(d.env=p.env),s[l]=d}return{mcpServers:s}},zr=()=>{const{t:e}=Z(),{token:s}=Fr(),[n,a]=Tt.useMessage(),{servers:o,selectedServerId:r,selectedServerTools:l,isLoadingServers:m,isMutatingConfig:c,isRefreshingAll:p,isSelectedServerToolsLoading:d,error:b,setSelectedServerId:f,addServer:v,updateServer:T,deleteServer:u,connectServer:M,disconnectServer:j,refreshServerTools:x,refreshAll:E,isServerActionLoading:S}=xr(),P=i.useMemo(()=>({[N.Connecting]:e("settings.mcpTab.status.connecting"),[N.Ready]:e("settings.mcpTab.status.ready"),[N.Degraded]:e("settings.mcpTab.status.degraded"),[N.Stopped]:e("settings.mcpTab.status.stopped"),[N.Error]:e("settings.mcpTab.status.error")}),[e]),ee=i.useMemo(()=>({[N.Connecting]:e("settings.mcpTab.statusHelp.connecting"),[N.Ready]:e("settings.mcpTab.statusHelp.ready"),[N.Degraded]:e("settings.mcpTab.statusHelp.degraded"),[N.Stopped]:e("settings.mcpTab.statusHelp.stopped"),[N.Error]:e("settings.mcpTab.statusHelp.error")}),[e]),[R,q]=i.useState(!1),[G,h]=i.useState("create"),[y,D]=i.useState(null),[_,O]=i.useState(!1),[X,A]=i.useState("merge"),[H,V]=i.useState(""),[oe,ce]=i.useState(null),[K,L]=i.useState(!1),W=i.useMemo(()=>r?o.find(g=>g.id===r)??null:null,[r,o]),Q=i.useMemo(()=>{const g=Ar();let ne=0;return o.forEach(de=>{var me,Me;const Ce=((me=de.runtime)==null?void 0:me.status)??N.Stopped;g[Ce]+=1,ne+=((Me=de.runtime)==null?void 0:Me.tool_count)??0}),{byStatus:g,totalServers:o.length,totalTools:ne}},[o]),se={background:s.colorFillSecondary,borderColor:s.colorBorderSecondary,color:s.colorTextSecondary},we=async g=>{try{await u(g.id),n.success(e("settings.mcpTab.serverDeleted"))}catch(ne){n.error(gt(ne,e("settings.mcpTab.deleteServerFailed")))}},qe=async g=>{try{await M(g.id),n.success(e("settings.mcpTab.connectedTo",{name:g.name||g.id}))}catch(ne){n.error(gt(ne,e("settings.mcpTab.connectServerFailed")))}},Ie=async g=>{try{await j(g.id),n.success(e("settings.mcpTab.disconnected",{name:g.name||g.id}))}catch(ne){n.error(gt(ne,e("settings.mcpTab.disconnectServerFailed")))}},kt=async g=>{try{await x(g.id),n.success(e("settings.mcpTab.toolsRefreshedFor",{name:g.name||g.id}))}catch(ne){n.error(gt(ne,e("settings.mcpTab.refreshToolsFailed")))}},ft=async()=>{try{await E(),n.success(e("settings.mcpTab.statusRefreshed"))}catch(g){n.error(gt(g,e("settings.mcpTab.refreshStatusFailed")))}},wt=()=>{D(null),h("create"),q(!0)},Ct=g=>{D(g),h("edit"),q(!0)},it=async g=>{try{if(G==="edit"){if(!y){n.error(e("settings.mcpTab.noServerForEditing"));return}await T(y.id,g),n.success(e("settings.mcpTab.savedServer",{name:y.name||y.id}))}else await v(g),n.success(e("settings.mcpTab.addedServer",{name:g.name||g.id}));q(!1),D(null)}catch(ne){n.error(gt(ne,e("settings.mcpTab.saveServerFailed")))}},lt=()=>{O(!0),ce(null),A("merge"),V("")},Le=async()=>{const g=Lr(o),ne=JSON.stringify(g,null,2);try{await Mn(ne),n.success(e("settings.mcpTab.copiedConfig"))}catch{O(!0),ce(null),A("merge"),V(ne),n.warning(e("settings.mcpTab.clipboardUnavailable"))}},Mt=async()=>{var Ce;ce(null);let g;try{g=JSON.parse(H)}catch(me){ce(`${e("settings.mcpTab.invalidJsonPrefix")}: ${me instanceof Error?me.message:e("settings.mcpTab.unknownError")}`);return}if(!g||typeof g!="object"){ce(e("settings.mcpTab.jsonMustBeObject"));return}const de=g.mcpServers;if(!de||typeof de!="object"){ce(e("settings.mcpTab.missingMcpServers"));return}L(!0);try{const me=await Pn.importServers({mcpServers:de,mode:X}),Me=((Ce=me.start_errors)==null?void 0:Ce.length)??0;n.success(e("settings.mcpTab.importSummary",{count:me.server_ids.length,added:me.added,updated:me.updated,removed:me.removed,failed:Me})),Me&&n.warning(e("settings.mcpTab.importStartFailures")),O(!1),V(""),await ft()}catch(me){ce(gt(me,e("settings.mcpTab.importFailed")))}finally{L(!1)}};return t.jsxs(I,{direction:"vertical",size:s.marginMD,style:{width:"100%"},children:[a,b?t.jsx(ke,{type:"error",showIcon:!0,message:b}):null,t.jsx(F,{size:"small",title:e("settings.mcpTab.overviewTitle"),children:t.jsxs(I,{direction:"vertical",size:s.marginXS,style:{width:"100%"},children:[t.jsx(Ft,{type:"secondary",children:e("settings.mcpTab.overviewDescription")}),t.jsxs(I,{wrap:!0,children:[t.jsx(ue,{style:se,children:e("settings.mcpTab.totalServers",{count:Q.totalServers})}),t.jsx(ue,{style:se,children:e("settings.mcpTab.totalTools",{count:Q.totalTools})}),Object.values(N).map(g=>t.jsx(xe,{title:ee[g],children:t.jsxs(ue,{color:g===N.Stopped?void 0:on[g],style:{cursor:"help",...g===N.Stopped?se:void 0},children:[P[g],": ",Q.byStatus[g]]})},g))]}),t.jsx(Ft,{type:"secondary",children:e("settings.mcpTab.statusGuideTitle")}),t.jsx(I,{direction:"vertical",size:2,style:{width:"100%"},children:Object.values(N).map(g=>t.jsxs(Ft,{type:"secondary",children:[t.jsx(ue,{color:g===N.Stopped?void 0:on[g],style:{marginInlineEnd:8,...g===N.Stopped?se:void 0},children:P[g]}),ee[g]]},`guide-${g}`))})]})}),t.jsx(F,{size:"small",title:e("settings.mcpTab.serversTitle"),extra:t.jsxs(I,{children:[t.jsx(z,{type:"primary",onClick:wt,children:e("settings.mcpTab.addServer")}),t.jsx(z,{icon:t.jsx(jt,{}),loading:p,onClick:()=>{ft()},children:e("settings.mcpTab.refreshAll")}),t.jsx(z,{icon:t.jsx(En,{}),onClick:()=>void Le(),children:e("settings.mcpTab.export")}),t.jsx(z,{icon:t.jsx(fa,{}),onClick:lt,children:e("settings.mcpTab.import")})]}),children:t.jsx(jr,{servers:o,loading:m,selectedServerId:r,onSelectServer:f,onEditServer:Ct,onDeleteServer:we,onConnectServer:qe,onDisconnectServer:Ie,onRefreshTools:kt,isServerActionLoading:S})}),t.jsx(Ir,{server:W,tools:l,loading:d}),t.jsx(wr,{open:R,mode:G,initialConfig:(y==null?void 0:y.config)??null,confirmLoading:c,onCancel:()=>{c||(q(!1),D(null))},onSubmit:g=>void it(g)}),t.jsx(ot,{open:_,title:e("settings.mcpTab.importModalTitle"),okText:e("settings.mcpTab.import"),onOk:()=>void Mt(),okButtonProps:{loading:K},onCancel:()=>{K||(O(!1),ce(null))},width:800,destroyOnClose:!1,children:t.jsxs(I,{direction:"vertical",style:{width:"100%"},size:"middle",children:[t.jsxs(Ft,{type:"secondary",children:[e("settings.mcpTab.importHint"),t.jsx("br",{}),t.jsx(Ft,{code:!0,children:'{ "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "..."] } } }'})]}),t.jsxs(bt.Group,{value:X,onChange:g=>A(g.target.value),optionType:"button",buttonStyle:"solid",children:[t.jsx(bt.Button,{value:"merge",children:e("settings.mcpTab.importModeMerge")}),t.jsx(bt.Button,{value:"replace",children:e("settings.mcpTab.importModeReplace")})]}),X==="replace"?t.jsx(ke,{type:"warning",showIcon:!0,message:e("settings.mcpTab.replaceWarning")}):null,oe?t.jsx(ke,{type:"error",showIcon:!0,message:oe}):null,t.jsx(Rr,{value:H,onChange:g=>V(g.target.value),rows:14,placeholder:'{"mcpServers": { "filesystem": { "command": "...", "args": [], "env": {} } }}',spellCheck:!1})]})})]})},In=1,Or=365,Fn=e=>Number.isFinite(e)?Math.min(Or,Math.max(In,Math.floor(e??30))):30,vs=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]),o=Number(s[3]),r=new Date(Date.UTC(n,a-1,o));return r.getUTCFullYear()!==n||r.getUTCMonth()!==a-1||r.getUTCDate()!==o?null:r},Rt=e=>e.toISOString().slice(0,10),Nr=(e,s)=>{const n=new Date(e.getTime());return n.setUTCDate(n.getUTCDate()+s),n},Vr=(e,s)=>{const n=s.getTime()-e.getTime(),a=Math.floor(n/864e5)+1;return Fn(a)},zs=(e,s=new Date)=>{const n=Fn(e.days),a=Rt(s),o=vs(e.endDate)??vs(a);if(!o)return{startDate:a,endDate:a,days:In};const r=vs(e.startDate);if(r){const m=o<r?r:o;return{startDate:Rt(r),endDate:Rt(m),days:Vr(r,m)}}const l=Nr(o,-(n-1));return{startDate:Rt(l),endDate:Rt(o),days:n}},$r=15e3,qr=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,Br=(e={})=>{const{filters:s,autoRefreshMs:n=$r}=e,a=i.useMemo(()=>({startDate:s==null?void 0:s.startDate,endDate:s==null?void 0:s.endDate,days:(s==null?void 0:s.days)??30,endpoint:s==null?void 0:s.endpoint,model:s==null?void 0:s.model,limit:(s==null?void 0:s.limit)??100}),[s==null?void 0:s.startDate,s==null?void 0:s.endDate,s==null?void 0:s.days,s==null?void 0:s.endpoint,s==null?void 0:s.model,s==null?void 0:s.limit]),o=i.useMemo(()=>zs({startDate:a.startDate,endDate:a.endDate,days:a.days}),[a.days,a.endDate,a.startDate]),[r,l]=i.useState(null),[m,c]=i.useState([]),[p,d]=i.useState([]),[b,f]=i.useState(!1),[v,T]=i.useState(!1),[u,M]=i.useState(null),j=i.useCallback(async E=>{E?f(!0):T(!0);try{const S={startDate:o.startDate,endDate:o.endDate,endpoint:a.endpoint,model:a.model,limit:a.limit},[P,ee,R]=await Promise.all([Vt.getForwardSummary(S),Vt.getForwardByEndpoint(S),Vt.getForwardRequests(S)]);l(P),c(ee),d(R),M(null)}catch(S){M(qr(S,"Failed to load forward metrics"))}finally{E?f(!1):T(!1)}},[a.endpoint,a.model,a.limit,o.endDate,o.startDate]),x=i.useCallback(async()=>{await j(!1)},[j]);return i.useEffect(()=>{j(!0)},[j]),i.useEffect(()=>{if(n<=0)return;const E=window.setInterval(()=>{j(!1)},n);return()=>{window.clearInterval(E)}},[n,j]),{summary:r,endpointMetrics:m,requests:p,isLoading:b,isRefreshing:v,error:u,refresh:x}},Ur=15e3,ln=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,Hr=(e={})=>{const{filters:s,autoRefreshMs:n=Ur,service:a=Vt}=e,o=i.useMemo(()=>({startDate:s==null?void 0:s.startDate,endDate:s==null?void 0:s.endDate,model:s==null?void 0:s.model,days:(s==null?void 0:s.days)??30,granularity:(s==null?void 0:s.granularity)??"daily",sessionLimit:(s==null?void 0:s.sessionLimit)??200}),[s==null?void 0:s.startDate,s==null?void 0:s.endDate,s==null?void 0:s.model,s==null?void 0:s.days,s==null?void 0:s.granularity,s==null?void 0:s.sessionLimit]),r=i.useMemo(()=>zs({startDate:o.startDate,endDate:o.endDate,days:o.days}),[o.days,o.endDate,o.startDate]),[l,m]=i.useState(null),[c,p]=i.useState([]),[d,b]=i.useState([]),[f,v]=i.useState([]),[T,u]=i.useState(null),[M,j]=i.useState([]),[x,E]=i.useState(null),[S,P]=i.useState(!1),[ee,R]=i.useState(!1),[q,G]=i.useState(!1),[h,y]=i.useState(null),D=i.useCallback(async A=>{A?R(!0):G(!0);try{const H=a.getMemorySummary?a.getMemorySummary().catch(()=>null):Promise.resolve(null),V=a.getMemoryTimeline?a.getMemoryTimeline({days:r.days,endDate:r.endDate,granularity:o.granularity}).catch(()=>[]):Promise.resolve([]),[oe,ce,K,L,W,Q]=await Promise.all([a.getSummary({startDate:r.startDate,endDate:r.endDate}),a.getByModel({startDate:r.startDate,endDate:r.endDate}),a.getSessions({startDate:r.startDate,endDate:r.endDate,model:o.model,limit:o.sessionLimit}),a.getDaily({days:r.days,endDate:r.endDate,granularity:o.granularity}),H,V]);m(oe),p(ce),b(K),v(L),u(W),j(Q),y(null)}catch(H){y(ln(H,"Failed to load metrics"))}finally{A?R(!1):G(!1)}},[o.granularity,o.model,o.sessionLimit,r.days,r.endDate,r.startDate,a]),_=i.useCallback(async()=>{await D(!1)},[D]),O=i.useCallback(async A=>{P(!0);try{const H=await a.getSessionDetail(A);E(H)}catch(H){y(ln(H,"Failed to load session detail"))}finally{P(!1)}},[a]),X=i.useCallback(()=>{E(null)},[]);return i.useEffect(()=>{D(!0)},[D]),i.useEffect(()=>{if(n<=0)return;const A=window.setInterval(()=>{D(!1)},n);return()=>{window.clearInterval(A)}},[n,D]),{summary:l,modelMetrics:c,sessions:d,timeline:f,memorySummary:T,memoryTimeline:M,sessionDetail:x,isLoading:ee,isRefreshing:q,isSessionDetailLoading:S,error:h,refresh:_,loadSessionDetail:O,clearSessionDetail:X}},Kr=15e3,Wr=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,Gr=(e={})=>{const{filters:s,autoRefreshMs:n=Kr}=e,a=i.useMemo(()=>({startDate:s==null?void 0:s.startDate,endDate:s==null?void 0:s.endDate,days:(s==null?void 0:s.days)??30,model:s==null?void 0:s.model}),[s==null?void 0:s.days,s==null?void 0:s.endDate,s==null?void 0:s.model,s==null?void 0:s.startDate]),o=i.useMemo(()=>zs({startDate:a.startDate,endDate:a.endDate,days:a.days}),[a.days,a.endDate,a.startDate]),[r,l]=i.useState(null),[m,c]=i.useState(!1),[p,d]=i.useState(!1),[b,f]=i.useState(null),v=i.useCallback(async u=>{u?c(!0):d(!0);try{const M=await Vt.getUsageBreakdown({startDate:o.startDate,endDate:o.endDate,model:a.model});l(M),f(null)}catch(M){f(Wr(M,"Failed to load usage breakdown"))}finally{u?c(!1):d(!1)}},[a.model,o.endDate,o.startDate]),T=i.useCallback(async()=>{await v(!1)},[v]);return i.useEffect(()=>{v(!0)},[v]),i.useEffect(()=>{if(n<=0)return;const u=window.setInterval(()=>{v(!1)},n);return()=>{window.clearInterval(u)}},[n,v]),{data:r,isLoading:m,isRefreshing:p,error:b,refresh:T}},{useToken:Jr}=fe,Xr=({data:e,loading:s})=>{const{t:n}=Z(),{token:a}=Jr();if(s)return t.jsx(F,{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(F,{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 o=e.map(r=>({endpoint:r.endpoint.split(".").pop()||r.endpoint,requests:r.requests,successful:r.successful,failed:r.failed}));return t.jsx(F,{size:"small",className:"lotus-metric-card",title:n("settings.charts.endpointDistribution"),children:t.jsx("div",{style:{width:"100%",height:240},children:t.jsx(St,{children:t.jsxs(As,{data:o,children:[t.jsx(Gt,{strokeDasharray:"3 3"}),t.jsx(Jt,{dataKey:"endpoint"}),t.jsx(Xt,{}),t.jsx(_t,{formatter:(r,l)=>[`${r}`,l.charAt(0).toUpperCase()+l.slice(1)]}),t.jsx(Ls,{}),t.jsx(ds,{dataKey:"successful",fill:"var(--lotus-chart-secondary)",name:n("settings.common.successful"),fillOpacity:.9,radius:[4,4,0,0]}),t.jsx(ds,{dataKey:"failed",fill:"var(--lotus-chart-danger)",name:n("settings.common.failed"),fillOpacity:.9,radius:[4,4,0,0]})]})})})})},Ts=e=>e.replace(/\.0$/,""),Rn=e=>e.toLocaleString(),An=e=>Number.isFinite(e)?e.toLocaleString(void 0,{maximumFractionDigits:20}):String(e),Os=e=>{if(!Number.isFinite(e))return String(e);const s=Math.abs(e);if(s>=1e9){const n=s>=1e10?0:1;return`${Ts((e/1e9).toFixed(n))}B`}if(s>=1e6){const n=s>=1e7?0:1;return`${Ts((e/1e6).toFixed(n))}M`}if(s>=1e3){const n=s>=1e4?0:1;return`${Ts((e/1e3).toFixed(n))}K`}return Rn(e)},Yr=e=>Number.isFinite(e)&&Math.abs(e)>=1e3,Ln=e=>An(e),Kt=e=>{if(!Number.isFinite(e))return String(e);const s=Os(e);return Yr(e)?t.jsx(xe,{title:t.jsx("div",{children:An(e)}),children:t.jsx("span",{children:s})}):s},Qe=e=>{const s=Number(e??0);return Number.isFinite(s)?Kt(s):e==null?"-":String(e)},{useToken:Zr}=fe,Qr=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),n=Math.floor(s/60),a=s%60;if(n>=60){const o=Math.floor(n/60),r=n%60;return`${o}h ${r}m`}return n>0?`${n}m ${a}s`:`${a}s`},cn=({summary:e,loading:s})=>{const{t:n}=Z(),{token:a}=Zr();if(s)return t.jsx(tt,{active:!0,paragraph:{rows:1}});const o=e&&e.total_requests>0?(e.successful_requests/e.total_requests*100).toFixed(1):"0.0";return t.jsxs(Ne,{gutter:[a.marginSM,a.marginSM],children:[t.jsx(ie,{xs:24,sm:12,xl:6,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:n("settings.forwardMetricsCards.totalForwardRequests"),value:(e==null?void 0:e.total_requests)??0,precision:0,formatter:Qe,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),t.jsx(ie,{xs:24,sm:12,xl:6,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:n("settings.forwardMetricsCards.successRate"),value:o,suffix:"%",valueStyle:{color:Number(o)>=95?"var(--lotus-chart-secondary)":Number(o)>=80?"var(--lotus-chart-accent)":"var(--lotus-chart-danger)"}})})}),t.jsx(ie,{xs:24,sm:12,xl:6,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:n("settings.forwardMetricsCards.forwardTokens"),value:(e==null?void 0:e.total_tokens.total_tokens)??0,precision:0,formatter:Qe,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})}),t.jsx(ie,{xs:24,sm:12,xl:6,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:n("settings.forwardMetricsCards.avgResponseTime"),value:Qr(e==null?void 0:e.avg_duration_ms),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:mt}=le,eo=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`},to=e=>new Date(e).toLocaleString(),so=({requests:e,loading:s})=>{const{t:n}=Z(),a=[{title:n("settings.metricsTable.forward.columns.id"),dataIndex:"forward_id",key:"forward_id",width:120,render:o=>t.jsxs(mt,{style:{fontSize:12},copyable:!0,children:[o.slice(0,8),"..."]})},{title:n("settings.metricsTable.forward.columns.endpoint"),dataIndex:"endpoint",key:"endpoint",width:150,render:o=>t.jsx(ue,{color:"processing",children:o.split(".").pop()||o})},{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:o=>t.jsx(ue,{color:o?"purple":"processing",children:n(o?"settings.metricsTable.forward.typeStream":"settings.metricsTable.forward.typeSync")})},{title:n("settings.metricsTable.forward.columns.status"),key:"status",width:100,render:(o,r)=>{const l=r.status==="success"?"success":r.status==="error"?"error":"default";return t.jsx(ya,{status:l,text:r.status_code?t.jsxs("span",{children:[r.status,t.jsxs(mt,{type:"secondary",style:{marginLeft:4},children:["(",r.status_code,")"]})]}):r.status||"-"})}},{title:n("settings.metricsTable.forward.columns.tokens"),key:"tokens",width:100,render:(o,r)=>r.token_usage?t.jsx(mt,{children:Kt(r.token_usage.total_tokens)}):t.jsx(mt,{type:"secondary",children:"-"})},{title:n("settings.metricsTable.forward.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",width:100,render:o=>eo(o)},{title:n("settings.metricsTable.forward.columns.started"),dataIndex:"started_at",key:"started_at",width:160,render:o=>t.jsx(mt,{type:"secondary",style:{fontSize:12},children:to(o)})},{title:n("settings.metricsTable.forward.columns.error"),dataIndex:"error",key:"error",width:200,render:o=>o?t.jsx(mt,{type:"danger",ellipsis:!0,style:{maxWidth:180},children:o}):t.jsx(mt,{type:"secondary",children:"-"})}];return t.jsx(et,{rowKey:"forward_id",className:"lotus-metric-table",columns:a,dataSource:e,loading:s,size:"small",pagination:{pageSize:10,showSizeChanger:!0,showTotal:o=>n("settings.metricsTable.forward.totalRequests",{total:o}),pageSizeOptions:["10","20","50","100"]},scroll:{x:1200},locale:{emptyText:n("settings.metricsTable.forward.empty")}})},{useToken:no}=fe,ao=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString()},dn=({summary:e,loading:s})=>{const{t:n}=Z(),{token:a}=no();return s?t.jsx(tt,{active:!0,paragraph:{rows:1}}):t.jsxs(Ne,{gutter:[a.marginSM,a.marginSM],children:[t.jsx(ie,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:n("settings.unifiedMetricsCards.totalMemories"),value:(e==null?void 0:e.total_memories)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),t.jsx(ie,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{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(ie,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:n("settings.unifiedMetricsCards.memoryProjects"),value:(e==null?void 0:e.project_count)??0,precision:0,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),t.jsx(ie,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:n("settings.unifiedMetricsCards.lastReindex"),value:ao(e==null?void 0:e.last_reindex_at),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:ro}=le,oo=({data:e,loading:s})=>{const{t:n}=Z();return s?t.jsx(F,{size:"small",className:"lotus-metric-card",title:n("settings.charts.memoryTrendTitle"),children:t.jsx(tt,{active:!0,paragraph:{rows:5}})}):t.jsx(F,{size:"small",className:"lotus-metric-card",title:n("settings.charts.memoryTrendTitle"),children:e.length===0?t.jsx(Ae,{image:Ae.PRESENTED_IMAGE_SIMPLE,description:n("settings.charts.noMemoryTrend")}):t.jsxs(t.Fragment,{children:[t.jsx(ro,{type:"secondary",children:n("settings.charts.memoryTrendDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(St,{children:t.jsxs(Dn,{data:e,children:[t.jsx(Gt,{strokeDasharray:"3 3"}),t.jsx(Jt,{dataKey:"label",minTickGap:24}),t.jsx(Xt,{allowDecimals:!1}),t.jsx(_t,{}),t.jsx(Ls,{}),t.jsx(vt,{type:"monotone",dataKey:"total_memories",name:n("settings.charts.totalMemories"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),t.jsx(vt,{type:"monotone",dataKey:"created_memories",name:n("settings.charts.createdMemories"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),t.jsx(vt,{type:"monotone",dataKey:"updated_memories",name:n("settings.charts.updatedMemories"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{useToken:io}=fe,lo=e=>{const s=Math.floor(e/1e3),n=Math.floor(s/60),a=s%60;return n>0?`${n}m ${a}s`:`${a}s`},co=e=>{const s=e.filter(a=>typeof a.duration_ms=="number"&&a.duration_ms>0);if(s.length===0)return 0;const n=s.reduce((a,o)=>a+(o.duration_ms??0),0);return Math.floor(n/s.length)},un=({summary:e,sessions:s,loading:n})=>{const{t:a}=Z(),{token:o}=io();if(n)return t.jsx(tt,{active:!0,paragraph:{rows:1}});const r=co(s);return t.jsxs(Ne,{gutter:[o.marginSM,o.marginSM],children:[t.jsx(ie,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{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(ie,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:a("settings.metricsCards.totalSessions"),value:(e==null?void 0:e.total_sessions)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),t.jsx(ie,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:a("settings.metricsCards.chatTokens"),value:(e==null?void 0:e.total_tokens.total_tokens)??0,precision:0,formatter:Qe,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})}),t.jsx(ie,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:a("settings.metricsCards.totalToolCalls"),value:(e==null?void 0:e.total_tool_calls)??0,precision:0,formatter:Qe,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),t.jsx(ie,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:a("settings.metricsCards.tokensSaved",{defaultValue:"Saved Tokens"}),value:(e==null?void 0:e.total_tokens_saved)??0,precision:0,formatter:Qe,valueStyle:{color:"var(--lotus-chart-cyan)"}})})}),t.jsx(ie,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:a("settings.metricsCards.toolContextSavedTokens",{defaultValue:"Tool Context Saved Tokens"}),value:(e==null?void 0:e.tool_context_tokens_saved)??0,precision:0,formatter:Qe,valueStyle:{color:"var(--lotus-chart-accent)"}})})}),t.jsx(ie,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:a("settings.metricsCards.compressionEvents",{defaultValue:"Compression Events"}),value:(e==null?void 0:e.total_compression_events)??0,precision:0,formatter:Qe,valueStyle:{color:"var(--lotus-chart-secondary)"}})})}),t.jsx(ie,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:a("settings.metricsCards.avgSessionDuration"),value:r>0?lo(r):"-",valueStyle:{color:"var(--lotus-chart-accent)"}})})})]})},{Text:uo}=le,gn=["var(--lotus-chart-primary)","var(--lotus-chart-secondary)","var(--lotus-chart-accent)","var(--lotus-chart-purple)","var(--lotus-chart-cyan)"],go=({data:e,loading:s})=>{const{t:n}=Z();if(s)return t.jsx(F,{size:"small",className:"lotus-metric-card",title:n("settings.charts.modelDistribution"),children:t.jsx(tt,{active:!0,paragraph:{rows:5}})});const a=e.map(o=>({name:o.model,value:o.tokens.total_tokens}));return t.jsx(F,{size:"small",className:"lotus-metric-card",title:n("settings.charts.modelDistribution"),children:a.length===0?t.jsx(Ae,{image:Ae.PRESENTED_IMAGE_SIMPLE,description:n("settings.charts.noModelMetrics")}):t.jsxs(t.Fragment,{children:[t.jsx(uo,{type:"secondary",children:n("settings.charts.modelDistributionDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(St,{children:t.jsxs(Ca,{children:[t.jsx(Ma,{data:a,cx:"50%",cy:"50%",outerRadius:90,fill:"var(--lotus-chart-primary)",dataKey:"value",nameKey:"name",label:!0,children:a.map((o,r)=>t.jsx(Ea,{fill:gn[r%gn.length]},`${o.name}-${r}`))}),t.jsx(_t,{formatter:o=>Ln(o)})]})})})]})})},mo=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?"-":s.toLocaleString()},po=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),n=Math.floor(s/60),a=s%60;if(n>=60){const o=Math.floor(n/60),r=n%60;return`${o}h ${r}m`}return n>0?`${n}m ${a}s`:`${a}s`},ho=e=>{switch(e){case"completed":return"success";case"running":return"processing";case"awaiting_response":return"gold";case"error":return"error";case"cancelled":return"warning";default:return"default"}},fo=(e,s)=>{switch(e){case"awaiting_response":return s("settings.metricsTable.session.status.awaitingResponse",{defaultValue:"Awaiting Response"});case"running":return s("settings.metricsTable.session.status.running",{defaultValue:"Running"});case"completed":return s("settings.metricsTable.session.status.completed",{defaultValue:"Completed"});case"error":return s("settings.metricsTable.session.status.error",{defaultValue:"Error"});case"cancelled":return s("settings.metricsTable.session.status.cancelled",{defaultValue:"Cancelled"});default:return e}},yo=({sessions:e,loading:s,onSelectSession:n})=>{const{t:a}=Z(),o=[{title:a("settings.metricsTable.session.columns.session"),dataIndex:"session_id",key:"session_id",render:r=>t.jsx(xe,{title:r,children:t.jsxs("span",{children:[r.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:r=>t.jsx(ue,{color:ho(r),children:fo(r,a)})},{title:a("settings.metricsTable.session.columns.started"),dataIndex:"started_at",key:"started_at",render:r=>mo(r),width:200,sorter:(r,l)=>new Date(r.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:r=>po(r),width:120},{title:a("settings.metricsTable.session.columns.tokens"),key:"tokens",render:(r,l)=>Kt(l.total_token_usage.total_tokens),width:120,sorter:(r,l)=>r.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:(r,l)=>r.tool_call_count-l.tool_call_count},{title:a("settings.metricsTable.session.columns.messages"),dataIndex:"message_count",key:"message_count",width:120,sorter:(r,l)=>r.message_count-l.message_count},{title:a("settings.metricsTable.session.columns.action"),key:"action",fixed:"right",width:120,render:(r,l)=>t.jsx(z,{type:"link",onClick:()=>{n(l.session_id)},children:a("settings.metricsTable.session.view")})}];return t.jsx(et,{rowKey:"session_id",size:"small",className:"lotus-metric-table",columns:o,loading:s,dataSource:e,pagination:{pageSize:10,showSizeChanger:!1},scroll:{x:1100}})},{Text:xo}=le,mn={message_count:"Message Count",last_message_id:"Last Message",pending_question:"Pending Question"},bo=e=>mn[e]?mn[e]:e.split("_").map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "),vo=({breakdown:e,loading:s})=>{const{t:n}=Z();if(s)return t.jsx(F,{size:"small",className:"lotus-metric-card",title:n("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),children:t.jsx(tt,{active:!0,paragraph:{rows:5}})});const a=Object.entries(e??{}).map(([o,r])=>({reason:o,label:n(`settings.syncMismatchReasons.${o}`,{defaultValue:bo(o)}),count:r})).sort((o,r)=>r.count-o.count);return t.jsx(F,{size:"small",className:"lotus-metric-card",title:n("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),extra:t.jsx(xo,{type:"secondary",children:n("settings.metricsDashboard.syncMismatchBreakdownSubtitle",{defaultValue:"Grouped by execute sync mismatch reason"})}),children:a.length===0?t.jsx(Ae,{image:Ae.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(St,{children:t.jsxs(As,{data:a,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[t.jsx(Gt,{strokeDasharray:"3 3"}),t.jsx(Jt,{type:"number",allowDecimals:!1}),t.jsx(Xt,{dataKey:"label",type:"category",width:110}),t.jsx(_t,{formatter:o=>[o.toLocaleString(),n("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})],labelFormatter:o=>n("settings.metricsDashboard.syncMismatchReasonLabel",{defaultValue:"Reason: {{label}}",label:o})}),t.jsx(ds,{dataKey:"count",fill:"var(--lotus-chart-danger)",radius:[0,6,6,0],name:n("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})})]})})})})},{Text:To}=le,jo=({data:e,loading:s})=>{const{t:n}=Z();return s?t.jsx(F,{size:"small",className:"lotus-metric-card",title:n("settings.charts.tokenUsageOverTime"),children:t.jsx(tt,{active:!0,paragraph:{rows:5}})}):t.jsx(F,{size:"small",className:"lotus-metric-card",title:n("settings.charts.tokenUsageOverTime"),children:e.length===0?t.jsx(Ae,{image:Ae.PRESENTED_IMAGE_SIMPLE,description:n("settings.charts.noTokenUsage")}):t.jsxs(t.Fragment,{children:[t.jsx(To,{type:"secondary",children:n("settings.charts.tokenUsageDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(St,{children:t.jsxs(Dn,{data:e,children:[t.jsx(Gt,{strokeDasharray:"3 3"}),t.jsx(Jt,{dataKey:"label",minTickGap:24}),t.jsx(Xt,{allowDecimals:!1,tickFormatter:Os}),t.jsx(_t,{formatter:a=>Ln(a)}),t.jsx(Ls,{}),t.jsx(vt,{type:"monotone",dataKey:"totalTokens",name:n("settings.charts.total"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),t.jsx(vt,{type:"monotone",dataKey:"promptTokens",name:n("settings.charts.prompt"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),t.jsx(vt,{type:"monotone",dataKey:"completionTokens",name:n("settings.charts.completion"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{Text:So}=le,At=({title:e,subtitle:s,emptyText:n,color:a="var(--lotus-chart-primary)",data:o,loading:r,countLabel:l})=>{const{t:m}=Z();return r?t.jsx(F,{size:"small",className:"lotus-metric-card",title:e,children:t.jsx(tt,{active:!0,paragraph:{rows:5}})}):t.jsx(F,{size:"small",className:"lotus-metric-card",title:e,children:o.length===0?t.jsx(Ae,{image:Ae.PRESENTED_IMAGE_SIMPLE,description:n}):t.jsxs(t.Fragment,{children:[s?t.jsx(So,{type:"secondary",children:s}):null,t.jsx("div",{style:{width:"100%",minWidth:0,height:280,marginTop:s?12:0},children:t.jsx(St,{children:t.jsxs(As,{data:o,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[t.jsx(Gt,{strokeDasharray:"3 3"}),t.jsx(Jt,{type:"number",allowDecimals:!1}),t.jsx(Xt,{dataKey:"label",type:"category",width:110}),t.jsx(_t,{formatter:c=>[c.toLocaleString(),l??m("settings.metricsDashboard.calls",{defaultValue:"Calls"})],labelFormatter:(c,p)=>{var b,f;const d=(f=(b=p==null?void 0:p[0])==null?void 0:b.payload)==null?void 0:f.meta;return d?`${c} · ${d}`:String(c)}}),t.jsx(ds,{dataKey:"count",fill:a,radius:[0,6,6,0],name:l??m("settings.metricsDashboard.calls",{defaultValue:"Calls"})})]})})})]})})},{useToken:_o}=fe,pn=({summary:e,loading:s})=>{const{t:n}=Z(),{token:a}=_o();if(s)return t.jsx(tt,{active:!0,paragraph:{rows:1}});const o=[{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(r=>r.value>0);return o.length===0?null:t.jsx(Ne,{gutter:[a.marginSM,a.marginSM],children:o.map(r=>t.jsx(ie,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:r.title,value:r.value,precision:0,formatter:Qe,valueStyle:{color:r.color}})})},r.key))})},{Text:pt}=le,{useToken:ko}=fe,hn=e=>"date"in e?e.date:e.label,wo=(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)"},ss=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),n=Math.floor(s/60),a=s%60;if(n>=60){const o=Math.floor(n/60),r=n%60;return`${o}h ${r}m`}return n>0?`${n}m ${a}s`:`${a}s`},fn=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString()},js=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}: ${Rn(a)}`).join(" • ")},Ss=(e,s=320)=>({width:"100%",display:"grid",gridTemplateColumns:`repeat(auto-fit, minmax(${s}px, 1fr))`,gap:e}),Co=()=>{const{t:e}=Z(),{token:s}=ko(),n=Jn(g=>g.themeMode)==="dark",[a,o]=i.useState(void 0),[r,l]=i.useState(void 0),[m,c]=i.useState(void 0),[p,d]=i.useState(30),[b,f]=i.useState("daily"),{summary:v,modelMetrics:T,sessions:u,timeline:M,memorySummary:j,memoryTimeline:x,sessionDetail:E,isLoading:S,isRefreshing:P,isSessionDetailLoading:ee,error:R,refresh:q,loadSessionDetail:G,clearSessionDetail:h}=Hr({filters:{startDate:a,endDate:r,model:m,days:p,granularity:b}}),{summary:y,endpointMetrics:D,requests:_,isLoading:O,isRefreshing:X,error:A,refresh:H}=Br({filters:{startDate:a,endDate:r,days:p,model:m}}),{data:V,isLoading:oe,isRefreshing:ce,error:K,refresh:L}=Gr({filters:{startDate:a,endDate:r,days:p,model:m}}),W=i.useMemo(()=>M.map(g=>({label:hn(g),promptTokens:g.total_token_usage.prompt_tokens,completionTokens:g.total_token_usage.completion_tokens,totalTokens:g.total_token_usage.total_tokens})),[M]),Q=i.useMemo(()=>T.map(g=>({label:g.model,value:g.model})),[T]),se=i.useMemo(()=>{const g=M.map(de=>({label:hn(de),sessions:de.total_sessions,tokens:de.total_token_usage.total_tokens})),ne=g.reduce((de,Ce)=>Math.max(de,Ce.sessions),0);return{points:g,maxSessions:ne}},[M]),we=i.useMemo(()=>{const g=_.map(de=>de.duration_ms).filter(de=>typeof de=="number"&&de>0).sort((de,Ce)=>de-Ce);if(g.length===0)return null;const ne=Math.ceil(g.length*.95)-1;return g[Math.max(0,Math.min(ne,g.length-1))]},[_]),qe=i.useMemo(()=>[{title:e("settings.metricsDashboard.roundColumns.round"),dataIndex:"round_id",key:"round_id",render:g=>`${g.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:g=>ss(g)},{title:e("settings.metricsDashboard.roundColumns.tokens"),key:"tokens",render:(g,ne)=>Kt(ne.token_usage.total_tokens)},{title:e("settings.metricsDashboard.roundColumns.toolCalls"),key:"tool_calls",render:(g,ne)=>ne.tool_calls.length}],[e]),Ie=i.useMemo(()=>{const g=(v==null?void 0:v.total_sessions)??0,ne=(v==null?void 0:v.total_tokens.total_tokens)??0,de=(v==null?void 0:v.total_tool_calls)??0,Ce=(v==null?void 0:v.active_sessions)??0,me=u.reduce((Te,We)=>Te+We.total_rounds,0),Me=(v==null?void 0:v.total_tokens_saved)??0,Qt=(v==null?void 0:v.tool_context_tokens_saved)??0,C=(v==null?void 0:v.non_tool_compression_tokens_saved)??0,w=(v==null?void 0:v.prompt_cached_tool_outputs)??0,J=(v==null?void 0:v.total_compression_events)??0,B=(y==null?void 0:y.total_requests)??0,Y=(y==null?void 0:y.total_tokens.total_tokens)??0,pe=(y==null?void 0:y.failed_requests)??0,re=_.filter(Te=>Te.is_stream).length,Ee=g>0?Ce/g*100:0,Ve=B>0?pe/B*100:0,De=_.length>0?re/_.length*100:0,Be=ne>0?Number((Me/ne*100).toFixed(1)):0,ye=Me>0?Number((Qt/Me*100).toFixed(1)):0;return[{title:e("settings.metricsDashboard.compactStats.avgTokensPerSession"),value:g>0?Math.round(ne/g):0},{title:e("settings.metricsDashboard.compactStats.savedTokens",{defaultValue:"Saved Tokens"}),value:Me},{title:e("settings.metricsDashboard.compactStats.toolContextSavedTokens",{defaultValue:"Tool Context Saved Tokens"}),value:Qt},{title:e("settings.metricsDashboard.compactStats.nonToolCompressionSavedTokens",{defaultValue:"Non-Tool Compression Saved Tokens"}),value:C},{title:e("settings.metricsDashboard.compactStats.savedTokenRatio",{defaultValue:"Saved / Chat Tokens"}),value:Be,suffix:"%"},{title:e("settings.metricsDashboard.compactStats.toolSavedShare",{defaultValue:"Tool Share of Saved Tokens"}),value:ye,suffix:"%"},{title:e("settings.metricsDashboard.compactStats.promptCachedToolOutputs",{defaultValue:"Prompt-Cached Tool Outputs"}),value:w},{title:e("settings.metricsDashboard.compactStats.compressionEvents",{defaultValue:"Compression Events"}),value:J},{title:e("settings.metricsDashboard.compactStats.avgRoundsPerSession"),value:g>0?Number((me/g).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.toolCallsPerSession"),value:g>0?Number((de/g).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.activeSessionRate"),value:Number(Ee.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.avgTokensPerForward"),value:B>0?Math.round(Y/B):0},{title:e("settings.metricsDashboard.compactStats.forwardErrorRate"),value:Number(Ve.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.streamingRatio"),value:Number(De.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.p95ForwardLatency"),value:ss(we)},{title:e("settings.metricsDashboard.compactStats.modelCoverage"),value:T.length},{title:e("settings.metricsDashboard.compactStats.endpointCoverage"),value:D.length}]},[D.length,_,y,T.length,we,u,v,e]),kt=i.useMemo(()=>{const g=(y==null?void 0:y.total_requests)??0,ne=(y==null?void 0:y.failed_requests)??0,de=_.filter(Me=>Me.is_stream).length,Ce=_.length>0?de/_.length*100:0,me=g>0?ne/g*100:0;return[{title:e("settings.metricsDashboard.forward.performance.p95Latency",{defaultValue:"P95 Latency"}),value:ss(we)},{title:e("settings.metricsDashboard.forward.performance.errorRate",{defaultValue:"Error Rate"}),value:Number(me.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.streamingRatio",{defaultValue:"Streaming Ratio"}),value:Number(Ce.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.endpointCoverage",{defaultValue:"Endpoint Coverage"}),value:D.length}]},[D.length,_,y,we,e]),ft=i.useMemo(()=>V?[{label:e("settings.metricsDashboard.skillsAndMcp.mix.coreTools",{defaultValue:"Core Tools"}),count:V.core_tool_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.skillLoads",{defaultValue:"Skill Loads"}),count:V.skill_load_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.mcpCalls",{defaultValue:"MCP Calls"}),count:V.mcp_calls}].filter(g=>g.count>0):[],[e,V]),wt=i.useMemo(()=>((V==null?void 0:V.top_skills)??[]).map(g=>({label:g.skill_id,count:g.count})),[V]),Ct=i.useMemo(()=>((V==null?void 0:V.top_mcp_servers)??[]).map(g=>({label:g.server_id,count:g.count,meta:e("settings.metricsDashboard.skillsAndMcp.meta.uniqueTools",{defaultValue:"{{count}} tools",count:g.unique_tools})})),[e,V]),it=i.useMemo(()=>((V==null?void 0:V.top_mcp_tools)??[]).map(g=>({label:g.tool_name,count:g.count,meta:g.server_id})),[V]),lt=i.useMemo(()=>((V==null?void 0:V.top_core_tools)??[]).map(g=>({label:g.name,count:g.count})),[V]),Le=E==null?void 0:E.session,Mt=P||X||ce;return t.jsxs(I,{direction:"vertical",size:s.marginMD,style:{width:"100%"},children:[R?t.jsx(ke,{type:"error",showIcon:!0,message:R}):null,A?t.jsx(ke,{type:"error",showIcon:!0,message:A}):null,K?t.jsx(ke,{type:"error",showIcon:!0,message:K}):null,t.jsx(F,{size:"small",title:e("settings.metricsDashboard.filtersTitle"),extra:t.jsx(z,{icon:t.jsx(jt,{}),loading:Mt,onClick:()=>{q(),H(),L()},children:e("settings.metricsDashboard.refresh")}),children:t.jsxs(I,{wrap:!0,children:[t.jsx(Xs,{placeholder:e("settings.metricsDashboard.startDate"),onChange:g=>{o(g?g.format("YYYY-MM-DD"):void 0)}}),t.jsx(Xs,{placeholder:e("settings.metricsDashboard.endDate"),onChange:g=>{l(g?g.format("YYYY-MM-DD"):void 0)}}),t.jsx(ae,{allowClear:!0,style:{minWidth:180},placeholder:e("settings.metricsDashboard.model"),value:m,options:Q,onChange:g=>{c(g)}}),t.jsx(ae,{style:{width:120},value:p,options:[7,14,30,90].map(g=>({label:e("settings.metricsDashboard.daysOption",{value:g}),value:g})),onChange:g=>{d(g)}}),t.jsx(ae,{style:{width:140},value:b,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:g=>{f(g)}})]})}),t.jsx(F,{size:"small",title:e("settings.metricsDashboard.dashboardTitle"),children:t.jsx(ls,{size:"small",destroyInactiveTabPane:!0,items:[{key:"overview",label:e("settings.metricsDashboard.tabs.overview"),children:t.jsxs(I,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(F,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.overviewSections.scaleTitle",{defaultValue:"Scale & Activity"}),extra:t.jsx(pt,{type:"secondary",children:e("settings.metricsDashboard.overviewSections.scaleSubtitle",{defaultValue:"Current usage volume across chat, forward, skills, and memory."})}),children:t.jsxs(I,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(un,{summary:v,sessions:u,loading:S}),t.jsx(cn,{summary:y,loading:O}),t.jsx(pn,{summary:V,loading:oe}),t.jsx(dn,{summary:j,loading:S})]})}),t.jsxs(F,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.overviewSections.efficiencyTitle",{defaultValue:"Compression & Efficiency Advantage"}),extra:t.jsx(pt,{type:"secondary",children:e("settings.metricsDashboard.overviewSections.efficiencySubtitle",{defaultValue:"Real savings from context compression, especially around tool-heavy workflows."})}),children:[t.jsx(Ne,{gutter:[s.marginSM,s.marginSM],children:Ie.map(g=>t.jsx(ie,{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(be,{title:g.title,value:g.value,suffix:g.suffix,formatter:typeof g.value=="number"?Qe:void 0,valueStyle:{fontSize:s.fontSizeHeading4}})})},g.title))}),t.jsx(pt,{type:"secondary",style:{display:"block",marginTop:s.marginXS},children:e("settings.metricsDashboard.efficiencyHint",{defaultValue:"这些指标优先使用真实运行统计:总节约 Tokens、工具上下文压缩节约、非工具压缩节约、压缩事件数,以及会话 / Forward 的平均负载与质量指标。"})})]})]})},{key:"chat",label:e("settings.metricsDashboard.tabs.chat",{defaultValue:"Chat"}),children:t.jsxs(I,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(un,{summary:v,sessions:u,loading:S}),t.jsxs("div",{style:Ss(s.marginSM,360),children:[t.jsx(jo,{data:W,loading:S}),t.jsx(go,{data:T,loading:S})]}),t.jsxs("div",{style:Ss(s.marginSM,360),children:[t.jsx(vo,{breakdown:v==null?void 0:v.sync_mismatch_breakdown,loading:S}),t.jsx(F,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.activityHeatmapTitle"),children:se.points.length===0?t.jsx(pt,{type:"secondary",children:e("settings.metricsDashboard.noActivity")}):t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(72px, 1fr))",gap:s.marginXS},children:se.points.map(g=>t.jsxs("div",{style:{borderRadius:s.borderRadiusSM,padding:s.paddingXS,background:wo(g.sessions,se.maxSessions),minHeight:64,color:g.sessions>0?"var(--lotus-metric-text-strong)":s.colorTextSecondary},children:[t.jsx("div",{style:{fontSize:12,lineHeight:1.2},children:g.label}),t.jsx("div",{style:{fontWeight:600,marginTop:4},children:e("settings.metricsDashboard.sessionsCount",{count:g.sessions})}),t.jsx("div",{style:{fontSize:12},children:e("settings.metricsDashboard.tokensAmount",{value:Os(g.tokens)})})]},g.label))})})]})]})},{key:"skills-and-mcp",label:e("settings.metricsDashboard.tabs.skillsAndMcp",{defaultValue:"Skills & MCP"}),children:t.jsxs(I,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(pn,{summary:V,loading:oe}),t.jsxs("div",{style:Ss(s.marginSM,360),children:[t.jsx(At,{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:ft,loading:oe,color:"var(--lotus-chart-primary)"}),t.jsx(At,{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:wt,loading:oe,color:"var(--lotus-chart-purple)"}),t.jsx(At,{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:Ct,loading:oe,color:"var(--lotus-chart-cyan)"}),t.jsx(At,{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:it,loading:oe,color:"var(--lotus-chart-accent)"}),t.jsx(At,{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:lt,loading:oe,color:"var(--lotus-chart-secondary)"})]})]})},{key:"forward",label:e("settings.metricsDashboard.tabs.forward",{defaultValue:"Forward"}),children:t.jsxs(I,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(cn,{summary:y,loading:O}),t.jsx(F,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.forward.performanceTitle",{defaultValue:"Forward Performance"}),children:t.jsx(Ne,{gutter:[s.marginSM,s.marginSM],children:kt.map(g=>t.jsx(ie,{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(be,{title:g.title,value:g.value,suffix:g.suffix,valueStyle:{fontSize:s.fontSizeHeading4}})})},g.title))})}),t.jsx(Xr,{data:D,loading:O})]})},{key:"memory",label:e("settings.metricsDashboard.tabs.memory",{defaultValue:"Memory"}),children:t.jsxs(I,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(dn,{summary:j,loading:S}),t.jsx(oo,{data:x,loading:S}),t.jsx(F,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.memory.breakdownTitle",{defaultValue:"Memory Breakdown"}),children:t.jsxs(_e,{size:"small",bordered:!0,column:1,children:[t.jsx(_e.Item,{label:e("settings.metricsDashboard.memory.byType",{defaultValue:"By Type"}),children:js(j==null?void 0:j.by_type)}),t.jsx(_e.Item,{label:e("settings.metricsDashboard.memory.byStatus",{defaultValue:"By Status"}),children:js(j==null?void 0:j.by_status)}),t.jsx(_e.Item,{label:e("settings.metricsDashboard.memory.byScope",{defaultValue:"By Scope"}),children:js(j==null?void 0:j.by_scope)}),t.jsx(_e.Item,{label:e("settings.metricsDashboard.memory.lastDream",{defaultValue:"Last Dream"}),children:fn(j==null?void 0:j.last_dream_at)}),t.jsx(_e.Item,{label:e("settings.metricsDashboard.memory.lastReindex",{defaultValue:"Last Reindex"}),children:fn(j==null?void 0:j.last_reindex_at)})]})})]})},{key:"records",label:e("settings.metricsDashboard.tabs.records"),children:t.jsx(ls,{size:"small",destroyInactiveTabPane:!0,items:[{key:"sessions",label:e("settings.metricsDashboard.sessionsTabLabel",{count:u.length}),children:t.jsx(F,{size:"small",extra:t.jsx(pt,{type:"secondary",children:e("settings.metricsDashboard.sessionsHint")}),children:t.jsx(yo,{sessions:u,loading:S,onSelectSession:g=>{G(g)}})})},{key:"forward-requests",label:e("settings.metricsDashboard.forwardTabLabel",{count:_.length}),children:t.jsx(F,{size:"small",children:t.jsx(so,{requests:_,loading:O})})}]})}]})}),t.jsx(ot,{title:e("settings.metricsDashboard.sessionMetricsTitle"),open:!!E,onCancel:h,onOk:h,width:960,destroyOnClose:!0,children:ee?t.jsx(pt,{children:e("settings.metricsDashboard.loadingSessionDetails")}):Le?t.jsxs(I,{direction:"vertical",style:{width:"100%"},size:s.marginMD,children:[t.jsxs(_e,{size:"small",bordered:!0,column:2,children:[t.jsx(_e.Item,{label:e("settings.metricsDashboard.sessionDetail.sessionId"),span:2,children:Le.session_id}),t.jsx(_e.Item,{label:e("settings.metricsDashboard.sessionDetail.model"),children:Le.model}),t.jsx(_e.Item,{label:e("settings.metricsDashboard.sessionDetail.status"),children:Le.status}),t.jsx(_e.Item,{label:e("settings.metricsDashboard.sessionDetail.duration"),children:ss(Le.duration_ms)}),t.jsx(_e.Item,{label:e("settings.metricsDashboard.sessionDetail.messages"),children:Le.message_count}),t.jsx(_e.Item,{label:e("settings.metricsDashboard.sessionDetail.totalTokens"),children:Kt(Le.total_token_usage.total_tokens)}),t.jsx(_e.Item,{label:e("settings.metricsDashboard.sessionDetail.toolCalls"),children:Le.tool_call_count})]}),t.jsx(et,{rowKey:"round_id",size:"small",columns:qe,dataSource:E.rounds,pagination:{pageSize:6,showSizeChanger:!1}})]}):t.jsx(pt,{type:"secondary",children:e("settings.metricsDashboard.noDetail")})})]})},{Text:ns}=le,{useToken:Mo}=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"},Do=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},Po=()=>{const{t:e}=Z(),{token:s}=Mo(),[n,a]=Tt.useMessage(),[o,r]=i.useState(!1),[l,m]=i.useState(!0),[c,p]=i.useState("placeholder"),d=i.useMemo(()=>[{label:e("settings.hooksTab.mode.placeholder"),value:"placeholder"},{label:e("settings.hooksTab.mode.error"),value:"error"},{label:e("settings.hooksTab.mode.ocr"),value:"ocr"},{label:e("settings.hooksTab.mode.vision"),value:"vision"}],[e]),b=i.useCallback(async()=>{r(!0);try{const u=await Se.getBambooConfig();m(Do(u)),p(Eo(u))}catch(u){n.error(u instanceof Error?u.message:e("settings.hooksTab.loadFailed"))}finally{r(!1)}},[n,e]),f=i.useCallback(async(u,M)=>{await Se.setBambooConfig({hooks:{image_fallback:{enabled:u,mode:M}}})},[]),v=i.useCallback(async u=>{r(!0);try{await f(u,c),n.success(e(u?"settings.hooksTab.enabled":"settings.hooksTab.disabled")),await b()}catch(M){n.error(M instanceof Error?M.message:e("settings.hooksTab.updateFailed"))}finally{r(!1)}},[b,c,n,f,e]),T=i.useCallback(async u=>{var M;r(!0);try{await f(l,u),n.success(e("settings.hooksTab.modeUpdated",{mode:((M=d.find(j=>j.value===u))==null?void 0:M.label)??u})),await b()}catch(j){n.error(j instanceof Error?j.message:e("settings.hooksTab.modeUpdateFailed"))}finally{r(!1)}},[l,b,d,n,f,e]);return i.useEffect(()=>{b()},[b]),t.jsxs($,{vertical:!0,gap:s.marginLG,children:[a,t.jsx(F,{size:"small",loading:o,children:t.jsxs($,{vertical:!0,gap:s.marginXS,children:[t.jsx(ns,{strong:!0,children:e("settings.hooksTab.title")}),t.jsxs($,{align:"center",justify:"space-between",children:[t.jsx(ns,{children:e("settings.hooksTab.enableImagePreflight")}),t.jsx(ge,{checked:l,onChange:v})]}),t.jsxs($,{align:"center",justify:"space-between",children:[t.jsx(ns,{children:e("settings.hooksTab.modeLabel")}),t.jsx(ae,{style:{width:180},value:c,options:d,onChange:T,disabled:!l})]}),t.jsx(ns,{type:"secondary",style:{fontSize:s.fontSizeSM},children:e("settings.hooksTab.description")})]})})]})},{Text:je}=le,Xe=Is.getInstance();function Io(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 Fo=[{label:te.t("settings.schedulesTab.weekdays.mon"),value:"mon"},{label:te.t("settings.schedulesTab.weekdays.tue"),value:"tue"},{label:te.t("settings.schedulesTab.weekdays.wed"),value:"wed"},{label:te.t("settings.schedulesTab.weekdays.thu"),value:"thu"},{label:te.t("settings.schedulesTab.weekdays.fri"),value:"fri"},{label:te.t("settings.schedulesTab.weekdays.sat"),value:"sat"},{label:te.t("settings.schedulesTab.weekdays.sun"),value:"sun"}];function ve(e){return String(e??"").trim()||void 0}function Ro(e){return(e==null?void 0:e.type)==="interval"?e.every_seconds:null}function zn(e){return{type:"interval",every_seconds:e}}function Ao(e){switch(e.type){case"interval":return te.t("settings.schedulesTab.triggerLabels.interval",{type:te.t("settings.schedulesTab.triggerTypes.interval"),seconds:e.every_seconds});case"daily":return te.t("settings.schedulesTab.triggerLabels.daily",{type:te.t("settings.schedulesTab.triggerTypes.daily"),time:`${String(e.hour).padStart(2,"0")}:${String(e.minute).padStart(2,"0")}`});case"weekly":return te.t("settings.schedulesTab.triggerLabels.weekly",{type:te.t("settings.schedulesTab.triggerTypes.weekly"),weekdays:e.weekdays.join(", ")});case"monthly":return te.t("settings.schedulesTab.triggerLabels.monthly",{type:te.t("settings.schedulesTab.triggerTypes.monthly"),days:e.days.join(", ")});case"cron":return te.t("settings.schedulesTab.triggerLabels.cron",{type:te.t("settings.schedulesTab.triggerTypes.cron"),expr:e.expr})}}function Lo(e){switch(e==null?void 0:e.type){case"skip":return te.t("settings.schedulesTab.misfirePolicyOptions.skip");case"catch_up_all":return te.t("settings.schedulesTab.misfirePolicyOptions.catchUpAll");case"catch_up_window":return te.t("settings.schedulesTab.misfirePolicyOptions.catchUpWindow");case"run_once":default:return te.t("settings.schedulesTab.misfirePolicyOptions.runOnce")}}function zo(e){switch(e){case"allow":return te.t("settings.schedulesTab.overlapPolicyOptions.allow");case"skip":return te.t("settings.schedulesTab.overlapPolicyOptions.skip");case"queue_one":default:return te.t("settings.schedulesTab.overlapPolicyOptions.queueOne")}}function Oo(e){var s;return(s=e.state)!=null&&s.next_fire_at?String(e.state.next_fire_at):"-"}function No(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 Vo(e){var s,n,a,o;return((s=e.state)==null?void 0:s.running_run_count)>0?{color:"processing",label:te.t("settings.schedulesTab.statusLabels.running"),detail:te.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:te.t("settings.schedulesTab.statusLabels.queued"),detail:te.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:te.t("settings.schedulesTab.statusLabels.failing"),detail:te.t("settings.schedulesTab.statusDetails.consecutiveFailures",{count:e.state.consecutive_failures})}:e.enabled?(o=e.state)!=null&&o.last_success_at?{color:"success",label:te.t("settings.schedulesTab.statusLabels.healthy"),detail:te.t("settings.schedulesTab.statusDetails.lastRunSucceeded")}:{color:"default",label:te.t("settings.schedulesTab.statusLabels.idle")}:{color:"default",label:te.t("settings.schedulesTab.statusLabels.disabled")}}function $o(e){const s=ve(e);if(!s)return{days:[],invalid:!1};const a=s.split(/[\s,]+/).filter(Boolean).map(l=>Number(l)),o=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:o}}function yn(e){switch(e.trigger_type){case"interval":{const s=Number(e.interval_seconds||0);return s<=0?{errorKey:"settings.schedulesTab.validation.intervalRequired"}:{trigger:zn(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}=$o(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,o=e.monthly_minute;return a==null||o==null?{errorKey:"settings.schedulesTab.validation.triggerRequired"}:{trigger:{type:"monthly",days:s,hour:a,minute:o,second:0}}}case"cron":{const s=ve(e.cron_expr);return s?{trigger:{type:"cron",expr:s}}:{errorKey:"settings.schedulesTab.validation.cronRequired"}}default:return{errorKey:"settings.schedulesTab.validation.triggerRequired"}}}function xn(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"}}}function qo(e){var n,a,o,r,l,m,c,p;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:((o=e.run_config)==null?void 0:o.task_message)||"",model:((r=e.run_config)==null?void 0:r.model)||"",workspace_path:((l=e.run_config)==null?void 0:l.workspace_path)||"",enhance_prompt:((m=e.run_config)==null?void 0:m.enhance_prompt)||"",auto_execute:!!((c=e.run_config)!=null&&c.auto_execute)};switch(((p=e.misfire_policy)==null?void 0:p.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 Bo(){const{t:e}=Z(),[s,n]=Tt.useMessage(),[a,o]=i.useState(!1),[r,l]=i.useState([]),[m,c]=i.useState({open:!1,scheduleId:null,sessions:[],loading:!1}),[p,d]=i.useState({open:!1,scheduleId:null,runs:[],loading:!1}),[b,f]=i.useState({open:!1,schedule:null,saving:!1}),v=Cs(h=>h.close),[T]=k.useForm(),[u]=k.useForm(),M=k.useWatch("trigger_type",T),j=k.useWatch("misfire_policy",T),x=k.useWatch("trigger_type",u),E=k.useWatch("misfire_policy",u),S=i.useCallback(async()=>{o(!0);try{const h=await Xe.listSchedules();l(h.schedules||[])}catch(h){console.error("[Schedules] Failed to load schedules:",h),s.error(e("settings.schedulesTab.loadFailed"))}finally{o(!1)}},[s,e]);i.useEffect(()=>{S()},[S]);const P=[{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")}],ee=[{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")}],R=[{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")}],q=(h,y)=>t.jsxs(t.Fragment,{children:[t.jsxs($,{gap:12,wrap:"wrap",children:[t.jsx(k.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(U,{})}),t.jsx(k.Item,{label:e("settings.schedulesTab.form.triggerType"),name:"trigger_type",rules:[{required:!0,message:e("settings.schedulesTab.validation.triggerRequired")}],style:{width:220},children:t.jsx(ae,{options:P})}),t.jsx(k.Item,{label:e("settings.schedulesTab.form.enabled"),name:"enabled",valuePropName:"checked",style:{width:120},children:t.jsx(ge,{})})]}),h==="interval"?t.jsx(k.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(he,{min:1,style:{width:"100%"}})}):null,h==="daily"?t.jsxs($,{gap:12,wrap:"wrap",children:[t.jsx(k.Item,{label:e("settings.schedulesTab.form.dailyHour"),name:"daily_hour",style:{width:180},children:t.jsx(he,{min:0,max:23,style:{width:"100%"}})}),t.jsx(k.Item,{label:e("settings.schedulesTab.form.dailyMinute"),name:"daily_minute",style:{width:180},children:t.jsx(he,{min:0,max:59,style:{width:"100%"}})})]}):null,h==="weekly"?t.jsxs(t.Fragment,{children:[t.jsx(k.Item,{label:e("settings.schedulesTab.form.weeklyWeekdays"),name:"weekly_weekdays",style:{minWidth:320},children:t.jsx(ae,{mode:"multiple",options:Fo})}),t.jsxs($,{gap:12,wrap:"wrap",children:[t.jsx(k.Item,{label:e("settings.schedulesTab.form.dailyHour"),name:"weekly_hour",style:{width:180},children:t.jsx(he,{min:0,max:23,style:{width:"100%"}})}),t.jsx(k.Item,{label:e("settings.schedulesTab.form.dailyMinute"),name:"weekly_minute",style:{width:180},children:t.jsx(he,{min:0,max:59,style:{width:"100%"}})})]})]}):null,h==="monthly"?t.jsxs(t.Fragment,{children:[t.jsx(k.Item,{label:e("settings.schedulesTab.form.monthlyDays"),name:"monthly_days",style:{minWidth:320},children:t.jsx(U,{placeholder:e("settings.schedulesTab.form.monthlyDaysPlaceholder")})}),t.jsxs($,{gap:12,wrap:"wrap",children:[t.jsx(k.Item,{label:e("settings.schedulesTab.form.dailyHour"),name:"monthly_hour",style:{width:180},children:t.jsx(he,{min:0,max:23,style:{width:"100%"}})}),t.jsx(k.Item,{label:e("settings.schedulesTab.form.dailyMinute"),name:"monthly_minute",style:{width:180},children:t.jsx(he,{min:0,max:59,style:{width:"100%"}})})]})]}):null,h==="cron"?t.jsx(k.Item,{label:e("settings.schedulesTab.form.cronExpr"),name:"cron_expr",children:t.jsx(U,{placeholder:e("settings.schedulesTab.form.cronExprPlaceholder")})}):null,t.jsxs($,{gap:12,wrap:"wrap",children:[t.jsx(k.Item,{label:e("settings.schedulesTab.form.timezone"),name:"timezone",style:{flex:"1 1 240px"},children:t.jsx(U,{placeholder:e("settings.schedulesTab.form.timezonePlaceholder")})}),t.jsx(k.Item,{label:e("settings.schedulesTab.form.startAt"),name:"start_at",style:{flex:"1 1 240px"},children:t.jsx(U,{placeholder:e("settings.schedulesTab.form.datetimePlaceholder")})}),t.jsx(k.Item,{label:e("settings.schedulesTab.form.endAt"),name:"end_at",style:{flex:"1 1 240px"},children:t.jsx(U,{placeholder:e("settings.schedulesTab.form.datetimePlaceholder")})})]}),t.jsxs($,{gap:12,wrap:"wrap",children:[t.jsx(k.Item,{label:e("settings.schedulesTab.form.misfirePolicy"),name:"misfire_policy",style:{flex:"1 1 240px"},children:t.jsx(ae,{options:ee})}),t.jsx(k.Item,{label:e("settings.schedulesTab.form.overlapPolicy"),name:"overlap_policy",style:{flex:"1 1 240px"},children:t.jsx(ae,{options:R})})]}),y==="catch_up_window"?t.jsxs($,{gap:12,wrap:"wrap",children:[t.jsx(k.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxRuns"),name:"catch_up_window_max_runs",style:{width:220},children:t.jsx(he,{min:1,style:{width:"100%"}})}),t.jsx(k.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxLatenessSeconds"),name:"catch_up_window_max_lateness_seconds",style:{width:260},children:t.jsx(he,{min:1,style:{width:"100%"}})})]}):null,t.jsx(k.Item,{label:e("settings.schedulesTab.form.taskMessage"),name:"task_message",children:t.jsx(U.TextArea,{rows:3,placeholder:e("settings.schedulesTab.form.taskMessagePlaceholder")})}),t.jsx(k.Item,{label:e("settings.schedulesTab.form.systemPrompt"),name:"system_prompt",children:t.jsx(U.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})}),t.jsxs($,{gap:12,wrap:"wrap",children:[t.jsx(k.Item,{label:e("settings.schedulesTab.form.model"),name:"model",style:{flex:"1 1 240px"},children:t.jsx(U,{placeholder:e("settings.schedulesTab.form.modelPlaceholder")})}),t.jsx(k.Item,{label:e("settings.schedulesTab.form.workspacePath"),name:"workspace_path",style:{flex:"1 1 320px"},children:t.jsx(U,{placeholder:e("settings.schedulesTab.optional")})}),t.jsx(k.Item,{label:e("settings.schedulesTab.form.autoExecute"),name:"auto_execute",valuePropName:"checked",style:{width:160},children:t.jsx(ge,{})})]}),t.jsx(k.Item,{label:e("settings.schedulesTab.form.enhancePrompt"),name:"enhance_prompt",children:t.jsx(U.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})})]}),G=i.useMemo(()=>[{title:e("settings.schedulesTab.columns.name"),key:"name",render:(h,y)=>t.jsxs($,{vertical:!0,gap:6,children:[t.jsx(je,{strong:!0,children:y.name}),t.jsxs($,{gap:6,wrap:"wrap",children:[t.jsx(ue,{children:Ao(y.trigger)}),y.timezone?t.jsx(ue,{color:"blue",children:y.timezone}):null,t.jsx(ue,{children:Lo(y.misfire_policy)}),t.jsx(ue,{children:zo(y.overlap_policy)})]})]})},{title:e("settings.schedulesTab.columns.status"),key:"status",render:(h,y)=>{const D=Vo(y);return t.jsxs($,{vertical:!0,gap:4,children:[t.jsx(ue,{color:D.color,children:D.label}),D.detail?t.jsx(je,{type:"secondary",children:D.detail}):null]})}},{title:e("settings.schedulesTab.columns.activity"),key:"activity",render:(h,y)=>{var D,_,O,X;return t.jsxs($,{vertical:!0,gap:2,children:[t.jsx(je,{type:"secondary",children:e("settings.schedulesTab.activityLabels.queued",{count:((D=y.state)==null?void 0:D.queued_run_count)??0})}),t.jsx(je,{type:"secondary",children:e("settings.schedulesTab.activityLabels.running",{count:((_=y.state)==null?void 0:_.running_run_count)??0})}),t.jsx(je,{type:"secondary",children:e("settings.schedulesTab.activityLabels.ok",{count:((O=y.state)==null?void 0:O.total_success_count)??0})}),t.jsx(je,{type:"secondary",children:e("settings.schedulesTab.activityLabels.fail",{count:((X=y.state)==null?void 0:X.total_failure_count)??0})})]})}},{title:e("settings.schedulesTab.columns.nextRun"),key:"next_run_at",render:(h,y)=>t.jsx(je,{type:"secondary",children:Oo(y)})},{title:e("settings.schedulesTab.columns.lastRun"),key:"last_run_at",render:(h,y)=>t.jsx(je,{type:"secondary",children:No(y)})},{title:e("settings.schedulesTab.columns.autoExecute"),key:"auto_execute",render:(h,y)=>{var D,_;return t.jsx(je,{type:(D=y.run_config)!=null&&D.auto_execute?void 0:"secondary",children:(_=y.run_config)!=null&&_.auto_execute?e("settings.schedulesTab.yes"):e("settings.schedulesTab.no")})}},{title:e("settings.schedulesTab.columns.model"),key:"model",render:(h,y)=>{var D;return t.jsx(je,{type:"secondary",children:(D=y.run_config)!=null&&D.model?String(y.run_config.model):"-"})}},{title:e("settings.schedulesTab.columns.enabled"),key:"enabled",render:(h,y)=>t.jsx(ge,{checked:y.enabled,onChange:async D=>{try{await Xe.patchSchedule(y.id,{enabled:D}),await S()}catch(_){console.error("[Schedules] Failed to toggle:",_),s.error(e("settings.schedulesTab.updateFailed"))}}})},{title:e("settings.schedulesTab.columns.actions"),key:"actions",render:(h,y)=>{const D=t.jsx(he,{min:1,value:Ro(y.trigger)??void 0,disabled:y.trigger.type!=="interval",onChange:async _=>{const O=typeof _=="number"?_:null;if(!(!O||O<=0))try{await Xe.patchSchedule(y.id,{trigger:zn(O)}),await S()}catch(X){console.error("[Schedules] Failed to patch interval:",X),s.error(e("settings.schedulesTab.updateFailed"))}}});return t.jsxs($,{vertical:!0,gap:8,children:[t.jsxs($,{gap:8,wrap:"wrap",children:[t.jsx(z,{size:"small",onClick:()=>{f({open:!0,schedule:y,saving:!1}),u.setFieldsValue(qo(y))},children:e("settings.schedulesTab.actions.edit")}),t.jsx(z,{size:"small",onClick:async()=>{try{await Xe.runScheduleNow(y.id),s.success(e("settings.schedulesTab.enqueuedRun")),await S()}catch(_){console.error("[Schedules] Failed to run now:",_),s.error(e("settings.schedulesTab.runNowFailed"))}},children:e("settings.schedulesTab.actions.runNow")}),t.jsx(z,{size:"small",onClick:async()=>{c(_=>({..._,open:!0,scheduleId:y.id,loading:!0,sessions:[]}));try{const _=await Xe.listScheduleSessions(y.id);c(O=>({...O,open:!0,scheduleId:y.id,loading:!1,sessions:(_.sessions||[]).map(X=>({id:X.id,title:X.title,updated_at:X.updated_at}))}))}catch(_){console.error("[Schedules] Failed to list sessions:",_),s.error(e("settings.schedulesTab.loadSessionsFailed")),c(O=>({...O,loading:!1}))}},children:e("settings.schedulesTab.actions.sessions")}),t.jsx(z,{size:"small",onClick:async()=>{d(_=>({..._,open:!0,scheduleId:y.id,loading:!0,runs:[]}));try{const _=await Xe.listScheduleRuns(y.id);d(O=>({...O,open:!0,scheduleId:y.id,loading:!1,runs:_.runs||[]}))}catch(_){console.error("[Schedules] Failed to list runs:",_),s.error(e("settings.schedulesTab.loadRunsFailed")),d(O=>({...O,loading:!1}))}},children:e("settings.schedulesTab.actions.runs")}),t.jsx(z,{danger:!0,size:"small",onClick:async()=>{try{await Xe.deleteSchedule(y.id),s.success(e("settings.schedulesTab.deleted")),await S()}catch(_){console.error("[Schedules] Failed to delete:",_),s.error(e("settings.schedulesTab.deleteFailed"))}},children:e("settings.schedulesTab.actions.delete")})]}),t.jsxs($,{gap:8,align:"center",wrap:"wrap",children:[t.jsx(je,{type:"secondary",children:e("settings.schedulesTab.columns.intervalSeconds")}),y.trigger.type==="interval"?D:t.jsx(xe,{title:e("settings.schedulesTab.nonIntervalReadOnly"),children:t.jsx("span",{children:D})})]})]})}}],[u,s,S,e]);return t.jsxs($,{vertical:!0,gap:16,children:[n,t.jsx(F,{title:e("settings.schedulesTab.createTitle"),className:"lotus-settings-card",children:t.jsxs(k,{form:T,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 h=>{try{const y=!!h.auto_execute,D=ve(h.task_message),_=ve(h.model);if(y&&!D){s.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:O,errorKey:X}=yn(h);if(!O){s.error(e(X||"settings.schedulesTab.validation.triggerRequired"));return}await Xe.createSchedule({name:String(h.name||"").trim(),trigger:O,timezone:ve(h.timezone),start_at:ve(h.start_at),end_at:ve(h.end_at),misfire_policy:xn(h),overlap_policy:h.overlap_policy,enabled:!!h.enabled,run_config:{system_prompt:ve(h.system_prompt),task_message:D,model:_,workspace_path:ve(h.workspace_path),enhance_prompt:ve(h.enhance_prompt),auto_execute:y}}),s.success(e("settings.schedulesTab.created")),T.resetFields(),await S()}catch(y){console.error("[Schedules] Failed to create schedule:",y),s.error(e("settings.schedulesTab.createFailed"))}},children:[q(M,j),t.jsx(z,{type:"primary",htmlType:"submit",children:e("settings.schedulesTab.actions.create")})]})}),t.jsx(F,{title:e("settings.schedulesTab.listTitle"),className:"lotus-settings-card",extra:t.jsx(z,{onClick:()=>void S(),loading:a,children:e("settings.schedulesTab.actions.refresh")}),children:t.jsx(et,{rowKey:"id",columns:G,dataSource:r,loading:a,pagination:{pageSize:10},scroll:{x:1500}})}),t.jsx(ot,{title:e("settings.schedulesTab.scheduleSessionsTitle"),open:m.open,onCancel:()=>c(h=>({...h,open:!1,scheduleId:null})),footer:null,children:m.loading?t.jsx(je,{type:"secondary",children:e("settings.schedulesTab.loading")}):t.jsx($,{vertical:!0,gap:8,children:m.sessions.length===0?t.jsx(je,{type:"secondary",children:e("settings.schedulesTab.noSessionsYet")}):m.sessions.map(h=>t.jsxs($,{justify:"space-between",align:"center",children:[t.jsxs($,{vertical:!0,style:{minWidth:0},children:[t.jsx(je,{strong:!0,ellipsis:!0,children:h.title}),t.jsxs(je,{type:"secondary",ellipsis:!0,children:[h.id," • ",h.updated_at]})]}),t.jsx(z,{size:"small",onClick:()=>{Xn(h.id,{forceRefreshIndex:!0,forceLoadHistory:!0,subscribeIfRunning:!0,forceSubscribe:!0}),v()},children:e("settings.schedulesTab.actions.open")})]},h.id))})}),t.jsx(ot,{title:e("settings.schedulesTab.scheduleRunsTitle"),open:p.open,onCancel:()=>d(h=>({...h,open:!1,scheduleId:null})),footer:null,width:960,children:p.loading?t.jsx(je,{type:"secondary",children:e("settings.schedulesTab.loading")}):p.runs.length===0?t.jsx(je,{type:"secondary",children:e("settings.schedulesTab.noRunsYet")}):t.jsx(et,{rowKey:"run_id",pagination:{pageSize:8},dataSource:p.runs,columns:[{title:e("settings.schedulesTab.runHistory.columns.status"),key:"status",render:(h,y)=>t.jsx(ue,{color:Io(y.status),children:y.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:(h,y)=>y.started_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.completedAt"),key:"completed_at",render:(h,y)=>y.completed_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.session"),key:"session_id",render:(h,y)=>y.session_id||"-"},{title:e("settings.schedulesTab.runHistory.columns.duration"),key:"execution_duration_ms",render:(h,y)=>y.execution_duration_ms!=null?`${y.execution_duration_ms}ms`:"-"},{title:e("settings.schedulesTab.runHistory.columns.outcome"),key:"outcome_reason",render:(h,y)=>y.outcome_reason||(y.was_catch_up?"catch-up":"-")}]})}),t.jsx(ot,{title:e("settings.schedulesTab.editTitle"),open:b.open,onCancel:()=>f({open:!1,schedule:null,saving:!1}),okText:e("settings.schedulesTab.actions.save"),confirmLoading:b.saving,onOk:()=>u.submit(),forceRender:!0,children:t.jsx(k,{form:u,layout:"vertical",onFinish:async h=>{const y=b.schedule;if(!y)return;const D=!!h.auto_execute,_=ve(h.task_message),O=ve(h.model);if(D&&!_){s.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:X,errorKey:A}=yn(h);if(!X){s.error(e(A||"settings.schedulesTab.validation.triggerRequired"));return}f(H=>({...H,saving:!0}));try{await Xe.patchSchedule(y.id,{name:String(h.name||"").trim()||void 0,enabled:!!h.enabled,trigger:X,timezone:ve(h.timezone),start_at:ve(h.start_at),end_at:ve(h.end_at),misfire_policy:xn(h),overlap_policy:h.overlap_policy,run_config:{system_prompt:ve(h.system_prompt),task_message:_,model:O,workspace_path:ve(h.workspace_path),enhance_prompt:ve(h.enhance_prompt),auto_execute:D}}),s.success(e("settings.schedulesTab.updated")),f({open:!1,schedule:null,saving:!1}),await S()}catch(H){console.error("[Schedules] Failed to patch schedule:",H),s.error(e("settings.schedulesTab.updateFailed")),f(V=>({...V,saving:!1}))}},children:q(x,E)})})]})}const{Text:Lt}=le,zt=Is.getInstance();function Uo(){const{t:e}=Z(),{modal:s,message:n}=Wt.useApp(),a=Re(T=>T.chats),o=Re(T=>T.currentSessionId),r=Re(T=>T.refreshChats),l=Re(T=>T.loadChats),m=Re(T=>T.loadChatHistory),[c,p]=i.useState(!0),[d,b]=i.useState(!1),f=i.useMemo(()=>o?a.find(T=>T.id===o)??null:null,[a,o]),v=async T=>{if(!d){b(!0);try{await T()}finally{b(!1)}}};return t.jsxs($,{vertical:!0,gap:16,children:[t.jsx(F,{size:"small",title:e("settings.sessionsTab.currentSessionTitle"),children:f?t.jsxs($,{vertical:!0,gap:4,children:[t.jsx(Lt,{strong:!0,ellipsis:!0,children:f.title}),t.jsxs(Lt,{type:"secondary",ellipsis:!0,children:[e("settings.sessionsTab.id"),": ",f.id," ","•"," ",e("settings.sessionsTab.kind"),": ",f.kind]}),t.jsx($,{gap:8,wrap:"wrap",style:{marginTop:8},children:t.jsx(z,{danger:!0,loading:d,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 v(async()=>{await zt.clearSession(f.id),await m(f.id),await r(),n.success(e("settings.sessionsTab.sessionCleared"))})}})},children:e("settings.sessionsTab.clearMessages")})})]}):t.jsx(Lt,{type:"secondary",children:e("settings.sessionsTab.noActiveSession")})}),t.jsxs(F,{size:"small",title:e("settings.sessionsTab.bulkCleanupTitle"),children:[t.jsxs($,{align:"center",gap:8,style:{marginBottom:12},children:[t.jsx(Lt,{children:e("settings.sessionsTab.keepPinned")}),t.jsx(ge,{checked:c,onChange:p})]}),t.jsxs($,{gap:8,wrap:"wrap",children:[t.jsx(z,{danger:!0,loading:d,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 v(async()=>{await zt.cleanupSessions("all",c),await l(),n.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteAll")}),t.jsx(z,{danger:!0,loading:d,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 v(async()=>{await zt.cleanupSessions("empty",c),await l(),n.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteEmpty")}),t.jsx(z,{danger:!0,loading:d,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 v(async()=>{await zt.cleanupSessions("children",c),await l(),n.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteChildren")})]})]}),t.jsxs(F,{size:"small",title:e("settings.sessionsTab.devResetTitle"),children:[t.jsx(Lt,{type:"secondary",children:e("settings.sessionsTab.devResetDescription")}),t.jsx($,{style:{marginTop:12},children:t.jsx(z,{danger:!0,type:"primary",loading:d,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 v(async()=>{await zt.devResetSessions(),await l(),n.success(e("settings.sessionsTab.devResetDone"))})}})},children:e("settings.sessionsTab.devResetAction")})})]})]})}const{Text:Ye}=le,{useToken:Ho}=fe,Ko=()=>{const{t:e}=Z(),{token:s}=Ho(),[n,a]=i.useState(Bs()),o=Yn(),r=(l,m)=>{const c={...n,[l]:m};a(c),Zn({[l]:m})};return i.useEffect(()=>{a(Bs())},[]),t.jsx(F,{size:"small",className:"lotus-settings-card",children:t.jsxs($,{vertical:!0,gap:s.marginMD,children:[!o&&t.jsx(ke,{type:"info",showIcon:!0,message:e("settings.notificationsTab.desktopOnly","Desktop notifications are only available in the Bodhi desktop app.")}),t.jsxs($,{align:"center",gap:s.marginSM,children:[t.jsx(xa,{}),t.jsx(Ye,{strong:!0,children:e("settings.notificationsTab.title","Desktop Notifications")})]}),t.jsx(Ye,{type:"secondary",style:{fontSize:s.fontSizeSM},children:e("settings.notificationsTab.description","Receive OS-level notifications when the app is in the background and user action is required.")}),t.jsx(Pe,{style:{margin:`${s.marginXS}px 0`}}),t.jsxs($,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(Ye,{children:e("settings.notificationsTab.enabled","Enable desktop notifications")}),t.jsx(ge,{"data-testid":"notification-enabled-toggle",checked:n.enabled,onChange:l=>r("enabled",l),disabled:!o})]}),t.jsx(Pe,{style:{margin:`${s.marginXS}px 0`}}),t.jsx(Ye,{strong:!0,style:{fontSize:s.fontSizeSM,opacity:n.enabled?1:.5},children:e("settings.notificationsTab.events","Notify when:")}),t.jsxs($,{vertical:!0,gap:s.marginSM,style:{opacity:n.enabled?1:.5,pointerEvents:n.enabled?"auto":"none"},children:[t.jsxs($,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(Ye,{children:e("settings.notificationsTab.onClarification","Agent needs clarification")}),t.jsx(ge,{"data-testid":"notification-clarification-toggle",checked:n.onClarification,onChange:l=>r("onClarification",l),disabled:!o})]}),t.jsxs($,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(Ye,{children:e("settings.notificationsTab.onToolApproval","Tool execution needs approval")}),t.jsx(ge,{"data-testid":"notification-tool-approval-toggle",checked:n.onToolApproval,onChange:l=>r("onToolApproval",l),disabled:!o})]}),t.jsxs($,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(Ye,{children:e("settings.notificationsTab.onContextPressure","Context window is critically full")}),t.jsx(ge,{"data-testid":"notification-context-pressure-toggle",checked:n.onContextPressure,onChange:l=>r("onContextPressure",l),disabled:!o})]}),t.jsxs($,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(Ye,{children:e("settings.notificationsTab.onSubAgentComplete","Background task completes")}),t.jsx(ge,{"data-testid":"notification-subagent-complete-toggle",checked:n.onSubAgentComplete,onChange:l=>r("onSubAgentComplete",l),disabled:!o})]})]}),t.jsx(Pe,{style:{margin:`${s.marginXS}px 0`}}),t.jsxs($,{align:"center",gap:s.marginSM,children:[t.jsx(ba,{style:{color:s.colorPrimary}}),t.jsx(Ye,{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:as,Paragraph:Wo}=le,Go=({open:e,onCancel:s,onComplete:n,onCopyCode:a,completingAuth:o,copiedUserCode:r,deviceCodeInfo:l,timeRemaining:m,token:c})=>{const{t:p}=Z();return t.jsx(ot,{title:p("settings.providerTab.copilotAuthModalTitle"),open:e,onCancel:s,footer:[t.jsx(z,{onClick:s,children:p("settings.providerTab.cancel")},"cancel"),t.jsx(z,{type:"primary",onClick:n,loading:o,children:p("settings.providerTab.completedAuthorization")},"complete")],children:l&&t.jsxs(I,{direction:"vertical",size:"large",style:{width:"100%"},children:[t.jsx(ke,{message:p("settings.providerTab.browserOpened"),description:t.jsxs("ol",{children:[t.jsx("li",{children:p("settings.providerTab.authStep1")}),t.jsx("li",{children:p("settings.providerTab.authStep2")}),t.jsx("li",{children:p("settings.providerTab.authStep3")})]}),type:"info"}),t.jsx(F,{size:"small",className:"lotus-settings-card",children:t.jsxs(I,{direction:"vertical",style:{width:"100%"},children:[t.jsx(as,{type:"secondary",children:p("settings.providerTab.visitUrl")}),t.jsx(I,{children:t.jsx(as,{copyable:{text:l.verification_uri},children:l.verification_uri})})]})}),t.jsx(F,{style:{textAlign:"center",background:c.colorFillTertiary,borderColor:c.colorBorderSecondary},children:t.jsxs(I,{direction:"vertical",style:{width:"100%"},children:[t.jsx(as,{type:"secondary",children:p("settings.providerTab.enterCode")}),t.jsxs(I,{children:[t.jsx(as,{style:{color:c.colorText,fontSize:"32px",fontFamily:"monospace",fontWeight:"bold",letterSpacing:"4px"},children:l.user_code}),t.jsx(z,{icon:r?t.jsx(Ms,{}):t.jsx(En,{}),onClick:a,type:r?"default":"primary",children:p(r?"settings.providerTab.copied":"settings.providerTab.copyCode")})]}),t.jsx("div",{style:{marginTop:8},children:t.jsxs(ue,{color:m<60?"error":m<180?"warning":"success",children:[t.jsx(va,{style:{marginRight:4}}),"Expires in ",Math.floor(m/60),":",(m%60).toString().padStart(2,"0")]})})]})}),t.jsx(Wo,{type:"secondary",children:p("settings.providerTab.afterContinueHint")})]})})},{Password:bn}=U,{Text:He,Paragraph:_s}=le,rs=["openai","anthropic","gemini","copilot","bodhi"],os=()=>null,Jo=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()))},Xo=(e,s,n)=>{const a=e;a[s]={...a[s]??{},model:n}},vn=e=>t.jsxs(I,{direction:"vertical",size:4,children:[t.jsxs(He,{type:"secondary",children:[e("settings.providerTab.responsesOnlyHelp1")," ",t.jsx(He,{code:!0,children:"/responses"}),"."]}),t.jsx(He,{type:"secondary",children:e("settings.providerTab.responsesOnlyHelp2")})]}),Yo=["low","medium","high","xhigh","max"],xt=(e,s)=>t.jsx(ae,{placeholder:e("settings.providerTab.reasoningEffortDefault"),allowClear:!0,value:s==null?void 0:s.value,onChange:s!=null&&s.onChange?n=>{var a;return(a=s.onChange)==null?void 0:a.call(s,n??void 0)}:void 0,disabled:s==null?void 0:s.disabled,size:s==null?void 0:s.size,style:s==null?void 0:s.style,"data-testid":s==null?void 0:s["data-testid"],children:Yo.map(n=>t.jsx(ae.Option,{value:n,children:e(`chat.input.reasoning.${n}`)},n))}),Zo=()=>{const{t:e}=Z(),{token:s}=fe.useToken(),{message:n}=Wt.useApp(),[a]=k.useForm(),[o,r]=i.useState(!1),[l,m]=i.useState(!1),[c,p]=i.useState("copilot"),[d,b]=i.useState(!1),[f,v]=i.useState(null),[T,u]=i.useState(!1),[M,j]=i.useState(!1),[x,E]=i.useState(null),[S,P]=i.useState(!1),[ee,R]=i.useState(!1),[q,G]=i.useState(0),[h,y]=i.useState(!1),[D,_]=i.useState([]),[O,X]=i.useState(!1),[A,H]=i.useState("idle"),[V,oe]=i.useState(null);i.useEffect(()=>{if(A!=="success")return;const C=setTimeout(()=>{H("idle"),oe(null)},2e3);return()=>clearTimeout(C)},[A]),i.useEffect(()=>{if(!S||!x){G(0);return}G(x.expires_in);const C=setInterval(()=>{G(w=>w<=1?(clearInterval(C),0):w-1)},1e3);return()=>clearInterval(C)},[S,x]);const ce=i.useCallback(async()=>{var C;try{r(!0);const w=await $e.getProviderConfig();let J=w.defaults;if(!((C=J==null?void 0:J.chat)!=null&&C.model)&&w.provider&&w.providers){const pe=w.provider,re=w.providers[pe],Ee=re==null?void 0:re.model;Ee&&(J={chat:{provider:pe,model:Ee}})}const B={provider:w.provider,defaults:J,providers:w.providers||{},features:w.features};rt("[Provider]","Loaded provider config:",B);const Y={...B.providers||{}};rs.forEach(pe=>{const re=Y[pe];re&&re.request_overrides&&typeof re.request_overrides=="object"&&(re.request_overrides_json=JSON.stringify(re.request_overrides,null,2))}),p(B.provider),a.setFieldsValue({...B,providers:Y,defaults:B.defaults}),b(!0)}catch(w){n.error(e("settings.providerTab.loadConfigFailed")),console.error("Failed to load provider config:",w)}finally{r(!1)}},[a,n,e]),K=i.useCallback(async()=>{try{const C=await $e.getEnvVars();_(C.entries||[])}catch(C){console.warn("Failed to load env vars for provider overrides:",C)}},[]),L=i.useCallback(async()=>{try{u(!0);const C=await $e.getCopilotAuthStatus();v(C)}catch(C){console.error("Failed to check Copilot auth status:",C),v({authenticated:!1,message:e("settings.providerTab.checkStatusFailed")})}finally{u(!1)}},[e]);i.useEffect(()=>{ce(),K(),$t.getState().loadCatalog(),L()},[ce,K,L]);const W=async()=>{try{j(!0);const C=await $e.startCopilotAuth();E(C),P(!0)}catch(C){n.error(e("settings.providerTab.startCopilotAuthFailed")),console.error("Failed to start Copilot authentication:",C)}finally{j(!1)}},Q=async()=>{if(x)try{R(!0),await $e.completeCopilotAuth({device_code:x.device_code,interval:x.interval||5,expires_in:x.expires_in}),n.success(e("settings.providerTab.copilotAuthSuccess")),P(!1),E(null),await L()}catch(C){n.error(e("settings.providerTab.completeAuthFailed")),console.error("Authentication completion failed:",C)}finally{R(!1)}},se=async()=>{if(x)try{await Mn(x.user_code),y(!0),n.success(e("settings.providerTab.userCodeCopied")),setTimeout(()=>y(!1),2e3)}catch{n.error(`${e("settings.providerTab.copyCodeFailedPrefix")} ${x.user_code}`)}},we=async()=>{try{j(!0),await $e.logoutCopilot(),n.success(e("settings.providerTab.logoutSuccess")),await L()}catch(C){n.error(e("settings.providerTab.logoutFailed")),console.error("Failed to logout:",C)}finally{j(!1)}},qe=i.useCallback(async()=>{X(!0);try{const C=await $e.fetchCatalogModels();await $t.getState().loadCatalog();const w=C.fetched.filter(B=>B.models&&B.models.length>0).length;C.fetched.filter(B=>B.error).length>0?n.warning(e("settings.providerTab.fetchModelsPartialSuccess",{success:w,total:C.fetched.length})):n.success(e("settings.providerTab.fetchModelsSuccess",{count:w}))}catch{n.error(e("settings.providerTab.fetchModelsFailed"))}finally{X(!1)}},[n,e]),Ie=C=>Qn(C)||C instanceof Error?C.message:e("settings.providerTab.unknownError"),kt=C=>{a.setFields([{name:["provider"],errors:[]},{name:["providers",C,"api_key"],errors:[]},{name:["defaults","chat"],errors:[]}])},ft=C=>{const w=C.trim();return w?w.includes(".")?w.split(".").filter(Boolean):w==="provider"?["provider"]:w==="provider/providers"?["provider"]:null:null},wt=(C,w)=>{if(!C.length)return;const J=C.map(B=>{const Y=ft(B.path);return Y?{name:Y,errors:[B.message]}:B.message.toLowerCase().includes("api key")?{name:["providers",w,"api_key"],errors:[B.message]}:{name:["provider"],errors:[B.message]}}).filter((B,Y,pe)=>pe.findIndex(re=>JSON.stringify(re.name)===JSON.stringify(B.name))===Y);J.length&&a.setFields(J)},Ct=async C=>{var J;const w=C.provider||c;kt(w);try{const Y=await qt.getInstance().validateBambooConfigPatch({provider:C.provider,providers:C.providers||{},defaults:C.defaults});if(Y.valid)return{valid:!0};const pe=((J=Y.errors)==null?void 0:J.provider)||[];wt(pe,w);const re=pe[0];return{valid:!1,message:(re==null?void 0:re.message)||e("settings.providerTab.invalidConfig")}}catch(B){return console.warn("Config validation failed, falling back to save:",B),{valid:!0}}},it=async(C,w)=>{var J,B;try{r(!0);const Y={provider:C.provider,defaults:C.defaults,providers:{...C.providers||{}},features:C.features},pe=(J=Y.defaults)==null?void 0:J.chat;if(!Jo(pe)){const Te=e("settings.providerTab.selectModelRequired");if(a.setFields([{name:["defaults","chat"],errors:[Te]}]),(w==null?void 0:w.showMessage)!==!1&&n.error(Te),w!=null&&w.throwOnError)throw new Error(Te);return}const re=Y.providers;for(const Te of rs){const We=re[Te];if(!We)continue;const Et=We.request_overrides_json;if(typeof Et!="string")continue;const Dt=Et.trim();if(!Dt)delete We.request_overrides;else try{We.request_overrides=JSON.parse(Dt)}catch(hs){const st=e("settings.providerTab.invalidRequestOverridesJson",{provider:Te,error:hs.message});if(a.setFields([{name:["providers",Te,"request_overrides_json"],errors:[st]}]),(w==null?void 0:w.showMessage)!==!1&&n.error(st),w!=null&&w.throwOnError)throw hs;return}delete We.request_overrides_json}const Ee={...Y.providers||{}},Ve=Y.provider,De=(B=Y.defaults)==null?void 0:B.chat;De!=null&&De.model&&Ve&&Xo(Ee,Ve,De.model);const Be={provider:Y.provider,defaults:Y.defaults,providers:Ee,features:Y.features},ye=await Ct(Y);if(!ye.valid){const Te=ye.message||e("settings.providerTab.invalidConfig");if((w==null?void 0:w.showMessage)!==!1&&n.error(`${e("settings.providerTab.invalidConfigPrefix")}: ${Te}`),w!=null&&w.throwOnError)throw new Error(Te);return}rt("[Provider]","Saving provider config:",Be),await $e.saveProviderConfig(Be),(w==null?void 0:w.showMessage)!==!1&&n.success(e("settings.providerTab.saveConfigSuccess"))}catch(Y){const pe=Ie(Y);if((w==null?void 0:w.showMessage)!==!1&&n.error(pe?`${e("settings.providerTab.saveConfigErrorPrefix")}: ${pe}`:e("settings.providerTab.saveConfigFailed")),console.error("Failed to save configuration:",Y),w!=null&&w.throwOnError)throw Y}finally{r(!1)}},lt=async C=>{var w,J,B,Y,pe;try{m(!0);const{useProviderStore:re}=await Es(async()=>{const{useProviderStore:st}=await import("./App-bVqmFSlk.js").then(fs=>fs.a8);return{useProviderStore:st}},__vite__mapDeps([4,1,2,3,5,6,7,8]),import.meta.url),{useAppStore:Ee}=await Es(async()=>{const{useAppStore:st}=await import("./App-bVqmFSlk.js").then(fs=>fs.a9);return{useAppStore:st}},__vite__mapDeps([4,1,2,3,5,6,7,8]),import.meta.url),Ve=(w=re.getState().providerConfig.defaults)==null?void 0:w.chat;await re.getState().loadProviderConfig();const De=(J=re.getState().providerConfig.defaults)==null?void 0:J.chat;re.getState().setSelectedModelRef(null);const Be=Ee.getState().currentSessionId,ye=Be&&Ee.getState().chats.find(st=>st.id===Be)||null,Te=Ve?`${Ve.provider}/${Ve.model}`:null,We=De?`${De.provider}/${De.model}`:null,Et=(B=ye==null?void 0:ye.config)!=null&&B.model_ref?`${ye.config.model_ref.provider}/${ye.config.model_ref.model}`:null,Dt=((pe=(Y=ye==null?void 0:ye.config)==null?void 0:Y.model)==null?void 0:pe.trim())||null;!!(Be&&(ye!=null&&ye.config)&&De&&We!==Te&&(!Et||Et===Te)&&(!Dt||Dt===(Ve==null?void 0:Ve.model)))&&Be&&(ye!=null&&ye.config)&&De&&Ee.getState().updateSession(Be,{config:{...ye.config,model:De.model,model_ref:De}}),(C==null?void 0:C.showMessage)!==!1&&n.success(e("settings.providerTab.applyConfigSuccess"))}catch(re){const Ee=Ie(re);if((C==null?void 0:C.showMessage)!==!1&&n.error(Ee?`${e("settings.providerTab.applyConfigErrorPrefix")}: ${Ee}`:e("settings.providerTab.applyConfigFailed")),console.error("Failed to apply configuration:",re),C!=null&&C.throwOnError)throw re}finally{m(!1)}},Le=async C=>{try{const w=a.getFieldsValue(!0);await it(w,{throwOnError:!0}),await lt({throwOnError:!0})}catch{}},Mt=async(C,w)=>{if(!(C==="chat"&&!w)&&A!=="saving"){H("saving"),oe(null);try{const J=a.getFieldsValue(!0),B=J.defaults;if(!(B!=null&&B.chat))throw new Error(e("settings.providerTab.selectModelRequired"));J.defaults={...B,[C]:w},await it(J,{showMessage:!1,throwOnError:!0}),await lt({showMessage:!1,throwOnError:!0}),H("success"),n.success(e("settings.providerTab.modelUpdated"))}catch(J){const B=Ie(J);H("error"),oe(B),n.error(B?`${e("settings.providerTab.updateModelErrorPrefix")}: ${B}`:e("settings.providerTab.updateModelFailed"))}}},g=async()=>{if(A!=="saving"){H("saving"),oe(null);try{const C=a.getFieldsValue(!0);await it(C,{showMessage:!1,throwOnError:!0}),await lt({showMessage:!1,throwOnError:!0}),H("success"),n.success(e("settings.providerTab.reasoningEffortUpdated"))}catch(C){const w=Ie(C);H("error"),oe(w),n.error(w?`${e("settings.providerTab.updateReasoningEffortErrorPrefix")}: ${w}`:e("settings.providerTab.updateReasoningEffortFailed"))}}},ne=(C,w)=>{if(!C)return null;const J=Pt[C],B=a.getFieldValue(["providers",C,"reasoning_effort"]);return t.jsx("div",{style:{marginTop:(w==null?void 0:w.marginTop)??8},children:t.jsxs(I,{direction:"vertical",size:4,style:{width:"100%"},children:[t.jsx(He,{strong:!0,children:(w==null?void 0:w.label)||`${J} · ${e("settings.providerTab.reasoningEffortOptional")}`}),xt(e,{value:B,disabled:A==="saving",size:w==null?void 0:w.size,style:{width:"100%"},"data-testid":w==null?void 0:w.dataTestId,onChange:Y=>{a.setFieldValue(["providers",C,"reasoning_effort"],Y),w!=null&&w.autoSave&&g()}}),t.jsx(He,{type:"secondary",children:(w==null?void 0:w.helperText)||e("settings.providerTab.reasoningEffortHelp")})]})})},de=i.useCallback(C=>{const w=a.getFieldValue(["providers",C]);return w?C==="copilot"?(f==null?void 0:f.authenticated)??!1:!!w.api_key:!1},[a,f]),Ce=()=>{const C=J=>{const B=a.getFieldValue(["defaults",J]);return t.jsx(ea,{value:B,disabled:A==="saving",onChange:Y=>{a.setFieldValue(["defaults",J],Y),Mt(J,Y)}})},w=(J,B,Y)=>t.jsxs("div",{children:[t.jsx(He,{strong:!0,children:B}),t.jsx("div",{style:{marginTop:8},children:C(J)}),t.jsx(k.Item,{noStyle:!0,shouldUpdate:!0,children:()=>{const pe=a.getFieldValue(["defaults",J]),re=pe==null?void 0:pe.provider;return ne(re,{autoSave:!0,dataTestId:`model-preference-${J}-reasoning-effort`,label:re?`${Pt[re]} · ${e("settings.providerTab.reasoningEffortOptional")}`:e("settings.providerTab.reasoningEffortOptional"),helperText:e("settings.providerTab.reasoningEffortHelp")})}}),Y?t.jsx(He,{type:"secondary",children:Y}):null]});return t.jsxs(F,{size:"small",title:e("settings.providerTab.modelPreferences"),style:{marginBottom:16},children:[t.jsx(k.Item,{name:["defaults","chat"],noStyle:!0,preserve:!0,children:t.jsx(os,{})}),t.jsx(k.Item,{name:["defaults","fast"],noStyle:!0,preserve:!0,children:t.jsx(os,{})}),t.jsx(k.Item,{name:["defaults","sub_agent"],noStyle:!0,preserve:!0,children:t.jsx(os,{})}),t.jsx(k.Item,{name:["defaults","vision"],noStyle:!0,preserve:!0,children:t.jsx(os,{})}),t.jsxs(I,{direction:"vertical",size:16,style:{width:"100%"},children:[w("chat",e("settings.providerTab.defaultModel")),w("fast",e("settings.providerTab.fastModel"),e("settings.providerTab.fastModelHelp")),w("sub_agent",e("settings.providerTab.subAgentModel"),e("settings.providerTab.subAgentModelHelp")),w("vision",e("settings.providerTab.visionModel"),e("settings.providerTab.visionModelHelp"))]})]})},me=C=>{const w=D.map(B=>B.name);return t.jsx(k.Item,{name:["providers",C,"request_overrides_json"],label:e("settings.providerTab.advancedRequestOverrides"),extra:t.jsxs(I,{direction:"vertical",size:4,children:[t.jsx(He,{type:"secondary",children:e("settings.providerTab.advancedRequestOverridesHelp")}),t.jsxs(He,{type:"secondary",children:[e("settings.providerTab.envVarInjection")," ",t.jsx(He,{code:!0,children:'{ "type": "env_ref", "name": "YOUR_ENV_NAME" }'})]}),w.length>0&&t.jsx(I,{wrap:!0,size:[6,6],children:w.map(B=>t.jsx(ue,{children:B},B))})]}),children:t.jsx(U.TextArea,{autoSize:{minRows:8,maxRows:20},placeholder:`{
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-DCmbOzco.js","./vendor-markdown-DZuK0SxV.js","./vendor-i18n-BNURlJ23.js","./vendor-antd-C8lKwvI6.js","./App-DRZhqTnn.js","./vendor-mermaid-C1Gk9PtT.js","./main-DZ0RS3MR.js","./main-B6snAd4S.css","./App-DNZiQHSs.css"])))=>i.map(i=>d[i]);
2
+ var On=Object.defineProperty;var Nn=(e,s,n)=>s in e?On(e,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[s]=n;var Vs=(e,s,n)=>Nn(e,typeof s!="symbol"?s+"":s,n);import{j as t}from"./vendor-markdown-DZuK0SxV.js";import{a as i,u as Z,R as $s,i as te}from"./vendor-i18n-BNURlJ23.js";import{z as Vn,u as Re,b as $n,F as qn,s as Bn,G as Is,j as $t,t as rt,H as Un,J as at,K as Se,L as Hn,M as Kn,N as Wn,O as Gn,P as wn,S as qt,Q as $e,y as qs,a as Ge,R as Cn,x as Mn,d as Jn,c as Cs,o as Xn,T as Bs,U as Yn,V as Zn,W as Pt,X as Qn,Y as ea,Z as ta,_ as Us,$ as Hs,a0 as Ks,a1 as Ws,f as sa,a2 as na,A as aa,a3 as ra,a4 as oa,a5 as ia,a6 as la,a7 as ca}from"./App-DRZhqTnn.js";import{C as F,S as I,A as ke,j as le,X as U,E as z,t as fe,N as k,K as Bt,av as ls,aw as ae,ax as ge,L as Ke,ay as Ne,az as ie,n as xe,aA as Fe,aB as he,aC as da,at as Pe,F as $,aD as Fs,aE as ua,U as cs,V as gs,ad as ga,aF as ma,M as Wt,aG as ms,Q as Rs,O as Ut,aH as Gs,l as ue,aI as et,W as ot,aj as Tt,J as jt,a9 as bt,aJ as pa,ac as ha,aK as Js,aL as _e,H as Ae,ai as En,aM as fa,aN as tt,aO as be,B as ya,aP as Xs,aQ as xa,aR as ba,m as Ms,z as va,aS as Ys,aT as es,aU as Ta,aV as ja,a4 as Sa,ao as _a,aW as ka}from"./vendor-antd-C8lKwvI6.js";import{_ as Es}from"./vendor-mermaid-C1Gk9PtT.js";import{r as wa}from"./onboardingStorage-BVcEpmTy.js";import"./main-DZ0RS3MR.js";import{m as Vt}from"./MetricsService-CvnuWjgH.js";import{R as St,B as As,C as Gt,X as Jt,Y as Xt,T as _t,L as Ls,a as ds,b as Dn,c as vt,P as Ca,d as Ma,e as Ea}from"./vendor-charts-bhMup2Pu.js";function Da(e){return e instanceof Vn}function Pa(){const{chats:e,currentSessionId:s,currentChat:n,addMessage:a,selectSession:o,deleteSession:r,deleteSessions:l,deleteMessage:m,updateSession:c,persistSessionTitle:p,pinSession:d,unpinSession:b,loadChats:f}=Re($n(x=>({chats:x.chats,currentSessionId:x.currentSessionId,currentChat:qn(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}))),v=Re(Bn(s)),T=i.useMemo(()=>(n==null?void 0:n.messages)||[],[n]),u=i.useMemo(()=>e.filter(x=>x.pinned),[e]),M=i.useMemo(()=>e.filter(x=>!x.pinned),[e]),j=e.length;return{chats:e,currentSessionId:s,currentChat:n,isProcessing:v,baseMessages:T,pinnedChats:u,unpinnedChats:M,chatCount:j,addMessage:a,deleteMessage:m,selectSession:o,deleteSession:r,deleteSessions:l,pinSession:d,unpinSession:b,updateSession:c,persistSessionTitle:p,loadChats:f}}function Ia(e){const s=Re(f=>f.addChat),n=Re(f=>f.lastSelectedPromptId),a=Re(f=>f.systemPrompts),o=Is.getInstance(),r=i.useCallback(async(f,v)=>{var j,x;const T=a.find(E=>E.id===n),u=(T==null?void 0:T.id)||(a.length>0?((j=a.find(E=>E.id==="general_assistant"))==null?void 0:j.id)||a[0].id:""),M={title:f||"New Session",createdAt:Date.now(),messages:[],config:{systemPromptId:u,baseSystemPrompt:(T==null?void 0:T.content)||(a.length>0?((x=a.find(E=>E.id==="general_assistant"))==null?void 0:x.content)||a[0].content:""),lastUsedEnhancedPrompt:null,...$t.getState().isProviderModelRefEnabled()?{model_ref:$t.getState().selectedModelRef}:{}},...v};await s(M)},[s,n,a]),l=i.useCallback(async f=>{rt("[ChatOps]","[useChatOperations] createChatWithSystemPrompt started with prompt:",f);const v={title:`New Session - ${f.name}`,createdAt:Date.now(),messages:[],config:{systemPromptId:f.id,baseSystemPrompt:f.content,lastUsedEnhancedPrompt:null}};rt("[ChatOps]","[useChatOperations] Calling addChat with newChatData.config:",v.config),await s(v)},[s]),m=i.useCallback(f=>{const v=e.chats.find(T=>T.id===f);v&&(v.pinned?e.unpinSession(f):e.pinSession(f))},[e]),c=i.useCallback((f,v)=>{e.updateSession(f,{title:v})},[e]),p=i.useCallback(async()=>{await o.cleanupSessions("empty",!0),await Re.getState().loadChats()},[o]),d=i.useCallback(async()=>{await o.cleanupSessions("all",!0),await Re.getState().loadChats()},[o]),b=i.useCallback(async()=>{await o.cleanupSessions("all",!1),await Re.getState().loadChats()},[o]);return{createNewChat:r,createChatWithSystemPrompt:l,toggleChatPin:m,updateChatTitle:c,deleteEmptyChats:p,deleteAllUnpinnedChats:d,deleteAllChats:b}}function Fa(e,s){const n=i.useMemo(()=>e.baseMessages,[e.baseMessages]),a=i.useCallback(async()=>{var p;if(!e.currentSessionId||!e.currentChat)return;const o=[...e.baseMessages];if(o.length===0)return;const r=o[o.length-1];let l=o;if((r==null?void 0:r.role)==="assistant"){if(!(await e.deleteMessage(e.currentSessionId,r.id)).success)return;l=o.slice(0,-1)}const m=[...l].reverse().find(d=>d.role==="user");if(!m)return;const c="content"in m?m.content:m.displayText;typeof c=="string"&&await((p=s==null?void 0:s.onRetry)==null?void 0:p.call(s,c))},[e,s]);return{currentMessages:n,retryLastMessage:a}}const Ra=()=>{const e=Pa(),s=Ia(e),n=Un({sessionId:e.currentSessionId,addMessage:e.addMessage,updateSession:e.updateSession}),a=Fa(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:ts}=le,{useToken:Aa}=fe,La=({httpProxy:e,httpsProxy:s,onHttpProxyChange:n,onHttpsProxyChange:a,onReload:o,onSave:r,isLoading:l})=>{const{t:m}=Z(),{token:c}=Aa(),p=at(S=>S.proxyAuthStatus),d=at(S=>S.isLoadingProxyAuthStatus),b=at(S=>S.loadProxyAuthStatus),f=at(S=>S.applyProxyAuth),v=at(S=>S.clearProxyAuth),[T,u]=i.useState({username:"",password:""}),[M,j]=i.useState(!1);i.useEffect(()=>{b()},[b]);const x=async()=>{const S=T.username.trim();if(S){j(!0);try{await f({username:S,password:T.password}),u({username:"",password:""})}catch(P){console.error("Failed to apply proxy auth:",P)}finally{j(!1)}}},E=async()=>{j(!0);try{await v()}catch(S){console.error("Failed to clear proxy auth:",S)}finally{j(!1)}};return t.jsx(F,{size:"small",title:t.jsx(ts,{strong:!0,children:m("settings.networkCard.title")}),className:"lotus-settings-card",children:t.jsxs(I,{direction:"vertical",size:c.marginSM,style:{width:"100%"},children:[t.jsx(ke,{message:m("settings.networkCard.guideTip"),type:"info",showIcon:!0}),t.jsxs(I,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[t.jsx(ts,{type:"secondary",children:m("settings.networkCard.httpProxy")}),t.jsx(U,{"data-testid":"proxy-url",style:{width:"100%"},value:e,onChange:S=>n(S.target.value),placeholder:m("settings.networkCard.proxyPlaceholder"),disabled:l})]}),t.jsxs(I,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[t.jsx(ts,{type:"secondary",children:m("settings.networkCard.httpsProxy")}),t.jsx(U,{style:{width:"100%"},value:s,onChange:S=>a(S.target.value),placeholder:m("settings.networkCard.proxyPlaceholder"),disabled:l})]}),t.jsx(F,{size:"small",title:m("settings.networkCard.proxyAuthTitle"),className:"lotus-settings-card",style:{marginTop:c.marginSM},children:p!=null&&p.configured?t.jsxs(I,{direction:"vertical",style:{width:"100%"},children:[t.jsx(ke,{type:"success",message:m("settings.networkCard.proxyConfiguredForUser",{username:p.username??""}),showIcon:!0}),t.jsx(z,{onClick:E,loading:M||d,danger:!0,children:m("settings.networkCard.clearCredentials")})]}):t.jsxs(I,{direction:"vertical",size:c.marginXS,style:{width:"100%"},children:[t.jsx(U,{placeholder:m("settings.networkCard.username"),value:T.username,onChange:S=>u(P=>({...P,username:S.target.value}))}),t.jsx(U.Password,{placeholder:m("settings.networkCard.password"),value:T.password,onChange:S=>u(P=>({...P,password:S.target.value}))}),t.jsx(z,{type:"primary",onClick:x,loading:M||d,disabled:!T.username.trim(),children:m("settings.networkCard.apply")})]})}),t.jsx(ts,{type:"secondary",style:{fontSize:c.fontSizeSM},children:m("settings.networkCard.credentialsStorageNote")}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:c.marginSM},children:[t.jsx(z,{onClick:()=>Promise.resolve(o()).finally(()=>b({force:!0})),disabled:l,children:m("settings.networkCard.reload")}),t.jsx(z,{"data-testid":"save-proxy-settings",type:"primary",onClick:()=>Promise.resolve(r()).finally(()=>b({force:!0})),disabled:l,children:m("settings.networkCard.save")})]})]})})},{Text:za}=le,{useToken:Oa}=fe,Na=({msgApi:e})=>{const{t:s}=Z(),{token:n}=Oa(),[a]=k.useForm(),[o,r]=i.useState(!1),[l,m]=i.useState(!1),[c,p]=i.useState(!1),[d,b]=i.useState(!1),[f,v]=i.useState(null),T=c&&!d,u=i.useMemo(()=>s(c?d?"settings.configTab.accessPassword.helperLocalBypass":"settings.configTab.accessPassword.helperRemote":"settings.configTab.accessPassword.helperNotEnabled"),[d,c,s]),M=i.useCallback(async()=>{r(!0),v(null);try{const x=await Se.getAccessStatus();p(x.password_enabled),b(x.local_bypass)}catch(x){const E=x instanceof Error?x.message:s("settings.configTab.accessPassword.loadStatusFailed","Failed to load access status");v(E)}finally{r(!1)}},[s]);i.useEffect(()=>{M()},[M]);const j=async()=>{var x;try{const E=await a.validateFields();m(!0),await Se.updateAccessPassword({current_password:((x=E.currentPassword)==null?void 0:x.trim())||void 0,new_password:E.newPassword.trim()}),e.success(s(c?"settings.configTab.accessPassword.updated":"settings.configTab.accessPassword.enabled")),a.resetFields(),await M()}catch(E){if(E.errorFields)return;const S=E instanceof Error?E.message:s("settings.configTab.accessPassword.updateFailed","Failed to update access password");e.error(S)}finally{m(!1)}};return t.jsx(F,{size:"small",className:"lotus-settings-card",title:t.jsx(za,{strong:!0,children:s("settings.configTab.accessPasswordTitle")}),children:t.jsxs(I,{direction:"vertical",size:n.marginMD,style:{width:"100%"},children:[t.jsx(ke,{type:c?"info":"warning",showIcon:!0,message:s(c?"settings.configTab.accessPassword.statusEnabled":"settings.configTab.accessPassword.statusDisabled"),description:u}),f?t.jsx(ke,{type:"error",showIcon:!0,message:f}):null,t.jsxs(k,{form:a,layout:"vertical",disabled:o||l,children:[T?t.jsx(k.Item,{label:s("settings.configTab.accessPassword.currentPasswordLabel"),name:"currentPassword",rules:[{required:!0,message:s("settings.configTab.accessPassword.validation.currentPasswordRequired")}],children:t.jsx(U.Password,{autoComplete:"current-password"})}):null,t.jsx(k.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(U.Password,{autoComplete:"new-password"})}),t.jsx(k.Item,{label:s("settings.configTab.accessPassword.confirmPasswordLabel"),name:"confirmPassword",dependencies:["newPassword"],rules:[{required:!0,message:s("settings.configTab.accessPassword.validation.confirmPasswordRequired")},({getFieldValue:x})=>({validator(E,S){return!S||x("newPassword")===S?Promise.resolve():Promise.reject(new Error(s("settings.configTab.accessPassword.validation.passwordMismatch")))}})],children:t.jsx(U.Password,{autoComplete:"new-password"})}),t.jsx(z,{type:"primary",loading:l,onClick:()=>void j(),children:s(c?"settings.configTab.accessPassword.updateAction":"settings.configTab.accessPassword.enableAction")})]})]})})},{Text:ze}=le,{useToken:Va}=fe,Zs="http://127.0.0.1:9562/v1",Ot=e=>[...new Set(e.map(s=>s.trim()).filter(s=>s.length>0))].sort(),$a=e=>{var n;const s=(n=e.tools)==null?void 0:n.disabled;return Array.isArray(s)?Ot(s.filter(a=>typeof a=="string")):[]},qa=({msgApi:e,locale:s,onLocaleChange:n})=>{const{t:a}=Z(),{token:o}=Va(),[r,l]=i.useState({http_proxy:"",https_proxy:"",memory:{auto_dream_enabled:!1,background_model:""}}),[m,c]=i.useState(Zs),[p,d]=i.useState([]),[b,f]=i.useState([]),[v,T]=i.useState([]),[u,M]=i.useState(!1),[j,x]=i.useState(!1),E=i.useCallback(async()=>{var A,H;M(!0);try{const[V,oe]=await Promise.all([Se.getBambooConfig(),Se.getBambooTools()]);l({http_proxy:V.http_proxy||"",https_proxy:V.https_proxy||"",memory:{auto_dream_enabled:((A=V.memory)==null?void 0:A.auto_dream_enabled)??!1,background_model:((H=V.memory)==null?void 0:H.background_model)||""}});const ce=$a(V);f(ce),T(ce),d(Ot(oe.tools||[]))}catch(V){console.error("Failed to load config:",V),e.error(a("settings.configTab.loadConfigFailed"))}finally{M(!1)}},[e,a]);i.useEffect(()=>{E()},[E]);const S=A=>{l(H=>({...H,http_proxy:A}))},P=A=>{l(H=>({...H,https_proxy:A}))},ee=A=>{l(H=>({...H,memory:{...H.memory,auto_dream_enabled:A}}))},R=A=>{l(H=>({...H,memory:{...H.memory,background_model:A}}))},q=async()=>{var A,H;M(!0);try{const V=await Se.validateBambooConfigPatch(r);if(!V.valid){const ce=((H=(A=V.errors)==null?void 0:A.proxy)==null?void 0:H[0])??Object.values(V.errors||{}).flat().filter(Boolean)[0];e.error((ce==null?void 0:ce.message)||a("settings.configTab.invalidConfig"));return}await Se.setBambooConfig(r),e.success(a("settings.configTab.saveConfigSuccess"))}catch(V){console.error("Failed to save config:",V);const oe=V instanceof Error&&V.message.trim()?V.message:a("settings.configTab.saveConfigFailed");e.error(oe)}finally{M(!1)}},G=async()=>{e.success(a("settings.configTab.backendSaved"))},h=()=>{c(Zs),e.success(a("settings.configTab.backendResetDefault"))},y=(A,H)=>{f(V=>{const oe=new Set(V);return H?oe.delete(A):oe.add(A),Ot([...oe])})},D=async()=>{x(!0);try{const A=await Se.getBambooTools();d(Ot(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)}},_=async()=>{x(!0);try{const A=Ot(b);await Se.setBambooConfig({tools:{disabled:A}}),f(A),T(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)}},O=JSON.stringify(b)!==JSON.stringify(v),X=new Set(b);return t.jsx(Bt,{spinning:u,tip:a("settings.common.loading"),children:t.jsx(ls,{items:[{key:"general",label:a("settings.configTab.tabs.general"),children:t.jsxs(I,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[t.jsx(ke,{message:a("settings.configTab.providerMovedTitle"),description:a("settings.configTab.providerMovedDescription"),type:"info",showIcon:!0,closable:!0}),t.jsx(La,{httpProxy:r.http_proxy,httpsProxy:r.https_proxy,onHttpProxyChange:S,onHttpsProxyChange:P,onReload:E,onSave:q,isLoading:u}),t.jsx(F,{size:"small",className:"lotus-settings-card",title:t.jsx(ze,{strong:!0,children:a("settings.configTab.language")}),children:t.jsx(ae,{value:s,style:{width:260},options:[{label:a("settings.configTab.languageEnglish"),value:"en-US"},{label:a("settings.configTab.languageChinese"),value:"zh-CN"},{label:a("settings.configTab.languageTraditionalChinese"),value:"zh-TW"},{label:a("settings.configTab.languageFrench"),value:"fr-FR"},{label:a("settings.configTab.languageJapanese"),value:"ja-JP"},{label:a("settings.configTab.languageHindi"),value:"hi-IN"}],onChange:A=>n(A)})}),t.jsx(F,{size:"small",className:"lotus-settings-card",title:t.jsx(ze,{strong:!0,children:a("settings.configTab.memoryTitle")}),children:t.jsxs(I,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[t.jsx(ze,{type:"secondary",children:a("settings.configTab.memoryDescription")}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:o.marginMD,flexWrap:"wrap"},children:[t.jsxs("div",{children:[t.jsx(ze,{strong:!0,children:a("settings.configTab.autoDreamEnabled")}),t.jsx("div",{children:t.jsx(ze,{type:"secondary",style:{fontSize:o.fontSizeSM},children:a("settings.configTab.autoDreamEnabledHint")})})]}),t.jsx(ge,{"data-testid":"auto-dream-toggle",checked:r.memory.auto_dream_enabled,onChange:ee})]}),t.jsxs(I,{direction:"vertical",size:o.marginXXS,style:{width:"100%"},children:[t.jsx(ze,{strong:!0,children:a("settings.configTab.backgroundModel")}),t.jsx(U,{"data-testid":"auto-dream-background-model-input",value:r.memory.background_model,onChange:A=>R(A.target.value),placeholder:a("settings.configTab.backgroundModelPlaceholder")}),t.jsx(ze,{type:"secondary",style:{fontSize:o.fontSizeSM},children:a("settings.configTab.backgroundModelHint")})]}),t.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:t.jsx(z,{"data-testid":"save-memory-settings",type:"primary",onClick:q,loading:u,children:a("settings.configTab.save")})})]})}),t.jsx(F,{size:"small",title:t.jsx(ze,{strong:!0,children:a("settings.configTab.backendApiBaseUrlTitle")}),children:t.jsxs(I,{direction:"vertical",size:o.marginSM,style:{width:"100%"},children:[t.jsx(I,{direction:"vertical",size:o.marginXXS,style:{width:"100%"},children:t.jsx(U,{style:{width:"100%"},value:m,onChange:A=>c(A.target.value),placeholder:a("settings.configTab.backendApiPlaceholder")})}),t.jsx(ze,{type:"secondary",style:{fontSize:o.fontSizeSM},children:a("settings.configTab.backendApiHint")}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:o.marginSM},children:[t.jsx(z,{"data-testid":"reset-to-defaults",onClick:h,children:a("settings.configTab.resetToDefault")}),t.jsx(z,{"data-testid":"save-api-settings",type:"primary",onClick:G,children:a("settings.configTab.save")})]})]})}),t.jsx(Na,{msgApi:e})]})},{key:"tools",label:a("settings.configTab.tabs.tools"),children:t.jsx(F,{size:"small",title:t.jsx(ze,{strong:!0,children:a("settings.configTab.toolsTitle")}),children:t.jsxs(I,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[t.jsx(ze,{type:"secondary",children:a("settings.configTab.toolsDescription")}),p.length===0?t.jsx(ke,{type:"info",showIcon:!0,message:a("settings.configTab.toolsEmpty")}):t.jsx(Ke,{bordered:!0,dataSource:p,renderItem:A=>t.jsx(Ke.Item,{actions:[t.jsx(ge,{checked:!X.has(A),onChange:H=>y(A,H)},`${A}-switch`)],children:t.jsx(ze,{code:!0,children:A})})}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:o.marginSM},children:[t.jsx(z,{onClick:D,loading:j,children:a("settings.configTab.reloadTools")}),t.jsx(z,{type:"primary",onClick:_,loading:j,disabled:!O,children:a("settings.configTab.save")})]})]})})}]})})},{Title:Ba,Text:ys}=le,{useToken:Ua}=fe,Ha=()=>{const{t:e}=Z(),{token:s}=Ua(),n=Hn(),a=Kn(),o=Wn(),[r]=k.useForm(),l=$s.useRef(n);$s.useEffect(()=>{l.current!==n&&(r.setFieldsValue(n),l.current=n)},[n,r]);const m=p=>{l.current={...l.current,...p},a(p)},c=()=>{o(),r.resetFields()};return t.jsxs("div",{style:{padding:"24px",maxWidth:"1200px",margin:"0 auto"},children:[t.jsx(Ba,{level:3,style:{marginBottom:"8px"},children:e("settings.mermaidTab.title")}),t.jsx(ys,{type:"secondary",style:{display:"block",marginBottom:"24px"},children:e("settings.mermaidTab.description")}),t.jsxs(k,{form:r,layout:"vertical",initialValues:n,onValuesChange:m,children:[t.jsxs(F,{title:e("settings.mermaidTab.themeCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:[t.jsx(Ne,{gutter:16,children:t.jsx(ie,{span:24,children:t.jsx(k.Item,{name:"theme",label:t.jsxs(I,{children:[e("settings.mermaidTab.themeLabel"),t.jsx(xe,{title:e("settings.mermaidTab.themeTooltip"),children:t.jsx(Fe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsxs(ae,{children:[t.jsx(ae.Option,{value:"default",children:e("settings.mermaidTab.themeOptions.default")}),t.jsx(ae.Option,{value:"neutral",children:e("settings.mermaidTab.themeOptions.neutral")}),t.jsx(ae.Option,{value:"dark",children:e("settings.mermaidTab.themeOptions.dark")}),t.jsx(ae.Option,{value:"forest",children:e("settings.mermaidTab.themeOptions.forest")}),t.jsx(ae.Option,{value:"base",children:e("settings.mermaidTab.themeOptions.base")})]})})})}),t.jsxs(ys,{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(F,{title:e("settings.mermaidTab.globalCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:[t.jsxs(Ne,{gutter:16,children:[t.jsx(ie,{span:12,children:t.jsx(k.Item,{name:"fontSize",label:t.jsxs(I,{children:[e("settings.mermaidTab.fontSizeLabel"),t.jsx(xe,{title:e("settings.mermaidTab.fontSizeTooltip"),children:t.jsx(Fe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:10,max:32,step:1,style:{width:"100%"},addonAfter:"px"})})}),t.jsx(ie,{span:12,children:t.jsx(k.Item,{name:"defaultScale",label:t.jsxs(I,{children:[e("settings.mermaidTab.defaultZoomLabel"),t.jsx(xe,{title:e("settings.mermaidTab.defaultZoomTooltip"),children:t.jsx(Fe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:.1,max:3,step:.1,style:{width:"100%"}})})})]}),t.jsx(k.Item,{name:"useMaxWidth",label:t.jsxs(I,{children:[e("settings.mermaidTab.responsiveWidthLabel"),t.jsx(xe,{title:e("settings.mermaidTab.responsiveWidthTooltip"),children:t.jsx(Fe,{style:{color:s.colorTextSecondary}})})]}),valuePropName:"checked",children:t.jsx(ge,{})})]}),t.jsx(F,{title:e("settings.mermaidTab.flowchartCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsxs(Ne,{gutter:16,children:[t.jsx(ie,{span:8,children:t.jsx(k.Item,{name:"flowchartNodeSpacing",label:t.jsxs(I,{children:[e("settings.mermaidTab.flowchartNodeSpacingLabel"),t.jsx(xe,{title:e("settings.mermaidTab.flowchartNodeSpacingTooltip"),children:t.jsx(Fe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:20,max:200,step:10,style:{width:"100%"}})})}),t.jsx(ie,{span:8,children:t.jsx(k.Item,{name:"flowchartRankSpacing",label:t.jsxs(I,{children:[e("settings.mermaidTab.flowchartRankSpacingLabel"),t.jsx(xe,{title:e("settings.mermaidTab.flowchartRankSpacingTooltip"),children:t.jsx(Fe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:20,max:200,step:10,style:{width:"100%"}})})}),t.jsx(ie,{span:8,children:t.jsx(k.Item,{name:"flowchartCurve",label:t.jsxs(I,{children:[e("settings.mermaidTab.flowchartCurveTypeLabel"),t.jsx(xe,{title:e("settings.mermaidTab.flowchartCurveTypeTooltip"),children:t.jsx(Fe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsxs(ae,{children:[t.jsx(ae.Option,{value:"basis",children:e("settings.mermaidTab.flowchartCurveOptions.basis")}),t.jsx(ae.Option,{value:"linear",children:e("settings.mermaidTab.flowchartCurveOptions.linear")}),t.jsx(ae.Option,{value:"cardinal",children:e("settings.mermaidTab.flowchartCurveOptions.cardinal")})]})})})]})}),t.jsx(F,{title:e("settings.mermaidTab.sequenceCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsxs(Ne,{gutter:16,children:[t.jsx(ie,{span:6,children:t.jsx(k.Item,{name:"sequenceActorMargin",label:t.jsxs(I,{children:[e("settings.mermaidTab.sequenceActorMarginLabel"),t.jsx(xe,{title:e("settings.mermaidTab.sequenceActorMarginTooltip"),children:t.jsx(Fe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:20,max:200,step:10,style:{width:"100%"}})})}),t.jsx(ie,{span:6,children:t.jsx(k.Item,{name:"sequenceMessageMargin",label:t.jsxs(I,{children:[e("settings.mermaidTab.sequenceMessageMarginLabel"),t.jsx(xe,{title:e("settings.mermaidTab.sequenceMessageMarginTooltip"),children:t.jsx(Fe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:10,max:100,step:5,style:{width:"100%"}})})}),t.jsx(ie,{span:6,children:t.jsx(k.Item,{name:"sequenceWidth",label:t.jsxs(I,{children:[e("settings.mermaidTab.sequenceActorWidthLabel"),t.jsx(xe,{title:e("settings.mermaidTab.sequenceActorWidthTooltip"),children:t.jsx(Fe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:100,max:300,step:10,style:{width:"100%"}})})}),t.jsx(ie,{span:6,children:t.jsx(k.Item,{name:"sequenceHeight",label:t.jsxs(I,{children:[e("settings.mermaidTab.sequenceActorHeightLabel"),t.jsx(xe,{title:e("settings.mermaidTab.sequenceActorHeightTooltip"),children:t.jsx(Fe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:40,max:150,step:5,style:{width:"100%"}})})})]})}),t.jsx(F,{title:e("settings.mermaidTab.ganttCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsxs(Ne,{gutter:16,children:[t.jsx(ie,{span:12,children:t.jsx(k.Item,{name:"ganttBarHeight",label:t.jsxs(I,{children:[e("settings.mermaidTab.ganttBarHeightLabel"),t.jsx(xe,{title:e("settings.mermaidTab.ganttBarHeightTooltip"),children:t.jsx(Fe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:10,max:50,step:5,style:{width:"100%"},addonAfter:"px"})})}),t.jsx(ie,{span:12,children:t.jsx(k.Item,{name:"ganttTopPadding",label:t.jsxs(I,{children:[e("settings.mermaidTab.ganttTopPaddingLabel"),t.jsx(xe,{title:e("settings.mermaidTab.ganttTopPaddingTooltip"),children:t.jsx(Fe,{style:{color:s.colorTextSecondary}})})]}),children:t.jsx(he,{min:20,max:100,step:10,style:{width:"100%"}})})})]})}),t.jsx(I,{children:t.jsx(z,{icon:t.jsx(da,{}),onClick:c,children:e("settings.mermaidTab.resetToDefaults")})}),t.jsx(Pe,{}),t.jsx(F,{title:e("settings.mermaidTab.previewTitle"),styles:{header:{backgroundColor:s.colorBgElevated}},children:t.jsx(ys,{type:"secondary",children:e("settings.mermaidTab.previewDescription")})})]})]})},Ka=i.lazy(()=>Es(()=>import("./index-DCmbOzco.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8]),import.meta.url)),{Text:ct}=le,{useToken:Wa}=fe,Ga=({promptEnhancement:e,onPromptEnhancementChange:s,mermaidEnhancementEnabled:n,taskEnhancementEnabled:a,showCopilotConclusionWithOptionsEnhancement:o,copilotConclusionWithOptionsEnhancementEnabled:r,onMermaidToggle:l,onTaskToggle:m,onCopilotConclusionWithOptionsToggle:c,onSaveEnhancement:p})=>{const{t:d}=Z(),{token:b}=Wa(),f=b.marginLG;return t.jsxs($,{vertical:!0,gap:f,children:[t.jsx(F,{size:"small",className:"lotus-settings-card",children:t.jsx(i.Suspense,{fallback:t.jsx(Bt,{size:"small"}),children:t.jsx(Ka,{})})}),t.jsx(F,{size:"small",className:"lotus-settings-card",children:t.jsxs(I,{direction:"vertical",size:b.marginXS,style:{width:"100%"},children:[t.jsx(ct,{strong:!0,children:d("settings.promptsTab.title")}),t.jsxs($,{align:"center",gap:b.marginSM,children:[t.jsx(ct,{strong:!0,children:d("settings.promptsTab.mermaidEnhancement")}),t.jsx(ge,{checked:n,onChange:l})]}),t.jsxs($,{align:"center",gap:b.marginSM,children:[t.jsx(ct,{strong:!0,children:d("settings.promptsTab.taskListRules")}),t.jsx(ge,{checked:a,onChange:m})]}),o&&t.jsxs(I,{direction:"vertical",size:b.marginXXS,style:{width:"100%"},children:[t.jsxs($,{align:"center",gap:b.marginSM,children:[t.jsx(ct,{strong:!0,children:d("settings.promptsTab.copilotConclusionWithOptionsBeforeFinish")}),t.jsx(ge,{checked:r,onChange:c})]}),t.jsx(ct,{type:"secondary",style:{fontSize:b.fontSizeSM},children:d("settings.promptsTab.copilotConclusionWithOptionsBeforeFinishDescription",{defaultValue:Gn()})})]}),t.jsx(U.TextArea,{rows:6,placeholder:d("settings.promptsTab.enhancementPlaceholder"),value:e,onChange:v=>s(v.target.value)}),t.jsx($,{justify:"flex-end",children:t.jsx(z,{type:"primary",onClick:p,children:d("settings.promptsTab.saveEnhancement")})}),t.jsx(ct,{type:"secondary",style:{fontSize:b.fontSizeSM},children:d("settings.promptsTab.description")})]})}),n&&t.jsx(Fs,{size:"small",items:[{key:"mermaid",label:t.jsx(ct,{strong:!0,children:d("settings.mermaidTab.title")}),children:t.jsx(Ha,{})}]})]})},{Text:nt}=le,{useToken:Ja}=fe,Xa=({themeMode:e,onThemeModeChange:s,vdiSafeMode:n,onVdiSafeModeToggle:a,onClearLocalStorage:o,onResetApp:r,isResetting:l,darkModeKey:m})=>{const{t:c}=Z(),{token:p}=Ja();return t.jsx(F,{size:"small",className:"lotus-settings-card",children:t.jsxs(I,{direction:"vertical",size:p.marginSM,style:{width:"100%"},children:[t.jsxs($,{align:"center",justify:"space-between",gap:p.marginSM,children:[t.jsx(nt,{strong:!0,children:c("settings.appTab.runningVersion","Running version")}),t.jsxs(nt,{code:!0,"data-testid":"settings-app-version",children:["v",wn]})]}),t.jsx(nt,{type:"secondary",style:{fontSize:p.fontSizeSM},children:c("settings.appTab.runningVersionDesc","This is the currently running Lotus frontend version.")}),t.jsxs($,{align:"center",gap:p.marginSM,children:[t.jsx(nt,{strong:!0,children:c("settings.appTab.darkMode")}),t.jsx(ge,{"data-testid":"dark-mode-toggle",checked:e==="dark",onChange:d=>{const b=d?"dark":"light";s(b),localStorage.setItem(m,b)}})]}),t.jsxs($,{align:"center",gap:p.marginSM,children:[t.jsx(nt,{strong:!0,children:c("settings.appTab.vdiSafeMode","Graphics compatibility mode")}),t.jsx(ge,{"data-testid":"vdi-safe-mode-toggle",checked:n,onChange:a})]}),t.jsx(nt,{type:"secondary",style:{fontSize:p.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(z,{block:!0,icon:t.jsx(ua,{}),onClick:()=>{wa(),window.location.reload()},children:c("settings.appTab.resetStepReplayGuide")}),t.jsx(cs,{title:c("settings.appTab.clearLocalStorageTitle"),description:c("settings.appTab.clearLocalStorageDescription"),onConfirm:o,okText:c("settings.appTab.confirmClear"),cancelText:c("settings.appTab.cancel"),placement:"top",children:t.jsx(z,{danger:!0,block:!0,icon:t.jsx(gs,{}),children:c("settings.appTab.clearLocalStorageButton")})}),t.jsx(Pe,{style:{margin:`${p.marginSM}px 0`}}),t.jsxs($,{align:"center",gap:p.marginSM,children:[t.jsx(ga,{style:{color:p.colorError}}),t.jsx(nt,{strong:!0,style:{color:p.colorError},children:c("settings.appTab.dangerZone")})]}),t.jsx(nt,{type:"secondary",style:{fontSize:p.fontSizeSM},children:c("settings.appTab.dangerDescription")}),t.jsx(cs,{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:r,okText:c("settings.appTab.resetConfirm"),cancelText:c("settings.appTab.cancel"),placement:"top",okButtonProps:{danger:!0},children:t.jsx(z,{"data-testid":"reset-to-defaults",danger:!0,block:!0,type:"primary",icon:t.jsx(ma,{}),loading:l,children:c("settings.appTab.resetButton")})})]})})},{Text:dt}=le,{useToken:Ya}=fe,Qs=[{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,}"}],Za=(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:te.t("settings.keywordMaskingTab.invalidRegexPattern")}}},Qa=()=>{const{t:e}=Z(),{message:s}=Wt.useApp(),{token:n}=Ya(),[a,o]=i.useState([]),[r,l]=i.useState(!1),[m,c]=i.useState(null),[p,d]=i.useState(""),[b,f]=i.useState("exact"),[v,T]=i.useState(!0),[u,M]=i.useState(),[j,x]=i.useState("My token is sk-123"),E=i.useCallback(async()=>{try{l(!0);const _=await qt.getInstance().getKeywordMaskingConfig();o(_.entries)}catch(D){s.error(e("settings.keywordMaskingTab.loadFailed")),console.error(D)}finally{l(!1)}},[e]);i.useEffect(()=>{E()},[E]);const S=async D=>{try{const _=qt.getInstance(),O=await _.validateKeywordEntries(D);if(!O.valid&&O.errors){const A=O.errors.map(H=>`Entry ${H.index+1}: ${H.message}`).join("; ");return s.error(`${e("settings.keywordMaskingTab.validationFailedPrefix")}: ${A}`),!1}const X=await _.updateKeywordMaskingConfig(D);return o(X.entries),s.success(e("settings.keywordMaskingTab.saveSuccess")),!0}catch(_){return s.error(_ instanceof Error?_.message:e("settings.keywordMaskingTab.saveFailed")),!1}},P=async()=>{const D={pattern:"",match_type:"exact",enabled:!0},_=[...a,D];o(_),c(_.length-1),d(""),f("exact"),T(!0),M(void 0)},ee=D=>{const _=a[D];c(D),d(_.pattern),f(_.match_type),T(_.enabled),M(void 0)},R=async()=>{if(m===null)return;if(!p.trim()){s.error(e("settings.keywordMaskingTab.patternRequired"));return}const D=[...a];D[m]={pattern:p.trim(),match_type:b,enabled:v},await S(D)&&c(null)},q=()=>{var D;m!==null&&!((D=a[m])!=null&&D.pattern)&&o(a.filter((_,O)=>O!==m)),c(null)},G=async D=>{const _=a.filter((O,X)=>X!==D);await S(_)},h=async(D,_)=>{const O=[...a];O[D]={...O[D],enabled:_},await S(O)},y=Za(j,p,b);return t.jsx(F,{className:"lotus-settings-card",title:e("settings.keywordMaskingTab.title"),extra:t.jsx(z,{"data-testid":"add-keyword",type:"primary",icon:t.jsx(Ut,{}),onClick:P,loading:r,children:e("settings.keywordMaskingTab.addKeyword")}),children:t.jsxs(I,{direction:"vertical",style:{width:"100%"},size:"large",children:[t.jsx(dt,{type:"secondary",children:e("settings.keywordMaskingTab.description")}),t.jsx(Ke,{loading:r,dataSource:a,locale:{emptyText:e("settings.keywordMaskingTab.empty")},renderItem:(D,_)=>t.jsx(Ke.Item,{style:{backgroundColor:n.colorFillAlter,marginBottom:8,borderRadius:n.borderRadius,padding:12},actions:m===_?[t.jsx(z,{"data-testid":"save-keyword",type:"primary",icon:t.jsx(ms,{}),onClick:R,"aria-label":e("settings.keywordMaskingTab.save")},"save"),t.jsx(z,{onClick:q,children:e("settings.keywordMaskingTab.cancel")},"cancel")]:[t.jsx(z,{icon:t.jsx(Rs,{}),onClick:()=>ee(_),"aria-label":e("settings.keywordMaskingTab.edit")},"edit"),t.jsx(z,{"data-testid":`delete-keyword-${_}`,danger:!0,icon:t.jsx(gs,{}),onClick:()=>G(_),"aria-label":e("settings.keywordMaskingTab.delete")},"delete")],children:t.jsx($,{vertical:!0,style:{width:"100%"},gap:8,children:m===_?t.jsxs(t.Fragment,{children:[t.jsx(U,{"data-testid":"keyword-pattern-input",placeholder:e("settings.keywordMaskingTab.patternPlaceholder"),value:p,onChange:O=>d(O.target.value),autoFocus:!0}),t.jsxs($,{gap:8,align:"center",wrap:"wrap",children:[t.jsx(ae,{"data-testid":"keyword-examples-select","aria-label":e("settings.keywordMaskingTab.examples"),placeholder:e("settings.keywordMaskingTab.examples"),value:u,onChange:O=>{M(O);const X=Qs.find(A=>A.value===O);X&&(d(X.pattern),f(X.match_type))},options:Qs.map(O=>({value:O.value,label:e(O.labelKey)})),style:{minWidth:220}}),t.jsx(ae,{value:b,onChange:f,options:[{value:"exact",label:e("settings.keywordMaskingTab.exactMatch")},{value:"regex",label:e("settings.keywordMaskingTab.regexPattern")}],style:{width:150}}),t.jsx(ge,{checked:v,onChange:T})]}),t.jsxs($,{vertical:!0,gap:6,children:[t.jsx(dt,{type:"secondary",children:e("settings.keywordMaskingTab.sampleText")}),t.jsx(U,{placeholder:e("settings.keywordMaskingTab.sampleTextPlaceholder"),value:j,onChange:O=>x(O.target.value)}),t.jsx(dt,{type:"secondary",children:e("settings.keywordMaskingTab.maskedPreview")}),t.jsx(U,{readOnly:!0,value:y.masked,status:y.error?"error":void 0}),y.error&&t.jsx(dt,{type:"danger",children:y.error})]})]}):t.jsxs($,{justify:"space-between",align:"center",children:[t.jsxs($,{vertical:!0,gap:4,children:[t.jsx(dt,{strong:!0,children:D.pattern||e("settings.keywordMaskingTab.emptyPattern")}),t.jsxs($,{gap:8,children:[t.jsx(dt,{type:"secondary",style:{fontSize:12},children:D.match_type==="regex"?e("settings.keywordMaskingTab.regexPattern"):e("settings.keywordMaskingTab.exactMatch")}),!D.enabled&&t.jsx(dt,{type:"warning",style:{fontSize:12},children:e("settings.keywordMaskingTab.disabled")})]})]}),t.jsx(ge,{checked:D.enabled,onChange:O=>h(_,O),size:"small"})]})})})})]})})},{Text:yt,Paragraph:er}=le,tr=/^[A-Za-z_][A-Za-z0-9_]*$/,sr=()=>{const{t:e}=Z(),{message:s}=Wt.useApp(),[n,a]=i.useState([]),[o,r]=i.useState(!1),[l,m]=i.useState(!1),[c,p]=i.useState(null),[d]=k.useForm(),b=i.useCallback(async()=>{r(!0);try{const x=await $e.getEnvVars();a(x.entries)}catch{s.error(e("settings.envVars.fetchError","Failed to load environment variables"))}finally{r(!1)}},[e]);i.useEffect(()=>{b()},[b]);const f=async x=>{var S;const E={name:x.name.trim(),value:x.value,secret:x.secret??!1,description:((S=x.description)==null?void 0:S.trim())||void 0};try{const P=await $e.upsertEnvVar(E);a(P.entries),s.success(c?e("settings.envVars.updated","Variable updated"):e("settings.envVars.created","Variable created")),M()}catch(P){s.error((P instanceof Error?P.message:void 0)||e("settings.envVars.saveError","Failed to save variable"))}},v=async x=>{try{const E=await $e.deleteEnvVar(x);a(E.entries),s.success(e("settings.envVars.deleted","Variable deleted"))}catch(E){s.error((E instanceof Error?E.message:void 0)||e("settings.envVars.deleteError","Failed to delete variable"))}},T=()=>{p(null),d.resetFields(),d.setFieldsValue({secret:!1}),m(!0)},u=x=>{p(x.name),d.setFieldsValue({name:x.name,value:"",secret:x.secret,description:x.description??""}),m(!0)},M=()=>{m(!1),p(null),d.resetFields()},j=[{title:e("settings.envVars.name","Name"),dataIndex:"name",key:"name",render:x=>t.jsx(yt,{code:!0,children:x})},{title:e("settings.envVars.value","Value"),dataIndex:"value",key:"value",render:(x,E)=>E.secret?t.jsxs(yt,{type:"secondary",children:[t.jsx(Gs,{style:{marginRight:4}}),E.has_value?"••••••••":e("settings.envVars.notSet","(not set)")]}):t.jsx(yt,{children:x||t.jsx(yt,{type:"secondary",children:e("settings.envVars.empty","(empty)")})})},{title:e("settings.envVars.type","Type"),key:"secret",width:100,render:(x,E)=>E.secret?t.jsx(ue,{color:"warning",icon:t.jsx(Gs,{}),children:e("settings.envVars.secret","Secret")}):t.jsx(ue,{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(yt,{type:"secondary",children:x}):t.jsx(yt,{type:"secondary",italic:!0,children:"—"})},{title:e("settings.envVars.actions","Actions"),key:"actions",width:120,render:(x,E)=>t.jsxs(I,{size:"small",children:[t.jsx(z,{type:"text",size:"small",icon:t.jsx(Rs,{}),onClick:()=>u(E),"aria-label":e("settings.envVars.edit","Edit")}),t.jsx(cs,{title:e("settings.envVars.deleteConfirm","Delete this variable?"),onConfirm:()=>v(E.name),okText:e("settings.envVars.yes","Yes"),cancelText:e("settings.envVars.no","No"),children:t.jsx(z,{type:"text",size:"small",danger:!0,icon:t.jsx(gs,{}),"aria-label":e("settings.envVars.delete","Delete")})})]})}];return t.jsxs("div",{style:{maxWidth:900},children:[t.jsxs(F,{className:"lotus-settings-card",title:e("settings.envVars.title","Environment Variables"),extra:t.jsx(z,{type:"primary",icon:t.jsx(Ut,{}),onClick:T,children:e("settings.envVars.addButton","Add Variable")}),children:[t.jsx(er,{type:"secondary",style:{marginBottom:16},children:e("settings.envVars.description","Variables are injected into Bash tool processes. Secret variables are encrypted at rest.")}),t.jsx(et,{dataSource:n,columns:j,rowKey:"name",size:"small",pagination:!1,loading:o,locale:{emptyText:e("settings.envVars.noVars","No environment variables configured")}})]}),t.jsx(ot,{title:c?e("settings.envVars.editTitle","Edit Variable"):e("settings.envVars.addTitle","Add Environment Variable"),open:l,onCancel:M,onOk:()=>d.submit(),okText:e("settings.envVars.save","Save"),cancelText:e("settings.envVars.cancel","Cancel"),destroyOnClose:!0,children:t.jsxs(k,{form:d,layout:"vertical",onFinish:f,initialValues:{secret:!1},children:[t.jsx(k.Item,{name:"name",label:e("settings.envVars.name","Name"),rules:[{required:!0,message:e("settings.envVars.nameRequired","Variable name is required")},{pattern:tr,message:e("settings.envVars.nameInvalid","Must start with a letter or underscore, followed by letters, digits, or underscores")}],children:t.jsx(U,{placeholder:"GITHUB_TOKEN",disabled:c!==null,autoFocus:c===null})}),t.jsx(k.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(U.Password,{placeholder:c?e("settings.envVars.valuePlaceholderEdit","Enter new value or leave empty"):e("settings.envVars.valuePlaceholder","Enter value"),visibilityToggle:!0})}),t.jsx(k.Item,{name:"secret",label:e("settings.envVars.secret","Secret"),valuePropName:"checked",extra:e("settings.envVars.secretHint","Secret variables are encrypted on disk and masked in the UI"),children:t.jsx(ge,{})}),t.jsx(k.Item,{name:"description",label:e("settings.envVars.descriptionField","Description"),children:t.jsx(U,{placeholder:e("settings.envVars.descriptionPlaceholder","Optional description")})})]})})]})},ht=class ht{constructor(){}static getInstance(){return ht.instance||(ht.instance=new ht),ht.instance}async listWorkflows(){try{rt("[WorkflowManager]","[WorkflowManagerService] Listing workflows");const s=await qs.get("bamboo/workflows"),n=Array.isArray(s)?s:[];return rt("[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{rt("[WorkflowManager]","[WorkflowManagerService] Getting workflow: "+s);const n=await qs.get("bamboo/workflows/"+encodeURIComponent(s)),a=n!=null&&n.name?String(n.name):s,o={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 rt("[WorkflowManager]","[WorkflowManagerService] Got workflow:",n),{name:a,content:String((n==null?void 0:n.content)||""),metadata:o}}catch(n){throw console.error("[WorkflowManagerService] Failed to get workflow "+s+":",n),Da(n)&&n.status===404?new Error("Workflow '"+s+"' not found"):n instanceof Error&&n.message.includes("404")?new Error("Workflow '"+s+"' not found"):n}}};Vs(ht,"instance");let Ds=ht;const{Text:xs}=le,{TextArea:nr}=U,{useToken:ar}=fe,rr=e=>!(!e||e.includes("/")||e.includes("\\")||e.includes("..")),or=()=>{const{t:e}=Z(),{token:s}=ar(),[n,a]=Tt.useMessage(),[o,r]=i.useState([]),[l,m]=i.useState(!1),[c,p]=i.useState(!1),[d,b]=i.useState(!1),[f,v]=i.useState(null),[T,u]=i.useState(""),[M,j]=i.useState(""),[x,E]=i.useState(!1),S=i.useMemo(()=>Ds.getInstance(),[]),P=i.useCallback(async()=>{m(!0);try{const h=await S.listWorkflows();return r(h),h}catch{return n.error(e("settings.workflowsTab.loadFailed")),[]}finally{m(!1)}},[n,e,S]);i.useEffect(()=>{P()},[P]);const ee=i.useCallback(async h=>{v(h),u(h.name),E(!1),p(!0);try{const y=await S.getWorkflow(h.name);j(y.content??"")}catch{n.error(e("settings.workflowsTab.loadContentFailed")),j("")}finally{p(!1)}},[n,e,S]),R=()=>{v(null),u(""),j(""),E(!1)},q=i.useCallback(async()=>{if(!rr(T)){n.error(e("settings.workflowsTab.invalidName"));return}const h=o.some(y=>y.name===T);if(!f&&h){n.error(e("settings.workflowsTab.nameAlreadyExists"));return}b(!0);try{await qt.getInstance().saveWorkflow(T,M),n.success(e("settings.workflowsTab.saved")),E(!1);const _=(await P()).find(O=>O.name===T);_&&v(_)}catch(y){n.error(y instanceof Error?y.message:e("settings.workflowsTab.saveFailed"))}finally{b(!1)}},[M,T,P,n,f,e,o]),G=i.useCallback(async h=>{try{await qt.getInstance().deleteWorkflow(h.name),n.success(e("settings.workflowsTab.deleted")),(f==null?void 0:f.name)===h.name&&R(),await P()}catch(y){n.error(y instanceof Error?y.message:e("settings.workflowsTab.deleteFailed"))}},[P,n,f,e]);return t.jsxs("div",{style:{padding:"24px"},children:[a,t.jsxs(F,{title:e("settings.workflowsTab.title"),extra:t.jsxs(I,{children:[t.jsx(z,{icon:t.jsx(jt,{}),onClick:P,loading:l,children:e("settings.workflowsTab.refresh")}),t.jsx(z,{"data-testid":"create-workflow",icon:t.jsx(Ut,{}),onClick:R,children:e("settings.workflowsTab.newWorkflow")}),t.jsx(z,{"data-testid":"save-workflow",type:"primary",icon:t.jsx(ms,{}),onClick:q,loading:d,disabled:!x,children:e("settings.workflowsTab.save")})]}),children:[t.jsx(xs,{type:"secondary",children:e("settings.workflowsTab.description")}),t.jsxs($,{gap:s.marginLG,style:{marginTop:s.marginLG},children:[t.jsx("div",{style:{width:320,flexShrink:0},children:t.jsx(Ke,{loading:l,dataSource:o,locale:{emptyText:e("settings.workflowsTab.empty")},renderItem:h=>t.jsx(Ke.Item,{style:{cursor:"pointer",backgroundColor:(f==null?void 0:f.name)===h.name?s.colorFillSecondary:"transparent",borderRadius:s.borderRadius,padding:s.paddingSM},onClick:()=>ee(h),actions:[t.jsx(z,{"data-testid":`delete-workflow-${h.name}`,type:"text",danger:!0,size:"small",icon:t.jsx(gs,{}),onClick:y=>{y.stopPropagation(),G(h)},"aria-label":e("settings.workflowsTab.delete")},"delete")],children:t.jsxs(I,{direction:"vertical",size:0,children:[t.jsxs(xs,{strong:!0,children:["/",h.name]}),t.jsx(xs,{type:"secondary",style:{fontSize:12},children:h.filename})]})})})}),t.jsx("div",{style:{flex:1},children:t.jsxs(I,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(U,{"data-testid":"workflow-name",placeholder:e("settings.workflowsTab.namePlaceholder"),value:T,onChange:h=>{u(h.target.value),E(!0)},disabled:!!f,prefix:t.jsx(Rs,{})}),t.jsx(nr,{"data-testid":"workflow-content",placeholder:e("settings.workflowsTab.contentPlaceholder"),value:M,onChange:h=>{j(h.target.value),E(!0)},autoSize:{minRows:12},disabled:c})]})})]})]})]})};var N=(e=>(e.Connecting="connecting",e.Ready="ready",e.Degraded="degraded",e.Stopped="stopped",e.Error="error",e))(N||{});const Yt=6e4,Zt=3e4,Ht=2e4,us=1e4,ps=e=>({id:e,enabled:!0,transport:{type:"stdio",command:"",args:[],env:{},startup_timeout_ms:Ht},request_timeout_ms:Yt,healthcheck_interval_ms:Zt,allowed_tools:[],denied_tools:[]}),ir=()=>({status:"stopped",tool_count:0,restart_count:0}),lr=e=>{switch(typeof e=="string"?e.trim().toLowerCase():""){case N.Connecting:return N.Connecting;case N.Ready:return N.Ready;case N.Degraded:return N.Degraded;case N.Error:return N.Error;case N.Stopped:default:return N.Stopped}},Ze=(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},cr=(e,s)=>{if(!e||typeof e!="object")return s;const n=e;if(n.type==="sse"){const r=Array.isArray(n.headers)?n.headers.map(l=>{if(!l||typeof l!="object")return null;const m=l;return typeof m.name!="string"||typeof m.value!="string"?null:{name:m.name,value:m.value}}).filter(l=>!!l):[];return{type:"sse",url:typeof n.url=="string"?n.url:"",headers:r,connect_timeout_ms:Ze(n.connect_timeout_ms,us)}}const a=Array.isArray(n.args)?n.args.filter(r=>typeof r=="string"):[],o=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:o.reduce((r,[l,m])=>(typeof m=="string"&&(r[l]=m),r),{}),startup_timeout_ms:Ze(n.startup_timeout_ms,Ht)}},dr=(e,s)=>{const n=ps(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:Ze(a.request_timeout_ms,Yt),healthcheck_interval_ms:Ze(a.healthcheck_interval_ms,Zt),allowed_tools:Array.isArray(a.allowed_tools)?a.allowed_tools.filter(r=>typeof r=="string"):[],denied_tools:Array.isArray(a.denied_tools)?a.denied_tools.filter(r=>typeof r=="string"):[],reconnect:a.reconnect&&typeof a.reconnect=="object"?{enabled:typeof a.reconnect.enabled=="boolean"?a.reconnect.enabled:!0,initial_backoff_ms:Ze(a.reconnect.initial_backoff_ms,1e3),max_backoff_ms:Ze(a.reconnect.max_backoff_ms,3e4),max_attempts:Ze(a.reconnect.max_attempts,0)}:void 0,transport:cr(a.transport,n.transport)}},ur=e=>{const s=ir(),a=e.runtime??{},o=a.status??e.status;return{status:lr(o),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:Ze(a.tool_count??e.tool_count,s.tool_count),restart_count:Ze(a.restart_count??e.restart_count,s.restart_count),last_ping_at:typeof a.last_ping_at=="string"?a.last_ping_at:void 0}},gr=e=>{const s=dr(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:ur(e)}},mr=(e,s)=>`mcp__${e}__${s}`,pr=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),o=s.slice(n+2);return!a||!o?null:{server_id:a,original_name:o}},hr=(e,s,n=0)=>{if(!e||typeof e!="object")return null;const a=e,o=typeof a.alias=="string"?a.alias:typeof a.name=="string"&&a.name.startsWith("mcp__")?a.name:void 0,r=o&&typeof o=="string"?pr(o):null,l=(typeof a.server_id=="string"?a.server_id:void 0)??(typeof a.serverId=="string"?a.serverId:void 0)??(r==null?void 0:r.server_id)??s??"",m=(typeof a.original_name=="string"?a.original_name:void 0)??(typeof a.originalName=="string"?a.originalName:void 0)??(r==null?void 0:r.original_name)??(typeof a.name=="string"?a.name:void 0)??"",c=o??(l&&m?mr(l,m):""),p=typeof a.description=="string"?a.description:"",d=a,b="parameters"in d?d.parameters:"inputSchema"in d?d.inputSchema:"input_schema"in d?d.input_schema:void 0,f=c||m||`mcp_tool_${n}`;return{alias:f,server_id:l||"unknown",original_name:m||f,description:p,parameters:b}};class fr{async getServers(){const s=await Ge.get("mcp/servers");return Array.isArray(s.servers)?s.servers.map(gr):[]}async addServer(s){return Ge.post("mcp/servers",s)}async updateServer(s,n){const a={...n,id:s};return Ge.put(`mcp/servers/${s}`,a)}async deleteServer(s){return Ge.delete(`mcp/servers/${s}`)}async connectServer(s){return Ge.post(`mcp/servers/${s}/connect`)}async disconnectServer(s){return Ge.post(`mcp/servers/${s}/disconnect`)}async refreshTools(s){return Ge.post(`mcp/servers/${s}/refresh`)}async getTools(s){const n=s?`mcp/servers/${s}/tools`:"mcp/tools",a=await Ge.get(n);return(Array.isArray(a.tools)?a.tools:[]).map((r,l)=>hr(r,s,l)).filter(r=>!!r)}async importServers(s){return Ge.post("mcp/servers/import",s)}}const Pn=new fr,yr=5e3,Je=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,en=(e,s)=>`${e}:${s}`,xr=(e={})=>{const{service:s=Pn,autoRefreshMs:n=yr,autoRefreshEnabled:a=!0}=e,[o,r]=i.useState([]),[l,m]=i.useState(null),[c,p]=i.useState({}),[d,b]=i.useState({}),[f,v]=i.useState({}),[T,u]=i.useState(!1),[M,j]=i.useState(!1),[x,E]=i.useState(!1),[S,P]=i.useState(null),ee=i.useRef({}),R=i.useCallback(L=>{const W=new Set(L.map(se=>se.id)),Q=L.map(se=>{const qe=ee.current[se.id]??se.config,Ie={...qe,id:se.id,name:qe.name??se.name};return ee.current[se.id]=Ie,{...se,name:se.name||Ie.name||se.id,enabled:se.enabled??Ie.enabled,config:Ie}});return Object.keys(ee.current).forEach(se=>{W.has(se)||delete ee.current[se]}),Q},[]),q=i.useCallback(async({silent:L=!1}={})=>{L||u(!0);try{const W=await s.getServers(),Q=R(W);r(Q),m(se=>{var we;return se&&Q.some(qe=>qe.id===se)?se:((we=Q[0])==null?void 0:we.id)??null}),P(null)}catch(W){throw P(Je(W,"Failed to load MCP servers")),W}finally{L||u(!1)}},[R,s]),G=i.useCallback(async(L,W=!1)=>{if(!L)return[];if(!W&&c[L])return c[L];b(Q=>({...Q,[L]:!0}));try{const Q=await s.getTools(L);return p(se=>({...se,[L]:Q})),P(null),Q}catch(Q){throw P(Je(Q,"Failed to load MCP tools")),Q}finally{b(Q=>({...Q,[L]:!1}))}},[s,c]),h=i.useCallback((L,W,Q)=>{const se=en(L,W);v(we=>({...we,[se]:Q}))},[]),y=i.useCallback(async L=>{j(!0);try{await s.addServer(L),ee.current[L.id]=L,await q()}catch(W){throw P(Je(W,"Failed to add MCP server")),W}finally{j(!1)}},[q,s]),D=i.useCallback(async(L,W)=>{j(!0);try{const Q={...W,id:L};await s.updateServer(L,Q),ee.current[L]=Q,await q()}catch(Q){throw P(Je(Q,"Failed to update MCP server")),Q}finally{j(!1)}},[q,s]),_=i.useCallback(async L=>{h(L,"delete",!0);try{await s.deleteServer(L),p(W=>{const Q={...W};return delete Q[L],Q}),delete ee.current[L],await q()}catch(W){throw P(Je(W,"Failed to delete MCP server")),W}finally{h(L,"delete",!1)}},[q,s,h]),O=i.useCallback(async L=>{h(L,"connect",!0);try{await s.connectServer(L),await q({silent:!0})}catch(W){throw P(Je(W,"Failed to connect MCP server")),W}finally{h(L,"connect",!1)}},[q,s,h]),X=i.useCallback(async L=>{h(L,"disconnect",!0);try{await s.disconnectServer(L),await q({silent:!0})}catch(W){throw P(Je(W,"Failed to disconnect MCP server")),W}finally{h(L,"disconnect",!1)}},[q,s,h]),A=i.useCallback(async L=>{h(L,"refresh",!0);try{await s.refreshTools(L),await G(L,!0),await q({silent:!0})}catch(W){throw P(Je(W,"Failed to refresh MCP tools")),W}finally{h(L,"refresh",!1)}},[G,q,s,h]),H=i.useCallback(async()=>{E(!0);try{const L=o.map(W=>W.id);await Promise.all(L.map(async W=>{try{await s.refreshTools(W)}catch{}})),await q(),l&&await G(l,!0)}catch(L){throw P(Je(L,"Failed to refresh MCP status")),L}finally{E(!1)}},[G,q,l,o,s]),V=i.useCallback(L=>{m(L)},[]),oe=i.useCallback((L,W)=>!!f[en(L,W)],[f]),ce=i.useMemo(()=>l?c[l]??[]:[],[l,c]),K=i.useMemo(()=>l?!!d[l]:!1,[l,d]);return i.useEffect(()=>{q().catch(()=>{})},[q]),i.useEffect(()=>{if(!a||n<=0)return;const L=window.setInterval(()=>{q({silent:!0}).catch(()=>{})},n);return()=>{window.clearInterval(L)}},[a,n,q]),i.useEffect(()=>{l&&G(l).catch(()=>{})},[G,l]),{servers:o,selectedServerId:l,selectedServerTools:ce,isLoadingServers:T,isMutatingConfig:M,isRefreshingAll:x,isSelectedServerToolsLoading:K,error:S,setSelectedServerId:V,refreshServers:q,addServer:y,updateServer:D,deleteServer:_,connectServer:O,disconnectServer:X,refreshServerTools:A,refreshAll:H,isServerActionLoading:oe}},br={[N.Connecting]:"blue",[N.Ready]:"green",[N.Degraded]:"orange",[N.Stopped]:"default",[N.Error]:"red"},vr=e=>e===N.Connecting||e===N.Ready||e===N.Degraded,Tr=e=>{if(!e)return;const s=e.replace(/\s+/g," ").trim();if(s)return s.length>180?`${s.slice(0,180)}...`:s},jr=({servers:e,loading:s=!1,selectedServerId:n,onSelectServer:a,onEditServer:o,onDeleteServer:r,onConnectServer:l,onDisconnectServer:m,onRefreshTools:c,isServerActionLoading:p})=>{const{t:d}=Z(),{token:b}=fe.useToken(),f=i.useMemo(()=>({[N.Connecting]:d("settings.mcpTab.statusHelp.connecting"),[N.Ready]:d("settings.mcpTab.statusHelp.ready"),[N.Degraded]:d("settings.mcpTab.statusHelp.degraded"),[N.Stopped]:d("settings.mcpTab.statusHelp.stopped"),[N.Error]:d("settings.mcpTab.statusHelp.error")}),[d]),v=i.useMemo(()=>[{key:"name",title:d("settings.mcpServerTable.columns.name"),render:(T,u)=>u.name||u.id},{key:"transport",title:d("settings.mcpServerTable.columns.transportType"),render:(T,u)=>u.config.transport.type==="sse"?d("settings.mcpServerTable.transportOptions.sse"):d("settings.mcpServerTable.transportOptions.stdio"),width:140},{key:"status",title:d("settings.mcpServerTable.columns.status"),render:(T,u)=>{var S,P;const M=((S=u.runtime)==null?void 0:S.status)??N.Stopped,j=Tr((P=u.runtime)==null?void 0:P.last_error),x=f[M],E={[N.Connecting]:d("settings.mcpTab.status.connecting"),[N.Ready]:d("settings.mcpTab.status.ready"),[N.Degraded]:d("settings.mcpTab.status.degraded"),[N.Stopped]:d("settings.mcpTab.status.stopped"),[N.Error]:d("settings.mcpTab.status.error")};return t.jsx(xe,{title:j?`${x} ${d("settings.mcpTab.statusLastError",{error:j})}`:x,children:t.jsx(ue,{color:M===N.Stopped?void 0:br[M],style:{marginInlineEnd:0,cursor:"help",...M===N.Stopped?{background:b.colorFillSecondary,borderColor:b.colorBorderSecondary,color:b.colorTextSecondary}:void 0},children:E[M]})})},width:120},{key:"toolCount",title:d("settings.mcpServerTable.columns.toolCount"),render:(T,u)=>{var M;return((M=u.runtime)==null?void 0:M.tool_count)??0},width:100},{key:"actions",title:d("settings.mcpServerTable.columns.actions"),width:360,render:(T,u)=>{var x;const M=((x=u.runtime)==null?void 0:x.status)??N.Stopped,j=vr(M);return t.jsxs(I,{size:b.marginXS,children:[t.jsx(z,{size:"small",onClick:E=>{E.stopPropagation(),o==null||o(u)},children:d("settings.mcpServerTable.actions.edit")}),t.jsx(cs,{title:d("settings.mcpServerTable.deleteTitle"),description:d("settings.mcpServerTable.deleteDescription",{name:u.name||u.id}),onConfirm:()=>r==null?void 0:r(u),okText:d("settings.mcpServerTable.actions.delete"),okButtonProps:{danger:!0,loading:p==null?void 0:p(u.id,"delete")},children:t.jsx(z,{size:"small",danger:!0,loading:p==null?void 0:p(u.id,"delete"),onClick:E=>E.stopPropagation(),children:d("settings.mcpServerTable.actions.delete")})}),j?t.jsx(z,{size:"small",onClick:E=>{E.stopPropagation(),m==null||m(u)},loading:p==null?void 0:p(u.id,"disconnect"),children:d("settings.mcpServerTable.actions.disconnect")}):t.jsx(z,{size:"small",type:"primary",ghost:!0,onClick:E=>{E.stopPropagation(),l==null||l(u)},loading:p==null?void 0:p(u.id,"connect"),children:d("settings.mcpServerTable.actions.connect")}),t.jsx(z,{size:"small",onClick:E=>{E.stopPropagation(),c==null||c(u)},loading:p==null?void 0:p(u.id,"refresh"),children:d("settings.mcpServerTable.actions.refreshTools")})]})}}],[p,l,r,m,o,c,f,d,b.colorBorderSecondary,b.colorFillSecondary,b.colorTextSecondary,b.marginXS]);return t.jsx(et,{rowKey:"id",columns:v,dataSource:e,loading:s,pagination:!1,locale:{emptyText:d("settings.mcpServerTable.empty")},onRow:T=>({onClick:()=>a==null?void 0:a(T.id),style:{cursor:a?"pointer":"default",backgroundColor:n===T.id?b.colorFillSecondary:void 0}})})},{Text:tn}=le,{TextArea:Sr}=U,sn=e=>{const s=e??ps(""),n=s.transport,a=n.type==="stdio"?Object.entries(n.env??{}).map(([r,l])=>({key:r,value:l})):[],o=n.type==="sse"?n.headers.map(r=>({name:r.name,value:r.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:o,requestTimeoutMs:s.request_timeout_ms||Yt,healthcheckIntervalMs:s.healthcheck_interval_ms||Zt,allowedTools:s.allowed_tools||[],deniedTools:s.denied_tools||[]}},_r=e=>e.reduce((s,n)=>{var o;const a=(o=n.key)==null?void 0:o.trim();return a&&(s[a]=n.value??""),s},{}),kr=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??""}}),nn=(e,s,n)=>{var d,b,f;const a=s==="edit"&&(n==null?void 0:n.id)||e.id,o=(d=e.name)==null?void 0:d.trim(),r=typeof e.requestTimeoutMs=="number"?e.requestTimeoutMs:(n==null?void 0:n.request_timeout_ms)??Yt,l=typeof e.healthcheckIntervalMs=="number"?e.healthcheckIntervalMs:(n==null?void 0:n.healthcheck_interval_ms)??Zt,m=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)??[],p=e.transportType==="sse"?{type:"sse",url:((b=e.url)==null?void 0:b.trim())||"",headers:kr(e.headerEntries||[]),connect_timeout_ms:(n==null?void 0:n.transport.type)==="sse"?n.transport.connect_timeout_ms??us:us}:{type:"stdio",command:((f=e.command)==null?void 0:f.trim())||"",args:e.args||[],env:_r(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??Ht:Ht};return{id:a,name:o||void 0,enabled:e.enabled,transport:p,request_timeout_ms:r,healthcheck_interval_ms:l,allowed_tools:m,denied_tools:c,reconnect:n==null?void 0:n.reconnect}},an=e=>JSON.stringify(e||ps(""),null,2),bs=(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 o=typeof a.id=="string"?a.id:"";if(!o.trim())return{valid:!1,error:s("settings.mcpServerForm.missingIdField")};if(a.transport&&typeof a.transport=="object"){const b=a;return!b.transport||typeof b.transport!="object"?{valid:!1,error:s("settings.mcpServerForm.missingTransportField")}:{valid:!0,config:b}}const r=typeof a.enabled=="boolean"?a.enabled:typeof a.disabled=="boolean"?!a.disabled:!0,l=typeof a.request_timeout_ms=="number"?a.request_timeout_ms:Yt,m=typeof a.healthcheck_interval_ms=="number"?a.healthcheck_interval_ms:Zt,c=Array.isArray(a.allowed_tools)?a.allowed_tools.filter(b=>typeof b=="string"):[],p=Array.isArray(a.denied_tools)?a.denied_tools.filter(b=>typeof b=="string"):[],d=typeof a.name=="string"?a.name:void 0;if(typeof a.url=="string"){const b=a.headers,f=Array.isArray(b)?b.map(T=>{if(!T||typeof T!="object")return null;const u=T,M=typeof u.name=="string"?u.name:"",j=typeof u.value=="string"?u.value:"";return M.trim()?{name:M,value:j}:null}).filter(T=>!!T):b&&typeof b=="object"?Object.entries(b).filter(([T])=>T.trim()).map(([T,u])=>({name:T,value:typeof u=="string"?u:""})):[],v=typeof a.connect_timeout_ms=="number"?a.connect_timeout_ms:us;return{valid:!0,config:{id:o,name:d,enabled:r,transport:{type:"sse",url:a.url,headers:f,connect_timeout_ms:v},request_timeout_ms:l,healthcheck_interval_ms:m,allowed_tools:c,denied_tools:p,reconnect:void 0}}}if(typeof a.command=="string"){const b=Array.isArray(a.args)?a.args.filter(u=>typeof u=="string"):[],f=a.env,v=f&&typeof f=="object"?Object.entries(f).reduce((u,[M,j])=>(typeof j=="string"&&(u[M]=j),u),{}):{},T=typeof a.startup_timeout_ms=="number"?a.startup_timeout_ms:Ht;return{valid:!0,config:{id:o,name:d,enabled:r,transport:{type:"stdio",command:a.command,args:b,cwd:typeof a.cwd=="string"?a.cwd:void 0,env:v,startup_timeout_ms:T},request_timeout_ms:l,healthcheck_interval_ms:m,allowed_tools:c,denied_tools:p,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")})}}},wr=({open:e,mode:s,initialConfig:n,confirmLoading:a=!1,onCancel:o,onSubmit:r})=>{const{t:l}=Z(),[m]=k.useForm(),[c,p]=i.useState("form"),[d,b]=i.useState(""),[f,v]=i.useState(null),T=i.useMemo(()=>sn(n),[n]),u=k.useWatch("transportType",m)??"stdio";i.useEffect(()=>{e&&(m.setFieldsValue(T),b(an(n)),v(null),p("form"))},[m,T,n,e]);const M=()=>{m.resetFields(),b(""),v(null),o()},j=async()=>{if(c==="json"){const S=bs(d,l);if(!S.valid){v(S.error);return}v(null);try{await r(S.config),b("")}catch(P){console.error("MCP server JSON submission error:",P)}return}try{const S=await m.validateFields(),P=nn(S,s,n);await r(P),m.resetFields()}catch(S){console.error("MCP server form submission error:",S)}},x=S=>{b(S),f&&bs(S,l).valid&&v(null)},E=S=>{if(S==="json")try{const P=m.getFieldsValue(),ee=nn(P,s,n);b(JSON.stringify(ee,null,2))}catch{b(an(n))}else{const P=bs(d,l);P.valid&&m.setFieldsValue(sn(P.config))}p(S),v(null)};return t.jsxs(ot,{title:l(s==="edit"?"settings.mcpServerForm.editTitle":"settings.mcpServerForm.addTitle"),open:e,onCancel:M,onOk:()=>{j()},okText:l("settings.mcpServerForm.save"),destroyOnClose:!0,forceRender:!0,confirmLoading:a,width:720,children:[t.jsx("div",{style:{marginBottom:16},children:t.jsxs(bt.Group,{value:c,onChange:S=>E(S.target.value),optionType:"button",buttonStyle:"solid",children:[t.jsxs(bt.Button,{value:"form",children:[t.jsx(pa,{})," ",l("settings.mcpServerForm.modeForm")]}),t.jsxs(bt.Button,{value:"json",children:[t.jsx(ha,{})," ",l("settings.mcpServerForm.modeJson")]})]})}),c==="json"&&f&&t.jsx(ke,{type:"error",message:l("settings.mcpServerForm.jsonError"),description:f,showIcon:!0,style:{marginBottom:16},closable:!0,onClose:()=>v(null)}),c==="json"?t.jsx(Sr,{value:d,onChange:S=>x(S.target.value),rows:20,style:{fontFamily:"monospace",fontSize:13},placeholder:JSON.stringify(ps("example-server"),null,2)}):t.jsxs(k,{layout:"vertical",form:m,preserve:!0,initialValues:T,children:[t.jsx(k.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(U,{placeholder:"filesystem",disabled:s==="edit",autoComplete:"off"})}),t.jsx(k.Item,{name:"name",label:l("settings.mcpServerForm.displayName"),children:t.jsx(U,{placeholder:"Filesystem MCP",autoComplete:"off"})}),t.jsx(k.Item,{name:"enabled",label:l("settings.mcpServerForm.enabled"),valuePropName:"checked",extra:l("settings.mcpServerForm.enabledHelp"),children:t.jsx(ge,{})}),t.jsx(k.Item,{name:"transportType",label:l("settings.mcpServerForm.transportType"),rules:[{required:!0,message:l("settings.mcpServerForm.transportTypeRequired")}],children:t.jsx(ae,{options:[{label:l("settings.mcpServerForm.transportOptions.stdio"),value:"stdio"},{label:l("settings.mcpServerForm.transportOptions.sse"),value:"sse"}]})}),u==="stdio"?t.jsxs(t.Fragment,{children:[t.jsx(k.Item,{name:"command",label:l("settings.mcpServerForm.command"),rules:[{required:!0,message:l("settings.mcpServerForm.commandRequired")}],children:t.jsx(U,{placeholder:"npx",autoComplete:"off"})}),t.jsx(k.Item,{name:"args",label:l("settings.mcpServerForm.arguments"),children:t.jsx(ae,{mode:"tags",tokenSeparators:[","],placeholder:l("settings.mcpServerForm.argumentsPlaceholder"),open:!1})}),t.jsx(k.List,{name:"envEntries",children:(S,{add:P,remove:ee})=>t.jsxs(I,{direction:"vertical",style:{width:"100%"},children:[t.jsxs(I,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[t.jsx(tn,{strong:!0,children:l("settings.mcpServerForm.envVars")}),t.jsx(z,{icon:t.jsx(Ut,{}),onClick:()=>P({key:"",value:""}),type:"dashed",children:l("settings.mcpServerForm.addEnv")})]}),S.map(R=>t.jsxs(I,{align:"baseline",style:{display:"flex"},children:[t.jsx(k.Item,{...R,name:[R.name,"key"],rules:[{required:!0,message:l("settings.mcpServerForm.keyRequired")}],children:t.jsx(U,{placeholder:"MCP_ROOT",autoComplete:"off"})}),t.jsx(k.Item,{...R,name:[R.name,"value"],children:t.jsx(U,{placeholder:"/Users/me/workspace",autoComplete:"off"})}),t.jsx(z,{danger:!0,type:"text",icon:t.jsx(Js,{}),onClick:()=>ee(R.name),"aria-label":l("settings.mcpServerForm.removeEnv","Remove environment variable")})]},R.key))]})})]}):t.jsxs(t.Fragment,{children:[t.jsx(k.Item,{name:"url",label:l("settings.mcpServerForm.sseUrl"),rules:[{required:!0,message:l("settings.mcpServerForm.sseUrlRequired")},{validator:async(S,P)=>{if(P)try{new URL(P)}catch{throw new Error(l("settings.mcpServerForm.validUrlRequired"))}}}],children:t.jsx(U,{placeholder:"http://localhost:4000/sse",autoComplete:"off"})}),t.jsx(k.List,{name:"headerEntries",children:(S,{add:P,remove:ee})=>t.jsxs(I,{direction:"vertical",style:{width:"100%"},children:[t.jsxs(I,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[t.jsx(tn,{strong:!0,children:l("settings.mcpServerForm.headers")}),t.jsx(z,{icon:t.jsx(Ut,{}),onClick:()=>P({name:"",value:""}),type:"dashed",children:l("settings.mcpServerForm.addHeader")})]}),S.map(R=>t.jsxs(I,{align:"baseline",style:{display:"flex"},children:[t.jsx(k.Item,{...R,name:[R.name,"name"],rules:[{required:!0,message:l("settings.mcpServerForm.headerNameRequired")}],children:t.jsx(U,{placeholder:"Authorization",autoComplete:"off"})}),t.jsx(k.Item,{...R,name:[R.name,"value"],children:t.jsx(U,{placeholder:"Bearer token",autoComplete:"off"})}),t.jsx(z,{danger:!0,type:"text",icon:t.jsx(Js,{}),onClick:()=>ee(R.name),"aria-label":l("settings.mcpServerForm.removeHeader","Remove header")})]},R.key))]})})]})]})]})},is=e=>!!e&&typeof e=="object"&&!Array.isArray(e),ut=(e,s)=>{const n=e[s];return typeof n=="string"?n:void 0},rn=(e,s)=>{const n=e[s];return typeof n=="boolean"?n:void 0},Cr=(e,s)=>{const n=e[s];return Array.isArray(n)?n:void 0},Nt=e=>{if(!is(e))return"any";const s=e.type;if(typeof s=="string"){if(s==="array"){const r=e.items;return`array<${Nt(r)}>`}return s==="object"?"object":s}if(Array.isArray(s)){const r=s.filter(l=>typeof l=="string").map(l=>l==="array"?"array<any>":l);return r.length>0?r.join(" | "):"any"}const n=Array.isArray(e.oneOf)?e.oneOf:null;if(n)return n.map(Nt).join(" | ")||"any";const a=Array.isArray(e.anyOf)?e.anyOf:null;if(a)return a.map(Nt).join(" | ")||"any";const o=Array.isArray(e.allOf)?e.allOf:null;return o&&o.map(Nt).join(" & ")||"any"},Mr=e=>{if(!is(e))return null;const s=e.properties;if(!is(s))return{schemaUri:ut(e,"$schema"),title:ut(e,"title"),description:ut(e,"description"),additionalProperties:rn(e,"additionalProperties"),fields:[]};const n=new Set((Cr(e,"required")??[]).filter(o=>typeof o=="string").map(o=>o)),a=Object.entries(s).map(([o,r])=>{const l=is(r)?r:void 0;return{name:o,type:Nt(r),required:n.has(o),description:l?ut(l,"description"):void 0,defaultValue:l?l.default:void 0,enumValues:l&&Array.isArray(l.enum)?l.enum:void 0}});return a.sort((o,r)=>o.required!==r.required?o.required?-1:1:o.name.localeCompare(r.name)),{schemaUri:ut(e,"$schema"),title:ut(e,"title"),description:ut(e,"description"),additionalProperties:rn(e,"additionalProperties"),fields:a}},{Text:Ue}=le,Er=e=>e===void 0?"":e===null?"null":typeof e=="string"?e:Cn(e,0),Dr=({schema:e})=>{const{token:s}=fe.useToken(),{t:n}=Z(),a=i.useMemo(()=>Mr(e),[e]);if(!a)return t.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:Cn(e,2)});const o=[{title:n("components.jsonSchema.field"),dataIndex:"name",key:"name",width:180,render:l=>t.jsx(Ue,{code:!0,children:l})},{title:n("components.jsonSchema.type"),dataIndex:"type",key:"type",width:140,render:l=>t.jsx(Ue,{children:l})},{title:n("components.jsonSchema.required"),dataIndex:"required",key:"required",width:110,render:l=>l?t.jsx(Ue,{strong:!0,style:{color:s.colorError},children:n("components.jsonSchema.yes")}):t.jsx(Ue,{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(Ue,{type:"secondary",children:"-"}):t.jsx(Ue,{children:Er(l)})},{title:n("components.jsonSchema.description"),dataIndex:"description",key:"description",render:l=>l?t.jsx(Ue,{style:{whiteSpace:"pre-wrap"},children:l}):t.jsx(Ue,{type:"secondary",children:"-"})}],r=(a.fields??[]).map(l=>({...l,key:l.name}));return t.jsxs("div",{style:{width:"100%"},children:[t.jsx(_e,{size:"small",column:1,items:[a.schemaUri?{key:"schema",label:"$schema",children:t.jsx(Ue,{code:!0,children:a.schemaUri})}:null,typeof a.additionalProperties=="boolean"?{key:"additionalProperties",label:"additionalProperties",children:t.jsx(Ue,{children:a.additionalProperties?"true":"false"})}:null].filter(Boolean)}),t.jsx(et,{size:"small",pagination:!1,columns:o,dataSource:r,locale:{emptyText:n("components.jsonSchema.noProperties")},style:{marginTop:s.marginSM}})]})},{Text:It}=le,Pr=(e,s)=>`mcp__${e}__${s}`,Ir=({server:e,tools:s,loading:n=!1})=>{const{t:a}=Z();return t.jsx(F,{title:a("settings.mcpToolList.title"),size:"small",children:e?t.jsx(Ke,{loading:n,dataSource:s,locale:{emptyText:a("settings.mcpToolList.empty")},renderItem:o=>{const r=Pr(o.server_id,o.original_name);return t.jsx(Ke.Item,{children:t.jsxs(I,{direction:"vertical",size:2,style:{width:"100%"},children:[t.jsx(It,{strong:!0,children:o.original_name}),t.jsx(It,{type:"secondary",children:o.description||a("settings.mcpToolList.noDescription")}),t.jsx(It,{code:!0,children:o.alias}),t.jsxs(It,{type:"secondary",children:[a("settings.mcpToolList.aliasMapping"),": ",t.jsx(It,{code:!0,children:r})]}),o.parameters!==void 0&&t.jsx(Fs,{size:"small",items:[{key:"schema",label:a("settings.mcpToolList.parametersSchema"),children:t.jsx(Dr,{schema:o.parameters})}]})]})})}}):t.jsx(Ae,{image:Ae.PRESENTED_IMAGE_SIMPLE,description:a("settings.mcpToolList.selectServerHint")})})},{Text:Ft}=le,{useToken:Fr}=fe,{TextArea:Rr}=U,on={[N.Connecting]:"processing",[N.Ready]:"success",[N.Degraded]:"warning",[N.Stopped]:"default",[N.Error]:"error"},Ar=()=>({[N.Connecting]:0,[N.Ready]:0,[N.Degraded]:0,[N.Stopped]:0,[N.Error]:0}),gt=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,Lr=e=>{var n,a,o;const s={};for(const r of e){const l=(n=r.id)==null?void 0:n.trim();if(!l)continue;const c=!(r.enabled??r.config.enabled),p=r.config.transport;if(p.type==="sse"){const b={};for(const v of p.headers??[]){const T=(a=v.name)==null?void 0:a.trim();T&&(b[T]=v.value??"")}const f={url:p.url};c&&(f.disabled=!0),Object.keys(b).length&&(f.headers=b),s[l]=f;continue}const d={command:p.command};c&&(d.disabled=!0),(o=p.args)!=null&&o.length&&(d.args=p.args),p.cwd&&(d.cwd=p.cwd),p.env&&Object.keys(p.env).length&&(d.env=p.env),s[l]=d}return{mcpServers:s}},zr=()=>{const{t:e}=Z(),{token:s}=Fr(),[n,a]=Tt.useMessage(),{servers:o,selectedServerId:r,selectedServerTools:l,isLoadingServers:m,isMutatingConfig:c,isRefreshingAll:p,isSelectedServerToolsLoading:d,error:b,setSelectedServerId:f,addServer:v,updateServer:T,deleteServer:u,connectServer:M,disconnectServer:j,refreshServerTools:x,refreshAll:E,isServerActionLoading:S}=xr(),P=i.useMemo(()=>({[N.Connecting]:e("settings.mcpTab.status.connecting"),[N.Ready]:e("settings.mcpTab.status.ready"),[N.Degraded]:e("settings.mcpTab.status.degraded"),[N.Stopped]:e("settings.mcpTab.status.stopped"),[N.Error]:e("settings.mcpTab.status.error")}),[e]),ee=i.useMemo(()=>({[N.Connecting]:e("settings.mcpTab.statusHelp.connecting"),[N.Ready]:e("settings.mcpTab.statusHelp.ready"),[N.Degraded]:e("settings.mcpTab.statusHelp.degraded"),[N.Stopped]:e("settings.mcpTab.statusHelp.stopped"),[N.Error]:e("settings.mcpTab.statusHelp.error")}),[e]),[R,q]=i.useState(!1),[G,h]=i.useState("create"),[y,D]=i.useState(null),[_,O]=i.useState(!1),[X,A]=i.useState("merge"),[H,V]=i.useState(""),[oe,ce]=i.useState(null),[K,L]=i.useState(!1),W=i.useMemo(()=>r?o.find(g=>g.id===r)??null:null,[r,o]),Q=i.useMemo(()=>{const g=Ar();let ne=0;return o.forEach(de=>{var me,Me;const Ce=((me=de.runtime)==null?void 0:me.status)??N.Stopped;g[Ce]+=1,ne+=((Me=de.runtime)==null?void 0:Me.tool_count)??0}),{byStatus:g,totalServers:o.length,totalTools:ne}},[o]),se={background:s.colorFillSecondary,borderColor:s.colorBorderSecondary,color:s.colorTextSecondary},we=async g=>{try{await u(g.id),n.success(e("settings.mcpTab.serverDeleted"))}catch(ne){n.error(gt(ne,e("settings.mcpTab.deleteServerFailed")))}},qe=async g=>{try{await M(g.id),n.success(e("settings.mcpTab.connectedTo",{name:g.name||g.id}))}catch(ne){n.error(gt(ne,e("settings.mcpTab.connectServerFailed")))}},Ie=async g=>{try{await j(g.id),n.success(e("settings.mcpTab.disconnected",{name:g.name||g.id}))}catch(ne){n.error(gt(ne,e("settings.mcpTab.disconnectServerFailed")))}},kt=async g=>{try{await x(g.id),n.success(e("settings.mcpTab.toolsRefreshedFor",{name:g.name||g.id}))}catch(ne){n.error(gt(ne,e("settings.mcpTab.refreshToolsFailed")))}},ft=async()=>{try{await E(),n.success(e("settings.mcpTab.statusRefreshed"))}catch(g){n.error(gt(g,e("settings.mcpTab.refreshStatusFailed")))}},wt=()=>{D(null),h("create"),q(!0)},Ct=g=>{D(g),h("edit"),q(!0)},it=async g=>{try{if(G==="edit"){if(!y){n.error(e("settings.mcpTab.noServerForEditing"));return}await T(y.id,g),n.success(e("settings.mcpTab.savedServer",{name:y.name||y.id}))}else await v(g),n.success(e("settings.mcpTab.addedServer",{name:g.name||g.id}));q(!1),D(null)}catch(ne){n.error(gt(ne,e("settings.mcpTab.saveServerFailed")))}},lt=()=>{O(!0),ce(null),A("merge"),V("")},Le=async()=>{const g=Lr(o),ne=JSON.stringify(g,null,2);try{await Mn(ne),n.success(e("settings.mcpTab.copiedConfig"))}catch{O(!0),ce(null),A("merge"),V(ne),n.warning(e("settings.mcpTab.clipboardUnavailable"))}},Mt=async()=>{var Ce;ce(null);let g;try{g=JSON.parse(H)}catch(me){ce(`${e("settings.mcpTab.invalidJsonPrefix")}: ${me instanceof Error?me.message:e("settings.mcpTab.unknownError")}`);return}if(!g||typeof g!="object"){ce(e("settings.mcpTab.jsonMustBeObject"));return}const de=g.mcpServers;if(!de||typeof de!="object"){ce(e("settings.mcpTab.missingMcpServers"));return}L(!0);try{const me=await Pn.importServers({mcpServers:de,mode:X}),Me=((Ce=me.start_errors)==null?void 0:Ce.length)??0;n.success(e("settings.mcpTab.importSummary",{count:me.server_ids.length,added:me.added,updated:me.updated,removed:me.removed,failed:Me})),Me&&n.warning(e("settings.mcpTab.importStartFailures")),O(!1),V(""),await ft()}catch(me){ce(gt(me,e("settings.mcpTab.importFailed")))}finally{L(!1)}};return t.jsxs(I,{direction:"vertical",size:s.marginMD,style:{width:"100%"},children:[a,b?t.jsx(ke,{type:"error",showIcon:!0,message:b}):null,t.jsx(F,{size:"small",title:e("settings.mcpTab.overviewTitle"),children:t.jsxs(I,{direction:"vertical",size:s.marginXS,style:{width:"100%"},children:[t.jsx(Ft,{type:"secondary",children:e("settings.mcpTab.overviewDescription")}),t.jsxs(I,{wrap:!0,children:[t.jsx(ue,{style:se,children:e("settings.mcpTab.totalServers",{count:Q.totalServers})}),t.jsx(ue,{style:se,children:e("settings.mcpTab.totalTools",{count:Q.totalTools})}),Object.values(N).map(g=>t.jsx(xe,{title:ee[g],children:t.jsxs(ue,{color:g===N.Stopped?void 0:on[g],style:{cursor:"help",...g===N.Stopped?se:void 0},children:[P[g],": ",Q.byStatus[g]]})},g))]}),t.jsx(Ft,{type:"secondary",children:e("settings.mcpTab.statusGuideTitle")}),t.jsx(I,{direction:"vertical",size:2,style:{width:"100%"},children:Object.values(N).map(g=>t.jsxs(Ft,{type:"secondary",children:[t.jsx(ue,{color:g===N.Stopped?void 0:on[g],style:{marginInlineEnd:8,...g===N.Stopped?se:void 0},children:P[g]}),ee[g]]},`guide-${g}`))})]})}),t.jsx(F,{size:"small",title:e("settings.mcpTab.serversTitle"),extra:t.jsxs(I,{children:[t.jsx(z,{type:"primary",onClick:wt,children:e("settings.mcpTab.addServer")}),t.jsx(z,{icon:t.jsx(jt,{}),loading:p,onClick:()=>{ft()},children:e("settings.mcpTab.refreshAll")}),t.jsx(z,{icon:t.jsx(En,{}),onClick:()=>void Le(),children:e("settings.mcpTab.export")}),t.jsx(z,{icon:t.jsx(fa,{}),onClick:lt,children:e("settings.mcpTab.import")})]}),children:t.jsx(jr,{servers:o,loading:m,selectedServerId:r,onSelectServer:f,onEditServer:Ct,onDeleteServer:we,onConnectServer:qe,onDisconnectServer:Ie,onRefreshTools:kt,isServerActionLoading:S})}),t.jsx(Ir,{server:W,tools:l,loading:d}),t.jsx(wr,{open:R,mode:G,initialConfig:(y==null?void 0:y.config)??null,confirmLoading:c,onCancel:()=>{c||(q(!1),D(null))},onSubmit:g=>void it(g)}),t.jsx(ot,{open:_,title:e("settings.mcpTab.importModalTitle"),okText:e("settings.mcpTab.import"),onOk:()=>void Mt(),okButtonProps:{loading:K},onCancel:()=>{K||(O(!1),ce(null))},width:800,destroyOnClose:!1,children:t.jsxs(I,{direction:"vertical",style:{width:"100%"},size:"middle",children:[t.jsxs(Ft,{type:"secondary",children:[e("settings.mcpTab.importHint"),t.jsx("br",{}),t.jsx(Ft,{code:!0,children:'{ "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "..."] } } }'})]}),t.jsxs(bt.Group,{value:X,onChange:g=>A(g.target.value),optionType:"button",buttonStyle:"solid",children:[t.jsx(bt.Button,{value:"merge",children:e("settings.mcpTab.importModeMerge")}),t.jsx(bt.Button,{value:"replace",children:e("settings.mcpTab.importModeReplace")})]}),X==="replace"?t.jsx(ke,{type:"warning",showIcon:!0,message:e("settings.mcpTab.replaceWarning")}):null,oe?t.jsx(ke,{type:"error",showIcon:!0,message:oe}):null,t.jsx(Rr,{value:H,onChange:g=>V(g.target.value),rows:14,placeholder:'{"mcpServers": { "filesystem": { "command": "...", "args": [], "env": {} } }}',spellCheck:!1})]})})]})},In=1,Or=365,Fn=e=>Number.isFinite(e)?Math.min(Or,Math.max(In,Math.floor(e??30))):30,vs=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]),o=Number(s[3]),r=new Date(Date.UTC(n,a-1,o));return r.getUTCFullYear()!==n||r.getUTCMonth()!==a-1||r.getUTCDate()!==o?null:r},Rt=e=>e.toISOString().slice(0,10),Nr=(e,s)=>{const n=new Date(e.getTime());return n.setUTCDate(n.getUTCDate()+s),n},Vr=(e,s)=>{const n=s.getTime()-e.getTime(),a=Math.floor(n/864e5)+1;return Fn(a)},zs=(e,s=new Date)=>{const n=Fn(e.days),a=Rt(s),o=vs(e.endDate)??vs(a);if(!o)return{startDate:a,endDate:a,days:In};const r=vs(e.startDate);if(r){const m=o<r?r:o;return{startDate:Rt(r),endDate:Rt(m),days:Vr(r,m)}}const l=Nr(o,-(n-1));return{startDate:Rt(l),endDate:Rt(o),days:n}},$r=15e3,qr=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,Br=(e={})=>{const{filters:s,autoRefreshMs:n=$r}=e,a=i.useMemo(()=>({startDate:s==null?void 0:s.startDate,endDate:s==null?void 0:s.endDate,days:(s==null?void 0:s.days)??30,endpoint:s==null?void 0:s.endpoint,model:s==null?void 0:s.model,limit:(s==null?void 0:s.limit)??100}),[s==null?void 0:s.startDate,s==null?void 0:s.endDate,s==null?void 0:s.days,s==null?void 0:s.endpoint,s==null?void 0:s.model,s==null?void 0:s.limit]),o=i.useMemo(()=>zs({startDate:a.startDate,endDate:a.endDate,days:a.days}),[a.days,a.endDate,a.startDate]),[r,l]=i.useState(null),[m,c]=i.useState([]),[p,d]=i.useState([]),[b,f]=i.useState(!1),[v,T]=i.useState(!1),[u,M]=i.useState(null),j=i.useCallback(async E=>{E?f(!0):T(!0);try{const S={startDate:o.startDate,endDate:o.endDate,endpoint:a.endpoint,model:a.model,limit:a.limit},[P,ee,R]=await Promise.all([Vt.getForwardSummary(S),Vt.getForwardByEndpoint(S),Vt.getForwardRequests(S)]);l(P),c(ee),d(R),M(null)}catch(S){M(qr(S,"Failed to load forward metrics"))}finally{E?f(!1):T(!1)}},[a.endpoint,a.model,a.limit,o.endDate,o.startDate]),x=i.useCallback(async()=>{await j(!1)},[j]);return i.useEffect(()=>{j(!0)},[j]),i.useEffect(()=>{if(n<=0)return;const E=window.setInterval(()=>{j(!1)},n);return()=>{window.clearInterval(E)}},[n,j]),{summary:r,endpointMetrics:m,requests:p,isLoading:b,isRefreshing:v,error:u,refresh:x}},Ur=15e3,ln=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,Hr=(e={})=>{const{filters:s,autoRefreshMs:n=Ur,service:a=Vt}=e,o=i.useMemo(()=>({startDate:s==null?void 0:s.startDate,endDate:s==null?void 0:s.endDate,model:s==null?void 0:s.model,days:(s==null?void 0:s.days)??30,granularity:(s==null?void 0:s.granularity)??"daily",sessionLimit:(s==null?void 0:s.sessionLimit)??200}),[s==null?void 0:s.startDate,s==null?void 0:s.endDate,s==null?void 0:s.model,s==null?void 0:s.days,s==null?void 0:s.granularity,s==null?void 0:s.sessionLimit]),r=i.useMemo(()=>zs({startDate:o.startDate,endDate:o.endDate,days:o.days}),[o.days,o.endDate,o.startDate]),[l,m]=i.useState(null),[c,p]=i.useState([]),[d,b]=i.useState([]),[f,v]=i.useState([]),[T,u]=i.useState(null),[M,j]=i.useState([]),[x,E]=i.useState(null),[S,P]=i.useState(!1),[ee,R]=i.useState(!1),[q,G]=i.useState(!1),[h,y]=i.useState(null),D=i.useCallback(async A=>{A?R(!0):G(!0);try{const H=a.getMemorySummary?a.getMemorySummary().catch(()=>null):Promise.resolve(null),V=a.getMemoryTimeline?a.getMemoryTimeline({days:r.days,endDate:r.endDate,granularity:o.granularity}).catch(()=>[]):Promise.resolve([]),[oe,ce,K,L,W,Q]=await Promise.all([a.getSummary({startDate:r.startDate,endDate:r.endDate}),a.getByModel({startDate:r.startDate,endDate:r.endDate}),a.getSessions({startDate:r.startDate,endDate:r.endDate,model:o.model,limit:o.sessionLimit}),a.getDaily({days:r.days,endDate:r.endDate,granularity:o.granularity}),H,V]);m(oe),p(ce),b(K),v(L),u(W),j(Q),y(null)}catch(H){y(ln(H,"Failed to load metrics"))}finally{A?R(!1):G(!1)}},[o.granularity,o.model,o.sessionLimit,r.days,r.endDate,r.startDate,a]),_=i.useCallback(async()=>{await D(!1)},[D]),O=i.useCallback(async A=>{P(!0);try{const H=await a.getSessionDetail(A);E(H)}catch(H){y(ln(H,"Failed to load session detail"))}finally{P(!1)}},[a]),X=i.useCallback(()=>{E(null)},[]);return i.useEffect(()=>{D(!0)},[D]),i.useEffect(()=>{if(n<=0)return;const A=window.setInterval(()=>{D(!1)},n);return()=>{window.clearInterval(A)}},[n,D]),{summary:l,modelMetrics:c,sessions:d,timeline:f,memorySummary:T,memoryTimeline:M,sessionDetail:x,isLoading:ee,isRefreshing:q,isSessionDetailLoading:S,error:h,refresh:_,loadSessionDetail:O,clearSessionDetail:X}},Kr=15e3,Wr=(e,s)=>e instanceof Error&&e.message.trim()?e.message:s,Gr=(e={})=>{const{filters:s,autoRefreshMs:n=Kr}=e,a=i.useMemo(()=>({startDate:s==null?void 0:s.startDate,endDate:s==null?void 0:s.endDate,days:(s==null?void 0:s.days)??30,model:s==null?void 0:s.model}),[s==null?void 0:s.days,s==null?void 0:s.endDate,s==null?void 0:s.model,s==null?void 0:s.startDate]),o=i.useMemo(()=>zs({startDate:a.startDate,endDate:a.endDate,days:a.days}),[a.days,a.endDate,a.startDate]),[r,l]=i.useState(null),[m,c]=i.useState(!1),[p,d]=i.useState(!1),[b,f]=i.useState(null),v=i.useCallback(async u=>{u?c(!0):d(!0);try{const M=await Vt.getUsageBreakdown({startDate:o.startDate,endDate:o.endDate,model:a.model});l(M),f(null)}catch(M){f(Wr(M,"Failed to load usage breakdown"))}finally{u?c(!1):d(!1)}},[a.model,o.endDate,o.startDate]),T=i.useCallback(async()=>{await v(!1)},[v]);return i.useEffect(()=>{v(!0)},[v]),i.useEffect(()=>{if(n<=0)return;const u=window.setInterval(()=>{v(!1)},n);return()=>{window.clearInterval(u)}},[n,v]),{data:r,isLoading:m,isRefreshing:p,error:b,refresh:T}},{useToken:Jr}=fe,Xr=({data:e,loading:s})=>{const{t:n}=Z(),{token:a}=Jr();if(s)return t.jsx(F,{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(F,{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 o=e.map(r=>({endpoint:r.endpoint.split(".").pop()||r.endpoint,requests:r.requests,successful:r.successful,failed:r.failed}));return t.jsx(F,{size:"small",className:"lotus-metric-card",title:n("settings.charts.endpointDistribution"),children:t.jsx("div",{style:{width:"100%",height:240},children:t.jsx(St,{children:t.jsxs(As,{data:o,children:[t.jsx(Gt,{strokeDasharray:"3 3"}),t.jsx(Jt,{dataKey:"endpoint"}),t.jsx(Xt,{}),t.jsx(_t,{formatter:(r,l)=>[`${r}`,l.charAt(0).toUpperCase()+l.slice(1)]}),t.jsx(Ls,{}),t.jsx(ds,{dataKey:"successful",fill:"var(--lotus-chart-secondary)",name:n("settings.common.successful"),fillOpacity:.9,radius:[4,4,0,0]}),t.jsx(ds,{dataKey:"failed",fill:"var(--lotus-chart-danger)",name:n("settings.common.failed"),fillOpacity:.9,radius:[4,4,0,0]})]})})})})},Ts=e=>e.replace(/\.0$/,""),Rn=e=>e.toLocaleString(),An=e=>Number.isFinite(e)?e.toLocaleString(void 0,{maximumFractionDigits:20}):String(e),Os=e=>{if(!Number.isFinite(e))return String(e);const s=Math.abs(e);if(s>=1e9){const n=s>=1e10?0:1;return`${Ts((e/1e9).toFixed(n))}B`}if(s>=1e6){const n=s>=1e7?0:1;return`${Ts((e/1e6).toFixed(n))}M`}if(s>=1e3){const n=s>=1e4?0:1;return`${Ts((e/1e3).toFixed(n))}K`}return Rn(e)},Yr=e=>Number.isFinite(e)&&Math.abs(e)>=1e3,Ln=e=>An(e),Kt=e=>{if(!Number.isFinite(e))return String(e);const s=Os(e);return Yr(e)?t.jsx(xe,{title:t.jsx("div",{children:An(e)}),children:t.jsx("span",{children:s})}):s},Qe=e=>{const s=Number(e??0);return Number.isFinite(s)?Kt(s):e==null?"-":String(e)},{useToken:Zr}=fe,Qr=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),n=Math.floor(s/60),a=s%60;if(n>=60){const o=Math.floor(n/60),r=n%60;return`${o}h ${r}m`}return n>0?`${n}m ${a}s`:`${a}s`},cn=({summary:e,loading:s})=>{const{t:n}=Z(),{token:a}=Zr();if(s)return t.jsx(tt,{active:!0,paragraph:{rows:1}});const o=e&&e.total_requests>0?(e.successful_requests/e.total_requests*100).toFixed(1):"0.0";return t.jsxs(Ne,{gutter:[a.marginSM,a.marginSM],children:[t.jsx(ie,{xs:24,sm:12,xl:6,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:n("settings.forwardMetricsCards.totalForwardRequests"),value:(e==null?void 0:e.total_requests)??0,precision:0,formatter:Qe,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),t.jsx(ie,{xs:24,sm:12,xl:6,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:n("settings.forwardMetricsCards.successRate"),value:o,suffix:"%",valueStyle:{color:Number(o)>=95?"var(--lotus-chart-secondary)":Number(o)>=80?"var(--lotus-chart-accent)":"var(--lotus-chart-danger)"}})})}),t.jsx(ie,{xs:24,sm:12,xl:6,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:n("settings.forwardMetricsCards.forwardTokens"),value:(e==null?void 0:e.total_tokens.total_tokens)??0,precision:0,formatter:Qe,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})}),t.jsx(ie,{xs:24,sm:12,xl:6,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:n("settings.forwardMetricsCards.avgResponseTime"),value:Qr(e==null?void 0:e.avg_duration_ms),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:mt}=le,eo=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`},to=e=>new Date(e).toLocaleString(),so=({requests:e,loading:s})=>{const{t:n}=Z(),a=[{title:n("settings.metricsTable.forward.columns.id"),dataIndex:"forward_id",key:"forward_id",width:120,render:o=>t.jsxs(mt,{style:{fontSize:12},copyable:!0,children:[o.slice(0,8),"..."]})},{title:n("settings.metricsTable.forward.columns.endpoint"),dataIndex:"endpoint",key:"endpoint",width:150,render:o=>t.jsx(ue,{color:"processing",children:o.split(".").pop()||o})},{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:o=>t.jsx(ue,{color:o?"purple":"processing",children:n(o?"settings.metricsTable.forward.typeStream":"settings.metricsTable.forward.typeSync")})},{title:n("settings.metricsTable.forward.columns.status"),key:"status",width:100,render:(o,r)=>{const l=r.status==="success"?"success":r.status==="error"?"error":"default";return t.jsx(ya,{status:l,text:r.status_code?t.jsxs("span",{children:[r.status,t.jsxs(mt,{type:"secondary",style:{marginLeft:4},children:["(",r.status_code,")"]})]}):r.status||"-"})}},{title:n("settings.metricsTable.forward.columns.tokens"),key:"tokens",width:100,render:(o,r)=>r.token_usage?t.jsx(mt,{children:Kt(r.token_usage.total_tokens)}):t.jsx(mt,{type:"secondary",children:"-"})},{title:n("settings.metricsTable.forward.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",width:100,render:o=>eo(o)},{title:n("settings.metricsTable.forward.columns.started"),dataIndex:"started_at",key:"started_at",width:160,render:o=>t.jsx(mt,{type:"secondary",style:{fontSize:12},children:to(o)})},{title:n("settings.metricsTable.forward.columns.error"),dataIndex:"error",key:"error",width:200,render:o=>o?t.jsx(mt,{type:"danger",ellipsis:!0,style:{maxWidth:180},children:o}):t.jsx(mt,{type:"secondary",children:"-"})}];return t.jsx(et,{rowKey:"forward_id",className:"lotus-metric-table",columns:a,dataSource:e,loading:s,size:"small",pagination:{pageSize:10,showSizeChanger:!0,showTotal:o=>n("settings.metricsTable.forward.totalRequests",{total:o}),pageSizeOptions:["10","20","50","100"]},scroll:{x:1200},locale:{emptyText:n("settings.metricsTable.forward.empty")}})},{useToken:no}=fe,ao=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString()},dn=({summary:e,loading:s})=>{const{t:n}=Z(),{token:a}=no();return s?t.jsx(tt,{active:!0,paragraph:{rows:1}}):t.jsxs(Ne,{gutter:[a.marginSM,a.marginSM],children:[t.jsx(ie,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:n("settings.unifiedMetricsCards.totalMemories"),value:(e==null?void 0:e.total_memories)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),t.jsx(ie,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{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(ie,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:n("settings.unifiedMetricsCards.memoryProjects"),value:(e==null?void 0:e.project_count)??0,precision:0,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),t.jsx(ie,{xs:24,sm:12,lg:8,xl:6,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:n("settings.unifiedMetricsCards.lastReindex"),value:ao(e==null?void 0:e.last_reindex_at),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:ro}=le,oo=({data:e,loading:s})=>{const{t:n}=Z();return s?t.jsx(F,{size:"small",className:"lotus-metric-card",title:n("settings.charts.memoryTrendTitle"),children:t.jsx(tt,{active:!0,paragraph:{rows:5}})}):t.jsx(F,{size:"small",className:"lotus-metric-card",title:n("settings.charts.memoryTrendTitle"),children:e.length===0?t.jsx(Ae,{image:Ae.PRESENTED_IMAGE_SIMPLE,description:n("settings.charts.noMemoryTrend")}):t.jsxs(t.Fragment,{children:[t.jsx(ro,{type:"secondary",children:n("settings.charts.memoryTrendDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(St,{children:t.jsxs(Dn,{data:e,children:[t.jsx(Gt,{strokeDasharray:"3 3"}),t.jsx(Jt,{dataKey:"label",minTickGap:24}),t.jsx(Xt,{allowDecimals:!1}),t.jsx(_t,{}),t.jsx(Ls,{}),t.jsx(vt,{type:"monotone",dataKey:"total_memories",name:n("settings.charts.totalMemories"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),t.jsx(vt,{type:"monotone",dataKey:"created_memories",name:n("settings.charts.createdMemories"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),t.jsx(vt,{type:"monotone",dataKey:"updated_memories",name:n("settings.charts.updatedMemories"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{useToken:io}=fe,lo=e=>{const s=Math.floor(e/1e3),n=Math.floor(s/60),a=s%60;return n>0?`${n}m ${a}s`:`${a}s`},co=e=>{const s=e.filter(a=>typeof a.duration_ms=="number"&&a.duration_ms>0);if(s.length===0)return 0;const n=s.reduce((a,o)=>a+(o.duration_ms??0),0);return Math.floor(n/s.length)},un=({summary:e,sessions:s,loading:n})=>{const{t:a}=Z(),{token:o}=io();if(n)return t.jsx(tt,{active:!0,paragraph:{rows:1}});const r=co(s);return t.jsxs(Ne,{gutter:[o.marginSM,o.marginSM],children:[t.jsx(ie,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{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(ie,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:a("settings.metricsCards.totalSessions"),value:(e==null?void 0:e.total_sessions)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),t.jsx(ie,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:a("settings.metricsCards.chatTokens"),value:(e==null?void 0:e.total_tokens.total_tokens)??0,precision:0,formatter:Qe,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})}),t.jsx(ie,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:a("settings.metricsCards.totalToolCalls"),value:(e==null?void 0:e.total_tool_calls)??0,precision:0,formatter:Qe,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),t.jsx(ie,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:a("settings.metricsCards.tokensSaved",{defaultValue:"Saved Tokens"}),value:(e==null?void 0:e.total_tokens_saved)??0,precision:0,formatter:Qe,valueStyle:{color:"var(--lotus-chart-cyan)"}})})}),t.jsx(ie,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:a("settings.metricsCards.toolContextSavedTokens",{defaultValue:"Tool Context Saved Tokens"}),value:(e==null?void 0:e.tool_context_tokens_saved)??0,precision:0,formatter:Qe,valueStyle:{color:"var(--lotus-chart-accent)"}})})}),t.jsx(ie,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:a("settings.metricsCards.compressionEvents",{defaultValue:"Compression Events"}),value:(e==null?void 0:e.total_compression_events)??0,precision:0,formatter:Qe,valueStyle:{color:"var(--lotus-chart-secondary)"}})})}),t.jsx(ie,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:a("settings.metricsCards.avgSessionDuration"),value:r>0?lo(r):"-",valueStyle:{color:"var(--lotus-chart-accent)"}})})})]})},{Text:uo}=le,gn=["var(--lotus-chart-primary)","var(--lotus-chart-secondary)","var(--lotus-chart-accent)","var(--lotus-chart-purple)","var(--lotus-chart-cyan)"],go=({data:e,loading:s})=>{const{t:n}=Z();if(s)return t.jsx(F,{size:"small",className:"lotus-metric-card",title:n("settings.charts.modelDistribution"),children:t.jsx(tt,{active:!0,paragraph:{rows:5}})});const a=e.map(o=>({name:o.model,value:o.tokens.total_tokens}));return t.jsx(F,{size:"small",className:"lotus-metric-card",title:n("settings.charts.modelDistribution"),children:a.length===0?t.jsx(Ae,{image:Ae.PRESENTED_IMAGE_SIMPLE,description:n("settings.charts.noModelMetrics")}):t.jsxs(t.Fragment,{children:[t.jsx(uo,{type:"secondary",children:n("settings.charts.modelDistributionDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(St,{children:t.jsxs(Ca,{children:[t.jsx(Ma,{data:a,cx:"50%",cy:"50%",outerRadius:90,fill:"var(--lotus-chart-primary)",dataKey:"value",nameKey:"name",label:!0,children:a.map((o,r)=>t.jsx(Ea,{fill:gn[r%gn.length]},`${o.name}-${r}`))}),t.jsx(_t,{formatter:o=>Ln(o)})]})})})]})})},mo=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?"-":s.toLocaleString()},po=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),n=Math.floor(s/60),a=s%60;if(n>=60){const o=Math.floor(n/60),r=n%60;return`${o}h ${r}m`}return n>0?`${n}m ${a}s`:`${a}s`},ho=e=>{switch(e){case"completed":return"success";case"running":return"processing";case"awaiting_response":return"gold";case"error":return"error";case"cancelled":return"warning";default:return"default"}},fo=(e,s)=>{switch(e){case"awaiting_response":return s("settings.metricsTable.session.status.awaitingResponse",{defaultValue:"Awaiting Response"});case"running":return s("settings.metricsTable.session.status.running",{defaultValue:"Running"});case"completed":return s("settings.metricsTable.session.status.completed",{defaultValue:"Completed"});case"error":return s("settings.metricsTable.session.status.error",{defaultValue:"Error"});case"cancelled":return s("settings.metricsTable.session.status.cancelled",{defaultValue:"Cancelled"});default:return e}},yo=({sessions:e,loading:s,onSelectSession:n})=>{const{t:a}=Z(),o=[{title:a("settings.metricsTable.session.columns.session"),dataIndex:"session_id",key:"session_id",render:r=>t.jsx(xe,{title:r,children:t.jsxs("span",{children:[r.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:r=>t.jsx(ue,{color:ho(r),children:fo(r,a)})},{title:a("settings.metricsTable.session.columns.started"),dataIndex:"started_at",key:"started_at",render:r=>mo(r),width:200,sorter:(r,l)=>new Date(r.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:r=>po(r),width:120},{title:a("settings.metricsTable.session.columns.tokens"),key:"tokens",render:(r,l)=>Kt(l.total_token_usage.total_tokens),width:120,sorter:(r,l)=>r.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:(r,l)=>r.tool_call_count-l.tool_call_count},{title:a("settings.metricsTable.session.columns.messages"),dataIndex:"message_count",key:"message_count",width:120,sorter:(r,l)=>r.message_count-l.message_count},{title:a("settings.metricsTable.session.columns.action"),key:"action",fixed:"right",width:120,render:(r,l)=>t.jsx(z,{type:"link",onClick:()=>{n(l.session_id)},children:a("settings.metricsTable.session.view")})}];return t.jsx(et,{rowKey:"session_id",size:"small",className:"lotus-metric-table",columns:o,loading:s,dataSource:e,pagination:{pageSize:10,showSizeChanger:!1},scroll:{x:1100}})},{Text:xo}=le,mn={message_count:"Message Count",last_message_id:"Last Message",pending_question:"Pending Question"},bo=e=>mn[e]?mn[e]:e.split("_").map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "),vo=({breakdown:e,loading:s})=>{const{t:n}=Z();if(s)return t.jsx(F,{size:"small",className:"lotus-metric-card",title:n("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),children:t.jsx(tt,{active:!0,paragraph:{rows:5}})});const a=Object.entries(e??{}).map(([o,r])=>({reason:o,label:n(`settings.syncMismatchReasons.${o}`,{defaultValue:bo(o)}),count:r})).sort((o,r)=>r.count-o.count);return t.jsx(F,{size:"small",className:"lotus-metric-card",title:n("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),extra:t.jsx(xo,{type:"secondary",children:n("settings.metricsDashboard.syncMismatchBreakdownSubtitle",{defaultValue:"Grouped by execute sync mismatch reason"})}),children:a.length===0?t.jsx(Ae,{image:Ae.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(St,{children:t.jsxs(As,{data:a,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[t.jsx(Gt,{strokeDasharray:"3 3"}),t.jsx(Jt,{type:"number",allowDecimals:!1}),t.jsx(Xt,{dataKey:"label",type:"category",width:110}),t.jsx(_t,{formatter:o=>[o.toLocaleString(),n("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})],labelFormatter:o=>n("settings.metricsDashboard.syncMismatchReasonLabel",{defaultValue:"Reason: {{label}}",label:o})}),t.jsx(ds,{dataKey:"count",fill:"var(--lotus-chart-danger)",radius:[0,6,6,0],name:n("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})})]})})})})},{Text:To}=le,jo=({data:e,loading:s})=>{const{t:n}=Z();return s?t.jsx(F,{size:"small",className:"lotus-metric-card",title:n("settings.charts.tokenUsageOverTime"),children:t.jsx(tt,{active:!0,paragraph:{rows:5}})}):t.jsx(F,{size:"small",className:"lotus-metric-card",title:n("settings.charts.tokenUsageOverTime"),children:e.length===0?t.jsx(Ae,{image:Ae.PRESENTED_IMAGE_SIMPLE,description:n("settings.charts.noTokenUsage")}):t.jsxs(t.Fragment,{children:[t.jsx(To,{type:"secondary",children:n("settings.charts.tokenUsageDescription")}),t.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:t.jsx(St,{children:t.jsxs(Dn,{data:e,children:[t.jsx(Gt,{strokeDasharray:"3 3"}),t.jsx(Jt,{dataKey:"label",minTickGap:24}),t.jsx(Xt,{allowDecimals:!1,tickFormatter:Os}),t.jsx(_t,{formatter:a=>Ln(a)}),t.jsx(Ls,{}),t.jsx(vt,{type:"monotone",dataKey:"totalTokens",name:n("settings.charts.total"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),t.jsx(vt,{type:"monotone",dataKey:"promptTokens",name:n("settings.charts.prompt"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),t.jsx(vt,{type:"monotone",dataKey:"completionTokens",name:n("settings.charts.completion"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{Text:So}=le,At=({title:e,subtitle:s,emptyText:n,color:a="var(--lotus-chart-primary)",data:o,loading:r,countLabel:l})=>{const{t:m}=Z();return r?t.jsx(F,{size:"small",className:"lotus-metric-card",title:e,children:t.jsx(tt,{active:!0,paragraph:{rows:5}})}):t.jsx(F,{size:"small",className:"lotus-metric-card",title:e,children:o.length===0?t.jsx(Ae,{image:Ae.PRESENTED_IMAGE_SIMPLE,description:n}):t.jsxs(t.Fragment,{children:[s?t.jsx(So,{type:"secondary",children:s}):null,t.jsx("div",{style:{width:"100%",minWidth:0,height:280,marginTop:s?12:0},children:t.jsx(St,{children:t.jsxs(As,{data:o,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[t.jsx(Gt,{strokeDasharray:"3 3"}),t.jsx(Jt,{type:"number",allowDecimals:!1}),t.jsx(Xt,{dataKey:"label",type:"category",width:110}),t.jsx(_t,{formatter:c=>[c.toLocaleString(),l??m("settings.metricsDashboard.calls",{defaultValue:"Calls"})],labelFormatter:(c,p)=>{var b,f;const d=(f=(b=p==null?void 0:p[0])==null?void 0:b.payload)==null?void 0:f.meta;return d?`${c} · ${d}`:String(c)}}),t.jsx(ds,{dataKey:"count",fill:a,radius:[0,6,6,0],name:l??m("settings.metricsDashboard.calls",{defaultValue:"Calls"})})]})})})]})})},{useToken:_o}=fe,pn=({summary:e,loading:s})=>{const{t:n}=Z(),{token:a}=_o();if(s)return t.jsx(tt,{active:!0,paragraph:{rows:1}});const o=[{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(r=>r.value>0);return o.length===0?null:t.jsx(Ne,{gutter:[a.marginSM,a.marginSM],children:o.map(r=>t.jsx(ie,{xs:24,sm:12,lg:8,xl:4,children:t.jsx(F,{size:"small",className:"lotus-metric-card",children:t.jsx(be,{title:r.title,value:r.value,precision:0,formatter:Qe,valueStyle:{color:r.color}})})},r.key))})},{Text:pt}=le,{useToken:ko}=fe,hn=e=>"date"in e?e.date:e.label,wo=(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)"},ss=e=>{if(!e||e<=0)return"-";const s=Math.floor(e/1e3),n=Math.floor(s/60),a=s%60;if(n>=60){const o=Math.floor(n/60),r=n%60;return`${o}h ${r}m`}return n>0?`${n}m ${a}s`:`${a}s`},fn=e=>{if(!e)return"-";const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString()},js=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}: ${Rn(a)}`).join(" • ")},Ss=(e,s=320)=>({width:"100%",display:"grid",gridTemplateColumns:`repeat(auto-fit, minmax(${s}px, 1fr))`,gap:e}),Co=()=>{const{t:e}=Z(),{token:s}=ko(),n=Jn(g=>g.themeMode)==="dark",[a,o]=i.useState(void 0),[r,l]=i.useState(void 0),[m,c]=i.useState(void 0),[p,d]=i.useState(30),[b,f]=i.useState("daily"),{summary:v,modelMetrics:T,sessions:u,timeline:M,memorySummary:j,memoryTimeline:x,sessionDetail:E,isLoading:S,isRefreshing:P,isSessionDetailLoading:ee,error:R,refresh:q,loadSessionDetail:G,clearSessionDetail:h}=Hr({filters:{startDate:a,endDate:r,model:m,days:p,granularity:b}}),{summary:y,endpointMetrics:D,requests:_,isLoading:O,isRefreshing:X,error:A,refresh:H}=Br({filters:{startDate:a,endDate:r,days:p,model:m}}),{data:V,isLoading:oe,isRefreshing:ce,error:K,refresh:L}=Gr({filters:{startDate:a,endDate:r,days:p,model:m}}),W=i.useMemo(()=>M.map(g=>({label:hn(g),promptTokens:g.total_token_usage.prompt_tokens,completionTokens:g.total_token_usage.completion_tokens,totalTokens:g.total_token_usage.total_tokens})),[M]),Q=i.useMemo(()=>T.map(g=>({label:g.model,value:g.model})),[T]),se=i.useMemo(()=>{const g=M.map(de=>({label:hn(de),sessions:de.total_sessions,tokens:de.total_token_usage.total_tokens})),ne=g.reduce((de,Ce)=>Math.max(de,Ce.sessions),0);return{points:g,maxSessions:ne}},[M]),we=i.useMemo(()=>{const g=_.map(de=>de.duration_ms).filter(de=>typeof de=="number"&&de>0).sort((de,Ce)=>de-Ce);if(g.length===0)return null;const ne=Math.ceil(g.length*.95)-1;return g[Math.max(0,Math.min(ne,g.length-1))]},[_]),qe=i.useMemo(()=>[{title:e("settings.metricsDashboard.roundColumns.round"),dataIndex:"round_id",key:"round_id",render:g=>`${g.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:g=>ss(g)},{title:e("settings.metricsDashboard.roundColumns.tokens"),key:"tokens",render:(g,ne)=>Kt(ne.token_usage.total_tokens)},{title:e("settings.metricsDashboard.roundColumns.toolCalls"),key:"tool_calls",render:(g,ne)=>ne.tool_calls.length}],[e]),Ie=i.useMemo(()=>{const g=(v==null?void 0:v.total_sessions)??0,ne=(v==null?void 0:v.total_tokens.total_tokens)??0,de=(v==null?void 0:v.total_tool_calls)??0,Ce=(v==null?void 0:v.active_sessions)??0,me=u.reduce((Te,We)=>Te+We.total_rounds,0),Me=(v==null?void 0:v.total_tokens_saved)??0,Qt=(v==null?void 0:v.tool_context_tokens_saved)??0,C=(v==null?void 0:v.non_tool_compression_tokens_saved)??0,w=(v==null?void 0:v.prompt_cached_tool_outputs)??0,J=(v==null?void 0:v.total_compression_events)??0,B=(y==null?void 0:y.total_requests)??0,Y=(y==null?void 0:y.total_tokens.total_tokens)??0,pe=(y==null?void 0:y.failed_requests)??0,re=_.filter(Te=>Te.is_stream).length,Ee=g>0?Ce/g*100:0,Ve=B>0?pe/B*100:0,De=_.length>0?re/_.length*100:0,Be=ne>0?Number((Me/ne*100).toFixed(1)):0,ye=Me>0?Number((Qt/Me*100).toFixed(1)):0;return[{title:e("settings.metricsDashboard.compactStats.avgTokensPerSession"),value:g>0?Math.round(ne/g):0},{title:e("settings.metricsDashboard.compactStats.savedTokens",{defaultValue:"Saved Tokens"}),value:Me},{title:e("settings.metricsDashboard.compactStats.toolContextSavedTokens",{defaultValue:"Tool Context Saved Tokens"}),value:Qt},{title:e("settings.metricsDashboard.compactStats.nonToolCompressionSavedTokens",{defaultValue:"Non-Tool Compression Saved Tokens"}),value:C},{title:e("settings.metricsDashboard.compactStats.savedTokenRatio",{defaultValue:"Saved / Chat Tokens"}),value:Be,suffix:"%"},{title:e("settings.metricsDashboard.compactStats.toolSavedShare",{defaultValue:"Tool Share of Saved Tokens"}),value:ye,suffix:"%"},{title:e("settings.metricsDashboard.compactStats.promptCachedToolOutputs",{defaultValue:"Prompt-Cached Tool Outputs"}),value:w},{title:e("settings.metricsDashboard.compactStats.compressionEvents",{defaultValue:"Compression Events"}),value:J},{title:e("settings.metricsDashboard.compactStats.avgRoundsPerSession"),value:g>0?Number((me/g).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.toolCallsPerSession"),value:g>0?Number((de/g).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.activeSessionRate"),value:Number(Ee.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.avgTokensPerForward"),value:B>0?Math.round(Y/B):0},{title:e("settings.metricsDashboard.compactStats.forwardErrorRate"),value:Number(Ve.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.streamingRatio"),value:Number(De.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.p95ForwardLatency"),value:ss(we)},{title:e("settings.metricsDashboard.compactStats.modelCoverage"),value:T.length},{title:e("settings.metricsDashboard.compactStats.endpointCoverage"),value:D.length}]},[D.length,_,y,T.length,we,u,v,e]),kt=i.useMemo(()=>{const g=(y==null?void 0:y.total_requests)??0,ne=(y==null?void 0:y.failed_requests)??0,de=_.filter(Me=>Me.is_stream).length,Ce=_.length>0?de/_.length*100:0,me=g>0?ne/g*100:0;return[{title:e("settings.metricsDashboard.forward.performance.p95Latency",{defaultValue:"P95 Latency"}),value:ss(we)},{title:e("settings.metricsDashboard.forward.performance.errorRate",{defaultValue:"Error Rate"}),value:Number(me.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.streamingRatio",{defaultValue:"Streaming Ratio"}),value:Number(Ce.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.endpointCoverage",{defaultValue:"Endpoint Coverage"}),value:D.length}]},[D.length,_,y,we,e]),ft=i.useMemo(()=>V?[{label:e("settings.metricsDashboard.skillsAndMcp.mix.coreTools",{defaultValue:"Core Tools"}),count:V.core_tool_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.skillLoads",{defaultValue:"Skill Loads"}),count:V.skill_load_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.mcpCalls",{defaultValue:"MCP Calls"}),count:V.mcp_calls}].filter(g=>g.count>0):[],[e,V]),wt=i.useMemo(()=>((V==null?void 0:V.top_skills)??[]).map(g=>({label:g.skill_id,count:g.count})),[V]),Ct=i.useMemo(()=>((V==null?void 0:V.top_mcp_servers)??[]).map(g=>({label:g.server_id,count:g.count,meta:e("settings.metricsDashboard.skillsAndMcp.meta.uniqueTools",{defaultValue:"{{count}} tools",count:g.unique_tools})})),[e,V]),it=i.useMemo(()=>((V==null?void 0:V.top_mcp_tools)??[]).map(g=>({label:g.tool_name,count:g.count,meta:g.server_id})),[V]),lt=i.useMemo(()=>((V==null?void 0:V.top_core_tools)??[]).map(g=>({label:g.name,count:g.count})),[V]),Le=E==null?void 0:E.session,Mt=P||X||ce;return t.jsxs(I,{direction:"vertical",size:s.marginMD,style:{width:"100%"},children:[R?t.jsx(ke,{type:"error",showIcon:!0,message:R}):null,A?t.jsx(ke,{type:"error",showIcon:!0,message:A}):null,K?t.jsx(ke,{type:"error",showIcon:!0,message:K}):null,t.jsx(F,{size:"small",title:e("settings.metricsDashboard.filtersTitle"),extra:t.jsx(z,{icon:t.jsx(jt,{}),loading:Mt,onClick:()=>{q(),H(),L()},children:e("settings.metricsDashboard.refresh")}),children:t.jsxs(I,{wrap:!0,children:[t.jsx(Xs,{placeholder:e("settings.metricsDashboard.startDate"),onChange:g=>{o(g?g.format("YYYY-MM-DD"):void 0)}}),t.jsx(Xs,{placeholder:e("settings.metricsDashboard.endDate"),onChange:g=>{l(g?g.format("YYYY-MM-DD"):void 0)}}),t.jsx(ae,{allowClear:!0,style:{minWidth:180},placeholder:e("settings.metricsDashboard.model"),value:m,options:Q,onChange:g=>{c(g)}}),t.jsx(ae,{style:{width:120},value:p,options:[7,14,30,90].map(g=>({label:e("settings.metricsDashboard.daysOption",{value:g}),value:g})),onChange:g=>{d(g)}}),t.jsx(ae,{style:{width:140},value:b,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:g=>{f(g)}})]})}),t.jsx(F,{size:"small",title:e("settings.metricsDashboard.dashboardTitle"),children:t.jsx(ls,{size:"small",destroyInactiveTabPane:!0,items:[{key:"overview",label:e("settings.metricsDashboard.tabs.overview"),children:t.jsxs(I,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(F,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.overviewSections.scaleTitle",{defaultValue:"Scale & Activity"}),extra:t.jsx(pt,{type:"secondary",children:e("settings.metricsDashboard.overviewSections.scaleSubtitle",{defaultValue:"Current usage volume across chat, forward, skills, and memory."})}),children:t.jsxs(I,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(un,{summary:v,sessions:u,loading:S}),t.jsx(cn,{summary:y,loading:O}),t.jsx(pn,{summary:V,loading:oe}),t.jsx(dn,{summary:j,loading:S})]})}),t.jsxs(F,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.overviewSections.efficiencyTitle",{defaultValue:"Compression & Efficiency Advantage"}),extra:t.jsx(pt,{type:"secondary",children:e("settings.metricsDashboard.overviewSections.efficiencySubtitle",{defaultValue:"Real savings from context compression, especially around tool-heavy workflows."})}),children:[t.jsx(Ne,{gutter:[s.marginSM,s.marginSM],children:Ie.map(g=>t.jsx(ie,{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(be,{title:g.title,value:g.value,suffix:g.suffix,formatter:typeof g.value=="number"?Qe:void 0,valueStyle:{fontSize:s.fontSizeHeading4}})})},g.title))}),t.jsx(pt,{type:"secondary",style:{display:"block",marginTop:s.marginXS},children:e("settings.metricsDashboard.efficiencyHint",{defaultValue:"这些指标优先使用真实运行统计:总节约 Tokens、工具上下文压缩节约、非工具压缩节约、压缩事件数,以及会话 / Forward 的平均负载与质量指标。"})})]})]})},{key:"chat",label:e("settings.metricsDashboard.tabs.chat",{defaultValue:"Chat"}),children:t.jsxs(I,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(un,{summary:v,sessions:u,loading:S}),t.jsxs("div",{style:Ss(s.marginSM,360),children:[t.jsx(jo,{data:W,loading:S}),t.jsx(go,{data:T,loading:S})]}),t.jsxs("div",{style:Ss(s.marginSM,360),children:[t.jsx(vo,{breakdown:v==null?void 0:v.sync_mismatch_breakdown,loading:S}),t.jsx(F,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.activityHeatmapTitle"),children:se.points.length===0?t.jsx(pt,{type:"secondary",children:e("settings.metricsDashboard.noActivity")}):t.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(72px, 1fr))",gap:s.marginXS},children:se.points.map(g=>t.jsxs("div",{style:{borderRadius:s.borderRadiusSM,padding:s.paddingXS,background:wo(g.sessions,se.maxSessions),minHeight:64,color:g.sessions>0?"var(--lotus-metric-text-strong)":s.colorTextSecondary},children:[t.jsx("div",{style:{fontSize:12,lineHeight:1.2},children:g.label}),t.jsx("div",{style:{fontWeight:600,marginTop:4},children:e("settings.metricsDashboard.sessionsCount",{count:g.sessions})}),t.jsx("div",{style:{fontSize:12},children:e("settings.metricsDashboard.tokensAmount",{value:Os(g.tokens)})})]},g.label))})})]})]})},{key:"skills-and-mcp",label:e("settings.metricsDashboard.tabs.skillsAndMcp",{defaultValue:"Skills & MCP"}),children:t.jsxs(I,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(pn,{summary:V,loading:oe}),t.jsxs("div",{style:Ss(s.marginSM,360),children:[t.jsx(At,{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:ft,loading:oe,color:"var(--lotus-chart-primary)"}),t.jsx(At,{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:wt,loading:oe,color:"var(--lotus-chart-purple)"}),t.jsx(At,{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:Ct,loading:oe,color:"var(--lotus-chart-cyan)"}),t.jsx(At,{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:it,loading:oe,color:"var(--lotus-chart-accent)"}),t.jsx(At,{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:lt,loading:oe,color:"var(--lotus-chart-secondary)"})]})]})},{key:"forward",label:e("settings.metricsDashboard.tabs.forward",{defaultValue:"Forward"}),children:t.jsxs(I,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(cn,{summary:y,loading:O}),t.jsx(F,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.forward.performanceTitle",{defaultValue:"Forward Performance"}),children:t.jsx(Ne,{gutter:[s.marginSM,s.marginSM],children:kt.map(g=>t.jsx(ie,{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(be,{title:g.title,value:g.value,suffix:g.suffix,valueStyle:{fontSize:s.fontSizeHeading4}})})},g.title))})}),t.jsx(Xr,{data:D,loading:O})]})},{key:"memory",label:e("settings.metricsDashboard.tabs.memory",{defaultValue:"Memory"}),children:t.jsxs(I,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[t.jsx(dn,{summary:j,loading:S}),t.jsx(oo,{data:x,loading:S}),t.jsx(F,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.memory.breakdownTitle",{defaultValue:"Memory Breakdown"}),children:t.jsxs(_e,{size:"small",bordered:!0,column:1,children:[t.jsx(_e.Item,{label:e("settings.metricsDashboard.memory.byType",{defaultValue:"By Type"}),children:js(j==null?void 0:j.by_type)}),t.jsx(_e.Item,{label:e("settings.metricsDashboard.memory.byStatus",{defaultValue:"By Status"}),children:js(j==null?void 0:j.by_status)}),t.jsx(_e.Item,{label:e("settings.metricsDashboard.memory.byScope",{defaultValue:"By Scope"}),children:js(j==null?void 0:j.by_scope)}),t.jsx(_e.Item,{label:e("settings.metricsDashboard.memory.lastDream",{defaultValue:"Last Dream"}),children:fn(j==null?void 0:j.last_dream_at)}),t.jsx(_e.Item,{label:e("settings.metricsDashboard.memory.lastReindex",{defaultValue:"Last Reindex"}),children:fn(j==null?void 0:j.last_reindex_at)})]})})]})},{key:"records",label:e("settings.metricsDashboard.tabs.records"),children:t.jsx(ls,{size:"small",destroyInactiveTabPane:!0,items:[{key:"sessions",label:e("settings.metricsDashboard.sessionsTabLabel",{count:u.length}),children:t.jsx(F,{size:"small",extra:t.jsx(pt,{type:"secondary",children:e("settings.metricsDashboard.sessionsHint")}),children:t.jsx(yo,{sessions:u,loading:S,onSelectSession:g=>{G(g)}})})},{key:"forward-requests",label:e("settings.metricsDashboard.forwardTabLabel",{count:_.length}),children:t.jsx(F,{size:"small",children:t.jsx(so,{requests:_,loading:O})})}]})}]})}),t.jsx(ot,{title:e("settings.metricsDashboard.sessionMetricsTitle"),open:!!E,onCancel:h,onOk:h,width:960,destroyOnClose:!0,children:ee?t.jsx(pt,{children:e("settings.metricsDashboard.loadingSessionDetails")}):Le?t.jsxs(I,{direction:"vertical",style:{width:"100%"},size:s.marginMD,children:[t.jsxs(_e,{size:"small",bordered:!0,column:2,children:[t.jsx(_e.Item,{label:e("settings.metricsDashboard.sessionDetail.sessionId"),span:2,children:Le.session_id}),t.jsx(_e.Item,{label:e("settings.metricsDashboard.sessionDetail.model"),children:Le.model}),t.jsx(_e.Item,{label:e("settings.metricsDashboard.sessionDetail.status"),children:Le.status}),t.jsx(_e.Item,{label:e("settings.metricsDashboard.sessionDetail.duration"),children:ss(Le.duration_ms)}),t.jsx(_e.Item,{label:e("settings.metricsDashboard.sessionDetail.messages"),children:Le.message_count}),t.jsx(_e.Item,{label:e("settings.metricsDashboard.sessionDetail.totalTokens"),children:Kt(Le.total_token_usage.total_tokens)}),t.jsx(_e.Item,{label:e("settings.metricsDashboard.sessionDetail.toolCalls"),children:Le.tool_call_count})]}),t.jsx(et,{rowKey:"round_id",size:"small",columns:qe,dataSource:E.rounds,pagination:{pageSize:6,showSizeChanger:!1}})]}):t.jsx(pt,{type:"secondary",children:e("settings.metricsDashboard.noDetail")})})]})},{Text:ns}=le,{useToken:Mo}=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"},Do=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},Po=()=>{const{t:e}=Z(),{token:s}=Mo(),[n,a]=Tt.useMessage(),[o,r]=i.useState(!1),[l,m]=i.useState(!0),[c,p]=i.useState("placeholder"),d=i.useMemo(()=>[{label:e("settings.hooksTab.mode.placeholder"),value:"placeholder"},{label:e("settings.hooksTab.mode.error"),value:"error"},{label:e("settings.hooksTab.mode.ocr"),value:"ocr"},{label:e("settings.hooksTab.mode.vision"),value:"vision"}],[e]),b=i.useCallback(async()=>{r(!0);try{const u=await Se.getBambooConfig();m(Do(u)),p(Eo(u))}catch(u){n.error(u instanceof Error?u.message:e("settings.hooksTab.loadFailed"))}finally{r(!1)}},[n,e]),f=i.useCallback(async(u,M)=>{await Se.setBambooConfig({hooks:{image_fallback:{enabled:u,mode:M}}})},[]),v=i.useCallback(async u=>{r(!0);try{await f(u,c),n.success(e(u?"settings.hooksTab.enabled":"settings.hooksTab.disabled")),await b()}catch(M){n.error(M instanceof Error?M.message:e("settings.hooksTab.updateFailed"))}finally{r(!1)}},[b,c,n,f,e]),T=i.useCallback(async u=>{var M;r(!0);try{await f(l,u),n.success(e("settings.hooksTab.modeUpdated",{mode:((M=d.find(j=>j.value===u))==null?void 0:M.label)??u})),await b()}catch(j){n.error(j instanceof Error?j.message:e("settings.hooksTab.modeUpdateFailed"))}finally{r(!1)}},[l,b,d,n,f,e]);return i.useEffect(()=>{b()},[b]),t.jsxs($,{vertical:!0,gap:s.marginLG,children:[a,t.jsx(F,{size:"small",loading:o,children:t.jsxs($,{vertical:!0,gap:s.marginXS,children:[t.jsx(ns,{strong:!0,children:e("settings.hooksTab.title")}),t.jsxs($,{align:"center",justify:"space-between",children:[t.jsx(ns,{children:e("settings.hooksTab.enableImagePreflight")}),t.jsx(ge,{checked:l,onChange:v})]}),t.jsxs($,{align:"center",justify:"space-between",children:[t.jsx(ns,{children:e("settings.hooksTab.modeLabel")}),t.jsx(ae,{style:{width:180},value:c,options:d,onChange:T,disabled:!l})]}),t.jsx(ns,{type:"secondary",style:{fontSize:s.fontSizeSM},children:e("settings.hooksTab.description")})]})})]})},{Text:je}=le,Xe=Is.getInstance();function Io(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 Fo=[{label:te.t("settings.schedulesTab.weekdays.mon"),value:"mon"},{label:te.t("settings.schedulesTab.weekdays.tue"),value:"tue"},{label:te.t("settings.schedulesTab.weekdays.wed"),value:"wed"},{label:te.t("settings.schedulesTab.weekdays.thu"),value:"thu"},{label:te.t("settings.schedulesTab.weekdays.fri"),value:"fri"},{label:te.t("settings.schedulesTab.weekdays.sat"),value:"sat"},{label:te.t("settings.schedulesTab.weekdays.sun"),value:"sun"}];function ve(e){return String(e??"").trim()||void 0}function Ro(e){return(e==null?void 0:e.type)==="interval"?e.every_seconds:null}function zn(e){return{type:"interval",every_seconds:e}}function Ao(e){switch(e.type){case"interval":return te.t("settings.schedulesTab.triggerLabels.interval",{type:te.t("settings.schedulesTab.triggerTypes.interval"),seconds:e.every_seconds});case"daily":return te.t("settings.schedulesTab.triggerLabels.daily",{type:te.t("settings.schedulesTab.triggerTypes.daily"),time:`${String(e.hour).padStart(2,"0")}:${String(e.minute).padStart(2,"0")}`});case"weekly":return te.t("settings.schedulesTab.triggerLabels.weekly",{type:te.t("settings.schedulesTab.triggerTypes.weekly"),weekdays:e.weekdays.join(", ")});case"monthly":return te.t("settings.schedulesTab.triggerLabels.monthly",{type:te.t("settings.schedulesTab.triggerTypes.monthly"),days:e.days.join(", ")});case"cron":return te.t("settings.schedulesTab.triggerLabels.cron",{type:te.t("settings.schedulesTab.triggerTypes.cron"),expr:e.expr})}}function Lo(e){switch(e==null?void 0:e.type){case"skip":return te.t("settings.schedulesTab.misfirePolicyOptions.skip");case"catch_up_all":return te.t("settings.schedulesTab.misfirePolicyOptions.catchUpAll");case"catch_up_window":return te.t("settings.schedulesTab.misfirePolicyOptions.catchUpWindow");case"run_once":default:return te.t("settings.schedulesTab.misfirePolicyOptions.runOnce")}}function zo(e){switch(e){case"allow":return te.t("settings.schedulesTab.overlapPolicyOptions.allow");case"skip":return te.t("settings.schedulesTab.overlapPolicyOptions.skip");case"queue_one":default:return te.t("settings.schedulesTab.overlapPolicyOptions.queueOne")}}function Oo(e){var s;return(s=e.state)!=null&&s.next_fire_at?String(e.state.next_fire_at):"-"}function No(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 Vo(e){var s,n,a,o;return((s=e.state)==null?void 0:s.running_run_count)>0?{color:"processing",label:te.t("settings.schedulesTab.statusLabels.running"),detail:te.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:te.t("settings.schedulesTab.statusLabels.queued"),detail:te.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:te.t("settings.schedulesTab.statusLabels.failing"),detail:te.t("settings.schedulesTab.statusDetails.consecutiveFailures",{count:e.state.consecutive_failures})}:e.enabled?(o=e.state)!=null&&o.last_success_at?{color:"success",label:te.t("settings.schedulesTab.statusLabels.healthy"),detail:te.t("settings.schedulesTab.statusDetails.lastRunSucceeded")}:{color:"default",label:te.t("settings.schedulesTab.statusLabels.idle")}:{color:"default",label:te.t("settings.schedulesTab.statusLabels.disabled")}}function $o(e){const s=ve(e);if(!s)return{days:[],invalid:!1};const a=s.split(/[\s,]+/).filter(Boolean).map(l=>Number(l)),o=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:o}}function yn(e){switch(e.trigger_type){case"interval":{const s=Number(e.interval_seconds||0);return s<=0?{errorKey:"settings.schedulesTab.validation.intervalRequired"}:{trigger:zn(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}=$o(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,o=e.monthly_minute;return a==null||o==null?{errorKey:"settings.schedulesTab.validation.triggerRequired"}:{trigger:{type:"monthly",days:s,hour:a,minute:o,second:0}}}case"cron":{const s=ve(e.cron_expr);return s?{trigger:{type:"cron",expr:s}}:{errorKey:"settings.schedulesTab.validation.cronRequired"}}default:return{errorKey:"settings.schedulesTab.validation.triggerRequired"}}}function xn(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"}}}function qo(e){var n,a,o,r,l,m,c,p;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:((o=e.run_config)==null?void 0:o.task_message)||"",model:((r=e.run_config)==null?void 0:r.model)||"",workspace_path:((l=e.run_config)==null?void 0:l.workspace_path)||"",enhance_prompt:((m=e.run_config)==null?void 0:m.enhance_prompt)||"",auto_execute:!!((c=e.run_config)!=null&&c.auto_execute)};switch(((p=e.misfire_policy)==null?void 0:p.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 Bo(){const{t:e}=Z(),[s,n]=Tt.useMessage(),[a,o]=i.useState(!1),[r,l]=i.useState([]),[m,c]=i.useState({open:!1,scheduleId:null,sessions:[],loading:!1}),[p,d]=i.useState({open:!1,scheduleId:null,runs:[],loading:!1}),[b,f]=i.useState({open:!1,schedule:null,saving:!1}),v=Cs(h=>h.close),[T]=k.useForm(),[u]=k.useForm(),M=k.useWatch("trigger_type",T),j=k.useWatch("misfire_policy",T),x=k.useWatch("trigger_type",u),E=k.useWatch("misfire_policy",u),S=i.useCallback(async()=>{o(!0);try{const h=await Xe.listSchedules();l(h.schedules||[])}catch(h){console.error("[Schedules] Failed to load schedules:",h),s.error(e("settings.schedulesTab.loadFailed"))}finally{o(!1)}},[s,e]);i.useEffect(()=>{S()},[S]);const P=[{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")}],ee=[{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")}],R=[{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")}],q=(h,y)=>t.jsxs(t.Fragment,{children:[t.jsxs($,{gap:12,wrap:"wrap",children:[t.jsx(k.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(U,{})}),t.jsx(k.Item,{label:e("settings.schedulesTab.form.triggerType"),name:"trigger_type",rules:[{required:!0,message:e("settings.schedulesTab.validation.triggerRequired")}],style:{width:220},children:t.jsx(ae,{options:P})}),t.jsx(k.Item,{label:e("settings.schedulesTab.form.enabled"),name:"enabled",valuePropName:"checked",style:{width:120},children:t.jsx(ge,{})})]}),h==="interval"?t.jsx(k.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(he,{min:1,style:{width:"100%"}})}):null,h==="daily"?t.jsxs($,{gap:12,wrap:"wrap",children:[t.jsx(k.Item,{label:e("settings.schedulesTab.form.dailyHour"),name:"daily_hour",style:{width:180},children:t.jsx(he,{min:0,max:23,style:{width:"100%"}})}),t.jsx(k.Item,{label:e("settings.schedulesTab.form.dailyMinute"),name:"daily_minute",style:{width:180},children:t.jsx(he,{min:0,max:59,style:{width:"100%"}})})]}):null,h==="weekly"?t.jsxs(t.Fragment,{children:[t.jsx(k.Item,{label:e("settings.schedulesTab.form.weeklyWeekdays"),name:"weekly_weekdays",style:{minWidth:320},children:t.jsx(ae,{mode:"multiple",options:Fo})}),t.jsxs($,{gap:12,wrap:"wrap",children:[t.jsx(k.Item,{label:e("settings.schedulesTab.form.dailyHour"),name:"weekly_hour",style:{width:180},children:t.jsx(he,{min:0,max:23,style:{width:"100%"}})}),t.jsx(k.Item,{label:e("settings.schedulesTab.form.dailyMinute"),name:"weekly_minute",style:{width:180},children:t.jsx(he,{min:0,max:59,style:{width:"100%"}})})]})]}):null,h==="monthly"?t.jsxs(t.Fragment,{children:[t.jsx(k.Item,{label:e("settings.schedulesTab.form.monthlyDays"),name:"monthly_days",style:{minWidth:320},children:t.jsx(U,{placeholder:e("settings.schedulesTab.form.monthlyDaysPlaceholder")})}),t.jsxs($,{gap:12,wrap:"wrap",children:[t.jsx(k.Item,{label:e("settings.schedulesTab.form.dailyHour"),name:"monthly_hour",style:{width:180},children:t.jsx(he,{min:0,max:23,style:{width:"100%"}})}),t.jsx(k.Item,{label:e("settings.schedulesTab.form.dailyMinute"),name:"monthly_minute",style:{width:180},children:t.jsx(he,{min:0,max:59,style:{width:"100%"}})})]})]}):null,h==="cron"?t.jsx(k.Item,{label:e("settings.schedulesTab.form.cronExpr"),name:"cron_expr",children:t.jsx(U,{placeholder:e("settings.schedulesTab.form.cronExprPlaceholder")})}):null,t.jsxs($,{gap:12,wrap:"wrap",children:[t.jsx(k.Item,{label:e("settings.schedulesTab.form.timezone"),name:"timezone",style:{flex:"1 1 240px"},children:t.jsx(U,{placeholder:e("settings.schedulesTab.form.timezonePlaceholder")})}),t.jsx(k.Item,{label:e("settings.schedulesTab.form.startAt"),name:"start_at",style:{flex:"1 1 240px"},children:t.jsx(U,{placeholder:e("settings.schedulesTab.form.datetimePlaceholder")})}),t.jsx(k.Item,{label:e("settings.schedulesTab.form.endAt"),name:"end_at",style:{flex:"1 1 240px"},children:t.jsx(U,{placeholder:e("settings.schedulesTab.form.datetimePlaceholder")})})]}),t.jsxs($,{gap:12,wrap:"wrap",children:[t.jsx(k.Item,{label:e("settings.schedulesTab.form.misfirePolicy"),name:"misfire_policy",style:{flex:"1 1 240px"},children:t.jsx(ae,{options:ee})}),t.jsx(k.Item,{label:e("settings.schedulesTab.form.overlapPolicy"),name:"overlap_policy",style:{flex:"1 1 240px"},children:t.jsx(ae,{options:R})})]}),y==="catch_up_window"?t.jsxs($,{gap:12,wrap:"wrap",children:[t.jsx(k.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxRuns"),name:"catch_up_window_max_runs",style:{width:220},children:t.jsx(he,{min:1,style:{width:"100%"}})}),t.jsx(k.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxLatenessSeconds"),name:"catch_up_window_max_lateness_seconds",style:{width:260},children:t.jsx(he,{min:1,style:{width:"100%"}})})]}):null,t.jsx(k.Item,{label:e("settings.schedulesTab.form.taskMessage"),name:"task_message",children:t.jsx(U.TextArea,{rows:3,placeholder:e("settings.schedulesTab.form.taskMessagePlaceholder")})}),t.jsx(k.Item,{label:e("settings.schedulesTab.form.systemPrompt"),name:"system_prompt",children:t.jsx(U.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})}),t.jsxs($,{gap:12,wrap:"wrap",children:[t.jsx(k.Item,{label:e("settings.schedulesTab.form.model"),name:"model",style:{flex:"1 1 240px"},children:t.jsx(U,{placeholder:e("settings.schedulesTab.form.modelPlaceholder")})}),t.jsx(k.Item,{label:e("settings.schedulesTab.form.workspacePath"),name:"workspace_path",style:{flex:"1 1 320px"},children:t.jsx(U,{placeholder:e("settings.schedulesTab.optional")})}),t.jsx(k.Item,{label:e("settings.schedulesTab.form.autoExecute"),name:"auto_execute",valuePropName:"checked",style:{width:160},children:t.jsx(ge,{})})]}),t.jsx(k.Item,{label:e("settings.schedulesTab.form.enhancePrompt"),name:"enhance_prompt",children:t.jsx(U.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})})]}),G=i.useMemo(()=>[{title:e("settings.schedulesTab.columns.name"),key:"name",render:(h,y)=>t.jsxs($,{vertical:!0,gap:6,children:[t.jsx(je,{strong:!0,children:y.name}),t.jsxs($,{gap:6,wrap:"wrap",children:[t.jsx(ue,{children:Ao(y.trigger)}),y.timezone?t.jsx(ue,{color:"blue",children:y.timezone}):null,t.jsx(ue,{children:Lo(y.misfire_policy)}),t.jsx(ue,{children:zo(y.overlap_policy)})]})]})},{title:e("settings.schedulesTab.columns.status"),key:"status",render:(h,y)=>{const D=Vo(y);return t.jsxs($,{vertical:!0,gap:4,children:[t.jsx(ue,{color:D.color,children:D.label}),D.detail?t.jsx(je,{type:"secondary",children:D.detail}):null]})}},{title:e("settings.schedulesTab.columns.activity"),key:"activity",render:(h,y)=>{var D,_,O,X;return t.jsxs($,{vertical:!0,gap:2,children:[t.jsx(je,{type:"secondary",children:e("settings.schedulesTab.activityLabels.queued",{count:((D=y.state)==null?void 0:D.queued_run_count)??0})}),t.jsx(je,{type:"secondary",children:e("settings.schedulesTab.activityLabels.running",{count:((_=y.state)==null?void 0:_.running_run_count)??0})}),t.jsx(je,{type:"secondary",children:e("settings.schedulesTab.activityLabels.ok",{count:((O=y.state)==null?void 0:O.total_success_count)??0})}),t.jsx(je,{type:"secondary",children:e("settings.schedulesTab.activityLabels.fail",{count:((X=y.state)==null?void 0:X.total_failure_count)??0})})]})}},{title:e("settings.schedulesTab.columns.nextRun"),key:"next_run_at",render:(h,y)=>t.jsx(je,{type:"secondary",children:Oo(y)})},{title:e("settings.schedulesTab.columns.lastRun"),key:"last_run_at",render:(h,y)=>t.jsx(je,{type:"secondary",children:No(y)})},{title:e("settings.schedulesTab.columns.autoExecute"),key:"auto_execute",render:(h,y)=>{var D,_;return t.jsx(je,{type:(D=y.run_config)!=null&&D.auto_execute?void 0:"secondary",children:(_=y.run_config)!=null&&_.auto_execute?e("settings.schedulesTab.yes"):e("settings.schedulesTab.no")})}},{title:e("settings.schedulesTab.columns.model"),key:"model",render:(h,y)=>{var D;return t.jsx(je,{type:"secondary",children:(D=y.run_config)!=null&&D.model?String(y.run_config.model):"-"})}},{title:e("settings.schedulesTab.columns.enabled"),key:"enabled",render:(h,y)=>t.jsx(ge,{checked:y.enabled,onChange:async D=>{try{await Xe.patchSchedule(y.id,{enabled:D}),await S()}catch(_){console.error("[Schedules] Failed to toggle:",_),s.error(e("settings.schedulesTab.updateFailed"))}}})},{title:e("settings.schedulesTab.columns.actions"),key:"actions",render:(h,y)=>{const D=t.jsx(he,{min:1,value:Ro(y.trigger)??void 0,disabled:y.trigger.type!=="interval",onChange:async _=>{const O=typeof _=="number"?_:null;if(!(!O||O<=0))try{await Xe.patchSchedule(y.id,{trigger:zn(O)}),await S()}catch(X){console.error("[Schedules] Failed to patch interval:",X),s.error(e("settings.schedulesTab.updateFailed"))}}});return t.jsxs($,{vertical:!0,gap:8,children:[t.jsxs($,{gap:8,wrap:"wrap",children:[t.jsx(z,{size:"small",onClick:()=>{f({open:!0,schedule:y,saving:!1}),u.setFieldsValue(qo(y))},children:e("settings.schedulesTab.actions.edit")}),t.jsx(z,{size:"small",onClick:async()=>{try{await Xe.runScheduleNow(y.id),s.success(e("settings.schedulesTab.enqueuedRun")),await S()}catch(_){console.error("[Schedules] Failed to run now:",_),s.error(e("settings.schedulesTab.runNowFailed"))}},children:e("settings.schedulesTab.actions.runNow")}),t.jsx(z,{size:"small",onClick:async()=>{c(_=>({..._,open:!0,scheduleId:y.id,loading:!0,sessions:[]}));try{const _=await Xe.listScheduleSessions(y.id);c(O=>({...O,open:!0,scheduleId:y.id,loading:!1,sessions:(_.sessions||[]).map(X=>({id:X.id,title:X.title,updated_at:X.updated_at}))}))}catch(_){console.error("[Schedules] Failed to list sessions:",_),s.error(e("settings.schedulesTab.loadSessionsFailed")),c(O=>({...O,loading:!1}))}},children:e("settings.schedulesTab.actions.sessions")}),t.jsx(z,{size:"small",onClick:async()=>{d(_=>({..._,open:!0,scheduleId:y.id,loading:!0,runs:[]}));try{const _=await Xe.listScheduleRuns(y.id);d(O=>({...O,open:!0,scheduleId:y.id,loading:!1,runs:_.runs||[]}))}catch(_){console.error("[Schedules] Failed to list runs:",_),s.error(e("settings.schedulesTab.loadRunsFailed")),d(O=>({...O,loading:!1}))}},children:e("settings.schedulesTab.actions.runs")}),t.jsx(z,{danger:!0,size:"small",onClick:async()=>{try{await Xe.deleteSchedule(y.id),s.success(e("settings.schedulesTab.deleted")),await S()}catch(_){console.error("[Schedules] Failed to delete:",_),s.error(e("settings.schedulesTab.deleteFailed"))}},children:e("settings.schedulesTab.actions.delete")})]}),t.jsxs($,{gap:8,align:"center",wrap:"wrap",children:[t.jsx(je,{type:"secondary",children:e("settings.schedulesTab.columns.intervalSeconds")}),y.trigger.type==="interval"?D:t.jsx(xe,{title:e("settings.schedulesTab.nonIntervalReadOnly"),children:t.jsx("span",{children:D})})]})]})}}],[u,s,S,e]);return t.jsxs($,{vertical:!0,gap:16,children:[n,t.jsx(F,{title:e("settings.schedulesTab.createTitle"),className:"lotus-settings-card",children:t.jsxs(k,{form:T,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 h=>{try{const y=!!h.auto_execute,D=ve(h.task_message),_=ve(h.model);if(y&&!D){s.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:O,errorKey:X}=yn(h);if(!O){s.error(e(X||"settings.schedulesTab.validation.triggerRequired"));return}await Xe.createSchedule({name:String(h.name||"").trim(),trigger:O,timezone:ve(h.timezone),start_at:ve(h.start_at),end_at:ve(h.end_at),misfire_policy:xn(h),overlap_policy:h.overlap_policy,enabled:!!h.enabled,run_config:{system_prompt:ve(h.system_prompt),task_message:D,model:_,workspace_path:ve(h.workspace_path),enhance_prompt:ve(h.enhance_prompt),auto_execute:y}}),s.success(e("settings.schedulesTab.created")),T.resetFields(),await S()}catch(y){console.error("[Schedules] Failed to create schedule:",y),s.error(e("settings.schedulesTab.createFailed"))}},children:[q(M,j),t.jsx(z,{type:"primary",htmlType:"submit",children:e("settings.schedulesTab.actions.create")})]})}),t.jsx(F,{title:e("settings.schedulesTab.listTitle"),className:"lotus-settings-card",extra:t.jsx(z,{onClick:()=>void S(),loading:a,children:e("settings.schedulesTab.actions.refresh")}),children:t.jsx(et,{rowKey:"id",columns:G,dataSource:r,loading:a,pagination:{pageSize:10},scroll:{x:1500}})}),t.jsx(ot,{title:e("settings.schedulesTab.scheduleSessionsTitle"),open:m.open,onCancel:()=>c(h=>({...h,open:!1,scheduleId:null})),footer:null,children:m.loading?t.jsx(je,{type:"secondary",children:e("settings.schedulesTab.loading")}):t.jsx($,{vertical:!0,gap:8,children:m.sessions.length===0?t.jsx(je,{type:"secondary",children:e("settings.schedulesTab.noSessionsYet")}):m.sessions.map(h=>t.jsxs($,{justify:"space-between",align:"center",children:[t.jsxs($,{vertical:!0,style:{minWidth:0},children:[t.jsx(je,{strong:!0,ellipsis:!0,children:h.title}),t.jsxs(je,{type:"secondary",ellipsis:!0,children:[h.id," • ",h.updated_at]})]}),t.jsx(z,{size:"small",onClick:()=>{Xn(h.id,{forceRefreshIndex:!0,forceLoadHistory:!0,subscribeIfRunning:!0,forceSubscribe:!0}),v()},children:e("settings.schedulesTab.actions.open")})]},h.id))})}),t.jsx(ot,{title:e("settings.schedulesTab.scheduleRunsTitle"),open:p.open,onCancel:()=>d(h=>({...h,open:!1,scheduleId:null})),footer:null,width:960,children:p.loading?t.jsx(je,{type:"secondary",children:e("settings.schedulesTab.loading")}):p.runs.length===0?t.jsx(je,{type:"secondary",children:e("settings.schedulesTab.noRunsYet")}):t.jsx(et,{rowKey:"run_id",pagination:{pageSize:8},dataSource:p.runs,columns:[{title:e("settings.schedulesTab.runHistory.columns.status"),key:"status",render:(h,y)=>t.jsx(ue,{color:Io(y.status),children:y.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:(h,y)=>y.started_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.completedAt"),key:"completed_at",render:(h,y)=>y.completed_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.session"),key:"session_id",render:(h,y)=>y.session_id||"-"},{title:e("settings.schedulesTab.runHistory.columns.duration"),key:"execution_duration_ms",render:(h,y)=>y.execution_duration_ms!=null?`${y.execution_duration_ms}ms`:"-"},{title:e("settings.schedulesTab.runHistory.columns.outcome"),key:"outcome_reason",render:(h,y)=>y.outcome_reason||(y.was_catch_up?"catch-up":"-")}]})}),t.jsx(ot,{title:e("settings.schedulesTab.editTitle"),open:b.open,onCancel:()=>f({open:!1,schedule:null,saving:!1}),okText:e("settings.schedulesTab.actions.save"),confirmLoading:b.saving,onOk:()=>u.submit(),forceRender:!0,children:t.jsx(k,{form:u,layout:"vertical",onFinish:async h=>{const y=b.schedule;if(!y)return;const D=!!h.auto_execute,_=ve(h.task_message),O=ve(h.model);if(D&&!_){s.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:X,errorKey:A}=yn(h);if(!X){s.error(e(A||"settings.schedulesTab.validation.triggerRequired"));return}f(H=>({...H,saving:!0}));try{await Xe.patchSchedule(y.id,{name:String(h.name||"").trim()||void 0,enabled:!!h.enabled,trigger:X,timezone:ve(h.timezone),start_at:ve(h.start_at),end_at:ve(h.end_at),misfire_policy:xn(h),overlap_policy:h.overlap_policy,run_config:{system_prompt:ve(h.system_prompt),task_message:_,model:O,workspace_path:ve(h.workspace_path),enhance_prompt:ve(h.enhance_prompt),auto_execute:D}}),s.success(e("settings.schedulesTab.updated")),f({open:!1,schedule:null,saving:!1}),await S()}catch(H){console.error("[Schedules] Failed to patch schedule:",H),s.error(e("settings.schedulesTab.updateFailed")),f(V=>({...V,saving:!1}))}},children:q(x,E)})})]})}const{Text:Lt}=le,zt=Is.getInstance();function Uo(){const{t:e}=Z(),{modal:s,message:n}=Wt.useApp(),a=Re(T=>T.chats),o=Re(T=>T.currentSessionId),r=Re(T=>T.refreshChats),l=Re(T=>T.loadChats),m=Re(T=>T.loadChatHistory),[c,p]=i.useState(!0),[d,b]=i.useState(!1),f=i.useMemo(()=>o?a.find(T=>T.id===o)??null:null,[a,o]),v=async T=>{if(!d){b(!0);try{await T()}finally{b(!1)}}};return t.jsxs($,{vertical:!0,gap:16,children:[t.jsx(F,{size:"small",title:e("settings.sessionsTab.currentSessionTitle"),children:f?t.jsxs($,{vertical:!0,gap:4,children:[t.jsx(Lt,{strong:!0,ellipsis:!0,children:f.title}),t.jsxs(Lt,{type:"secondary",ellipsis:!0,children:[e("settings.sessionsTab.id"),": ",f.id," ","•"," ",e("settings.sessionsTab.kind"),": ",f.kind]}),t.jsx($,{gap:8,wrap:"wrap",style:{marginTop:8},children:t.jsx(z,{danger:!0,loading:d,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 v(async()=>{await zt.clearSession(f.id),await m(f.id),await r(),n.success(e("settings.sessionsTab.sessionCleared"))})}})},children:e("settings.sessionsTab.clearMessages")})})]}):t.jsx(Lt,{type:"secondary",children:e("settings.sessionsTab.noActiveSession")})}),t.jsxs(F,{size:"small",title:e("settings.sessionsTab.bulkCleanupTitle"),children:[t.jsxs($,{align:"center",gap:8,style:{marginBottom:12},children:[t.jsx(Lt,{children:e("settings.sessionsTab.keepPinned")}),t.jsx(ge,{checked:c,onChange:p})]}),t.jsxs($,{gap:8,wrap:"wrap",children:[t.jsx(z,{danger:!0,loading:d,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 v(async()=>{await zt.cleanupSessions("all",c),await l(),n.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteAll")}),t.jsx(z,{danger:!0,loading:d,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 v(async()=>{await zt.cleanupSessions("empty",c),await l(),n.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteEmpty")}),t.jsx(z,{danger:!0,loading:d,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 v(async()=>{await zt.cleanupSessions("children",c),await l(),n.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteChildren")})]})]}),t.jsxs(F,{size:"small",title:e("settings.sessionsTab.devResetTitle"),children:[t.jsx(Lt,{type:"secondary",children:e("settings.sessionsTab.devResetDescription")}),t.jsx($,{style:{marginTop:12},children:t.jsx(z,{danger:!0,type:"primary",loading:d,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 v(async()=>{await zt.devResetSessions(),await l(),n.success(e("settings.sessionsTab.devResetDone"))})}})},children:e("settings.sessionsTab.devResetAction")})})]})]})}const{Text:Ye}=le,{useToken:Ho}=fe,Ko=()=>{const{t:e}=Z(),{token:s}=Ho(),[n,a]=i.useState(Bs()),o=Yn(),r=(l,m)=>{const c={...n,[l]:m};a(c),Zn({[l]:m})};return i.useEffect(()=>{a(Bs())},[]),t.jsx(F,{size:"small",className:"lotus-settings-card",children:t.jsxs($,{vertical:!0,gap:s.marginMD,children:[!o&&t.jsx(ke,{type:"info",showIcon:!0,message:e("settings.notificationsTab.desktopOnly","Desktop notifications are only available in the Bodhi desktop app.")}),t.jsxs($,{align:"center",gap:s.marginSM,children:[t.jsx(xa,{}),t.jsx(Ye,{strong:!0,children:e("settings.notificationsTab.title","Desktop Notifications")})]}),t.jsx(Ye,{type:"secondary",style:{fontSize:s.fontSizeSM},children:e("settings.notificationsTab.description","Receive OS-level notifications when the app is in the background and user action is required.")}),t.jsx(Pe,{style:{margin:`${s.marginXS}px 0`}}),t.jsxs($,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(Ye,{children:e("settings.notificationsTab.enabled","Enable desktop notifications")}),t.jsx(ge,{"data-testid":"notification-enabled-toggle",checked:n.enabled,onChange:l=>r("enabled",l),disabled:!o})]}),t.jsx(Pe,{style:{margin:`${s.marginXS}px 0`}}),t.jsx(Ye,{strong:!0,style:{fontSize:s.fontSizeSM,opacity:n.enabled?1:.5},children:e("settings.notificationsTab.events","Notify when:")}),t.jsxs($,{vertical:!0,gap:s.marginSM,style:{opacity:n.enabled?1:.5,pointerEvents:n.enabled?"auto":"none"},children:[t.jsxs($,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(Ye,{children:e("settings.notificationsTab.onClarification","Agent needs clarification")}),t.jsx(ge,{"data-testid":"notification-clarification-toggle",checked:n.onClarification,onChange:l=>r("onClarification",l),disabled:!o})]}),t.jsxs($,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(Ye,{children:e("settings.notificationsTab.onToolApproval","Tool execution needs approval")}),t.jsx(ge,{"data-testid":"notification-tool-approval-toggle",checked:n.onToolApproval,onChange:l=>r("onToolApproval",l),disabled:!o})]}),t.jsxs($,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(Ye,{children:e("settings.notificationsTab.onContextPressure","Context window is critically full")}),t.jsx(ge,{"data-testid":"notification-context-pressure-toggle",checked:n.onContextPressure,onChange:l=>r("onContextPressure",l),disabled:!o})]}),t.jsxs($,{align:"center",justify:"space-between",gap:s.marginSM,children:[t.jsx(Ye,{children:e("settings.notificationsTab.onSubAgentComplete","Background task completes")}),t.jsx(ge,{"data-testid":"notification-subagent-complete-toggle",checked:n.onSubAgentComplete,onChange:l=>r("onSubAgentComplete",l),disabled:!o})]})]}),t.jsx(Pe,{style:{margin:`${s.marginXS}px 0`}}),t.jsxs($,{align:"center",gap:s.marginSM,children:[t.jsx(ba,{style:{color:s.colorPrimary}}),t.jsx(Ye,{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:as,Paragraph:Wo}=le,Go=({open:e,onCancel:s,onComplete:n,onCopyCode:a,completingAuth:o,copiedUserCode:r,deviceCodeInfo:l,timeRemaining:m,token:c})=>{const{t:p}=Z();return t.jsx(ot,{title:p("settings.providerTab.copilotAuthModalTitle"),open:e,onCancel:s,footer:[t.jsx(z,{onClick:s,children:p("settings.providerTab.cancel")},"cancel"),t.jsx(z,{type:"primary",onClick:n,loading:o,children:p("settings.providerTab.completedAuthorization")},"complete")],children:l&&t.jsxs(I,{direction:"vertical",size:"large",style:{width:"100%"},children:[t.jsx(ke,{message:p("settings.providerTab.browserOpened"),description:t.jsxs("ol",{children:[t.jsx("li",{children:p("settings.providerTab.authStep1")}),t.jsx("li",{children:p("settings.providerTab.authStep2")}),t.jsx("li",{children:p("settings.providerTab.authStep3")})]}),type:"info"}),t.jsx(F,{size:"small",className:"lotus-settings-card",children:t.jsxs(I,{direction:"vertical",style:{width:"100%"},children:[t.jsx(as,{type:"secondary",children:p("settings.providerTab.visitUrl")}),t.jsx(I,{children:t.jsx(as,{copyable:{text:l.verification_uri},children:l.verification_uri})})]})}),t.jsx(F,{style:{textAlign:"center",background:c.colorFillTertiary,borderColor:c.colorBorderSecondary},children:t.jsxs(I,{direction:"vertical",style:{width:"100%"},children:[t.jsx(as,{type:"secondary",children:p("settings.providerTab.enterCode")}),t.jsxs(I,{children:[t.jsx(as,{style:{color:c.colorText,fontSize:"32px",fontFamily:"monospace",fontWeight:"bold",letterSpacing:"4px"},children:l.user_code}),t.jsx(z,{icon:r?t.jsx(Ms,{}):t.jsx(En,{}),onClick:a,type:r?"default":"primary",children:p(r?"settings.providerTab.copied":"settings.providerTab.copyCode")})]}),t.jsx("div",{style:{marginTop:8},children:t.jsxs(ue,{color:m<60?"error":m<180?"warning":"success",children:[t.jsx(va,{style:{marginRight:4}}),"Expires in ",Math.floor(m/60),":",(m%60).toString().padStart(2,"0")]})})]})}),t.jsx(Wo,{type:"secondary",children:p("settings.providerTab.afterContinueHint")})]})})},{Password:bn}=U,{Text:He,Paragraph:_s}=le,rs=["openai","anthropic","gemini","copilot","bodhi"],os=()=>null,Jo=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()))},Xo=(e,s,n)=>{const a=e;a[s]={...a[s]??{},model:n}},vn=e=>t.jsxs(I,{direction:"vertical",size:4,children:[t.jsxs(He,{type:"secondary",children:[e("settings.providerTab.responsesOnlyHelp1")," ",t.jsx(He,{code:!0,children:"/responses"}),"."]}),t.jsx(He,{type:"secondary",children:e("settings.providerTab.responsesOnlyHelp2")})]}),Yo=["low","medium","high","xhigh","max"],xt=(e,s)=>t.jsx(ae,{placeholder:e("settings.providerTab.reasoningEffortDefault"),allowClear:!0,value:s==null?void 0:s.value,onChange:s!=null&&s.onChange?n=>{var a;return(a=s.onChange)==null?void 0:a.call(s,n??void 0)}:void 0,disabled:s==null?void 0:s.disabled,size:s==null?void 0:s.size,style:s==null?void 0:s.style,"data-testid":s==null?void 0:s["data-testid"],children:Yo.map(n=>t.jsx(ae.Option,{value:n,children:e(`chat.input.reasoning.${n}`)},n))}),Zo=()=>{const{t:e}=Z(),{token:s}=fe.useToken(),{message:n}=Wt.useApp(),[a]=k.useForm(),[o,r]=i.useState(!1),[l,m]=i.useState(!1),[c,p]=i.useState("copilot"),[d,b]=i.useState(!1),[f,v]=i.useState(null),[T,u]=i.useState(!1),[M,j]=i.useState(!1),[x,E]=i.useState(null),[S,P]=i.useState(!1),[ee,R]=i.useState(!1),[q,G]=i.useState(0),[h,y]=i.useState(!1),[D,_]=i.useState([]),[O,X]=i.useState(!1),[A,H]=i.useState("idle"),[V,oe]=i.useState(null);i.useEffect(()=>{if(A!=="success")return;const C=setTimeout(()=>{H("idle"),oe(null)},2e3);return()=>clearTimeout(C)},[A]),i.useEffect(()=>{if(!S||!x){G(0);return}G(x.expires_in);const C=setInterval(()=>{G(w=>w<=1?(clearInterval(C),0):w-1)},1e3);return()=>clearInterval(C)},[S,x]);const ce=i.useCallback(async()=>{var C;try{r(!0);const w=await $e.getProviderConfig();let J=w.defaults;if(!((C=J==null?void 0:J.chat)!=null&&C.model)&&w.provider&&w.providers){const pe=w.provider,re=w.providers[pe],Ee=re==null?void 0:re.model;Ee&&(J={chat:{provider:pe,model:Ee}})}const B={provider:w.provider,defaults:J,providers:w.providers||{},features:w.features};rt("[Provider]","Loaded provider config:",B);const Y={...B.providers||{}};rs.forEach(pe=>{const re=Y[pe];re&&re.request_overrides&&typeof re.request_overrides=="object"&&(re.request_overrides_json=JSON.stringify(re.request_overrides,null,2))}),p(B.provider),a.setFieldsValue({...B,providers:Y,defaults:B.defaults}),b(!0)}catch(w){n.error(e("settings.providerTab.loadConfigFailed")),console.error("Failed to load provider config:",w)}finally{r(!1)}},[a,n,e]),K=i.useCallback(async()=>{try{const C=await $e.getEnvVars();_(C.entries||[])}catch(C){console.warn("Failed to load env vars for provider overrides:",C)}},[]),L=i.useCallback(async()=>{try{u(!0);const C=await $e.getCopilotAuthStatus();v(C)}catch(C){console.error("Failed to check Copilot auth status:",C),v({authenticated:!1,message:e("settings.providerTab.checkStatusFailed")})}finally{u(!1)}},[e]);i.useEffect(()=>{ce(),K(),$t.getState().loadCatalog(),L()},[ce,K,L]);const W=async()=>{try{j(!0);const C=await $e.startCopilotAuth();E(C),P(!0)}catch(C){n.error(e("settings.providerTab.startCopilotAuthFailed")),console.error("Failed to start Copilot authentication:",C)}finally{j(!1)}},Q=async()=>{if(x)try{R(!0),await $e.completeCopilotAuth({device_code:x.device_code,interval:x.interval||5,expires_in:x.expires_in}),n.success(e("settings.providerTab.copilotAuthSuccess")),P(!1),E(null),await L()}catch(C){n.error(e("settings.providerTab.completeAuthFailed")),console.error("Authentication completion failed:",C)}finally{R(!1)}},se=async()=>{if(x)try{await Mn(x.user_code),y(!0),n.success(e("settings.providerTab.userCodeCopied")),setTimeout(()=>y(!1),2e3)}catch{n.error(`${e("settings.providerTab.copyCodeFailedPrefix")} ${x.user_code}`)}},we=async()=>{try{j(!0),await $e.logoutCopilot(),n.success(e("settings.providerTab.logoutSuccess")),await L()}catch(C){n.error(e("settings.providerTab.logoutFailed")),console.error("Failed to logout:",C)}finally{j(!1)}},qe=i.useCallback(async()=>{X(!0);try{const C=await $e.fetchCatalogModels();await $t.getState().loadCatalog();const w=C.fetched.filter(B=>B.models&&B.models.length>0).length;C.fetched.filter(B=>B.error).length>0?n.warning(e("settings.providerTab.fetchModelsPartialSuccess",{success:w,total:C.fetched.length})):n.success(e("settings.providerTab.fetchModelsSuccess",{count:w}))}catch{n.error(e("settings.providerTab.fetchModelsFailed"))}finally{X(!1)}},[n,e]),Ie=C=>Qn(C)||C instanceof Error?C.message:e("settings.providerTab.unknownError"),kt=C=>{a.setFields([{name:["provider"],errors:[]},{name:["providers",C,"api_key"],errors:[]},{name:["defaults","chat"],errors:[]}])},ft=C=>{const w=C.trim();return w?w.includes(".")?w.split(".").filter(Boolean):w==="provider"?["provider"]:w==="provider/providers"?["provider"]:null:null},wt=(C,w)=>{if(!C.length)return;const J=C.map(B=>{const Y=ft(B.path);return Y?{name:Y,errors:[B.message]}:B.message.toLowerCase().includes("api key")?{name:["providers",w,"api_key"],errors:[B.message]}:{name:["provider"],errors:[B.message]}}).filter((B,Y,pe)=>pe.findIndex(re=>JSON.stringify(re.name)===JSON.stringify(B.name))===Y);J.length&&a.setFields(J)},Ct=async C=>{var J;const w=C.provider||c;kt(w);try{const Y=await qt.getInstance().validateBambooConfigPatch({provider:C.provider,providers:C.providers||{},defaults:C.defaults});if(Y.valid)return{valid:!0};const pe=((J=Y.errors)==null?void 0:J.provider)||[];wt(pe,w);const re=pe[0];return{valid:!1,message:(re==null?void 0:re.message)||e("settings.providerTab.invalidConfig")}}catch(B){return console.warn("Config validation failed, falling back to save:",B),{valid:!0}}},it=async(C,w)=>{var J,B;try{r(!0);const Y={provider:C.provider,defaults:C.defaults,providers:{...C.providers||{}},features:C.features},pe=(J=Y.defaults)==null?void 0:J.chat;if(!Jo(pe)){const Te=e("settings.providerTab.selectModelRequired");if(a.setFields([{name:["defaults","chat"],errors:[Te]}]),(w==null?void 0:w.showMessage)!==!1&&n.error(Te),w!=null&&w.throwOnError)throw new Error(Te);return}const re=Y.providers;for(const Te of rs){const We=re[Te];if(!We)continue;const Et=We.request_overrides_json;if(typeof Et!="string")continue;const Dt=Et.trim();if(!Dt)delete We.request_overrides;else try{We.request_overrides=JSON.parse(Dt)}catch(hs){const st=e("settings.providerTab.invalidRequestOverridesJson",{provider:Te,error:hs.message});if(a.setFields([{name:["providers",Te,"request_overrides_json"],errors:[st]}]),(w==null?void 0:w.showMessage)!==!1&&n.error(st),w!=null&&w.throwOnError)throw hs;return}delete We.request_overrides_json}const Ee={...Y.providers||{}},Ve=Y.provider,De=(B=Y.defaults)==null?void 0:B.chat;De!=null&&De.model&&Ve&&Xo(Ee,Ve,De.model);const Be={provider:Y.provider,defaults:Y.defaults,providers:Ee,features:Y.features},ye=await Ct(Y);if(!ye.valid){const Te=ye.message||e("settings.providerTab.invalidConfig");if((w==null?void 0:w.showMessage)!==!1&&n.error(`${e("settings.providerTab.invalidConfigPrefix")}: ${Te}`),w!=null&&w.throwOnError)throw new Error(Te);return}rt("[Provider]","Saving provider config:",Be),await $e.saveProviderConfig(Be),(w==null?void 0:w.showMessage)!==!1&&n.success(e("settings.providerTab.saveConfigSuccess"))}catch(Y){const pe=Ie(Y);if((w==null?void 0:w.showMessage)!==!1&&n.error(pe?`${e("settings.providerTab.saveConfigErrorPrefix")}: ${pe}`:e("settings.providerTab.saveConfigFailed")),console.error("Failed to save configuration:",Y),w!=null&&w.throwOnError)throw Y}finally{r(!1)}},lt=async C=>{var w,J,B,Y,pe;try{m(!0);const{useProviderStore:re}=await Es(async()=>{const{useProviderStore:st}=await import("./App-DRZhqTnn.js").then(fs=>fs.a8);return{useProviderStore:st}},__vite__mapDeps([4,1,2,3,5,6,7,8]),import.meta.url),{useAppStore:Ee}=await Es(async()=>{const{useAppStore:st}=await import("./App-DRZhqTnn.js").then(fs=>fs.a9);return{useAppStore:st}},__vite__mapDeps([4,1,2,3,5,6,7,8]),import.meta.url),Ve=(w=re.getState().providerConfig.defaults)==null?void 0:w.chat;await re.getState().loadProviderConfig();const De=(J=re.getState().providerConfig.defaults)==null?void 0:J.chat;re.getState().setSelectedModelRef(null);const Be=Ee.getState().currentSessionId,ye=Be&&Ee.getState().chats.find(st=>st.id===Be)||null,Te=Ve?`${Ve.provider}/${Ve.model}`:null,We=De?`${De.provider}/${De.model}`:null,Et=(B=ye==null?void 0:ye.config)!=null&&B.model_ref?`${ye.config.model_ref.provider}/${ye.config.model_ref.model}`:null,Dt=((pe=(Y=ye==null?void 0:ye.config)==null?void 0:Y.model)==null?void 0:pe.trim())||null;!!(Be&&(ye!=null&&ye.config)&&De&&We!==Te&&(!Et||Et===Te)&&(!Dt||Dt===(Ve==null?void 0:Ve.model)))&&Be&&(ye!=null&&ye.config)&&De&&Ee.getState().updateSession(Be,{config:{...ye.config,model:De.model,model_ref:De}}),(C==null?void 0:C.showMessage)!==!1&&n.success(e("settings.providerTab.applyConfigSuccess"))}catch(re){const Ee=Ie(re);if((C==null?void 0:C.showMessage)!==!1&&n.error(Ee?`${e("settings.providerTab.applyConfigErrorPrefix")}: ${Ee}`:e("settings.providerTab.applyConfigFailed")),console.error("Failed to apply configuration:",re),C!=null&&C.throwOnError)throw re}finally{m(!1)}},Le=async C=>{try{const w=a.getFieldsValue(!0);await it(w,{throwOnError:!0}),await lt({throwOnError:!0})}catch{}},Mt=async(C,w)=>{if(!(C==="chat"&&!w)&&A!=="saving"){H("saving"),oe(null);try{const J=a.getFieldsValue(!0),B=J.defaults;if(!(B!=null&&B.chat))throw new Error(e("settings.providerTab.selectModelRequired"));J.defaults={...B,[C]:w},await it(J,{showMessage:!1,throwOnError:!0}),await lt({showMessage:!1,throwOnError:!0}),H("success"),n.success(e("settings.providerTab.modelUpdated"))}catch(J){const B=Ie(J);H("error"),oe(B),n.error(B?`${e("settings.providerTab.updateModelErrorPrefix")}: ${B}`:e("settings.providerTab.updateModelFailed"))}}},g=async()=>{if(A!=="saving"){H("saving"),oe(null);try{const C=a.getFieldsValue(!0);await it(C,{showMessage:!1,throwOnError:!0}),await lt({showMessage:!1,throwOnError:!0}),H("success"),n.success(e("settings.providerTab.reasoningEffortUpdated"))}catch(C){const w=Ie(C);H("error"),oe(w),n.error(w?`${e("settings.providerTab.updateReasoningEffortErrorPrefix")}: ${w}`:e("settings.providerTab.updateReasoningEffortFailed"))}}},ne=(C,w)=>{if(!C)return null;const J=Pt[C],B=a.getFieldValue(["providers",C,"reasoning_effort"]);return t.jsx("div",{style:{marginTop:(w==null?void 0:w.marginTop)??8},children:t.jsxs(I,{direction:"vertical",size:4,style:{width:"100%"},children:[t.jsx(He,{strong:!0,children:(w==null?void 0:w.label)||`${J} · ${e("settings.providerTab.reasoningEffortOptional")}`}),xt(e,{value:B,disabled:A==="saving",size:w==null?void 0:w.size,style:{width:"100%"},"data-testid":w==null?void 0:w.dataTestId,onChange:Y=>{a.setFieldValue(["providers",C,"reasoning_effort"],Y),w!=null&&w.autoSave&&g()}}),t.jsx(He,{type:"secondary",children:(w==null?void 0:w.helperText)||e("settings.providerTab.reasoningEffortHelp")})]})})},de=i.useCallback(C=>{const w=a.getFieldValue(["providers",C]);return w?C==="copilot"?(f==null?void 0:f.authenticated)??!1:!!w.api_key:!1},[a,f]),Ce=()=>{const C=J=>{const B=a.getFieldValue(["defaults",J]);return t.jsx(ea,{value:B,disabled:A==="saving",onChange:Y=>{a.setFieldValue(["defaults",J],Y),Mt(J,Y)}})},w=(J,B,Y)=>t.jsxs("div",{children:[t.jsx(He,{strong:!0,children:B}),t.jsx("div",{style:{marginTop:8},children:C(J)}),t.jsx(k.Item,{noStyle:!0,shouldUpdate:!0,children:()=>{const pe=a.getFieldValue(["defaults",J]),re=pe==null?void 0:pe.provider;return ne(re,{autoSave:!0,dataTestId:`model-preference-${J}-reasoning-effort`,label:re?`${Pt[re]} · ${e("settings.providerTab.reasoningEffortOptional")}`:e("settings.providerTab.reasoningEffortOptional"),helperText:e("settings.providerTab.reasoningEffortHelp")})}}),Y?t.jsx(He,{type:"secondary",children:Y}):null]});return t.jsxs(F,{size:"small",title:e("settings.providerTab.modelPreferences"),style:{marginBottom:16},children:[t.jsx(k.Item,{name:["defaults","chat"],noStyle:!0,preserve:!0,children:t.jsx(os,{})}),t.jsx(k.Item,{name:["defaults","fast"],noStyle:!0,preserve:!0,children:t.jsx(os,{})}),t.jsx(k.Item,{name:["defaults","sub_agent"],noStyle:!0,preserve:!0,children:t.jsx(os,{})}),t.jsx(k.Item,{name:["defaults","vision"],noStyle:!0,preserve:!0,children:t.jsx(os,{})}),t.jsxs(I,{direction:"vertical",size:16,style:{width:"100%"},children:[w("chat",e("settings.providerTab.defaultModel")),w("fast",e("settings.providerTab.fastModel"),e("settings.providerTab.fastModelHelp")),w("sub_agent",e("settings.providerTab.subAgentModel"),e("settings.providerTab.subAgentModelHelp")),w("vision",e("settings.providerTab.visionModel"),e("settings.providerTab.visionModelHelp"))]})]})},me=C=>{const w=D.map(B=>B.name);return t.jsx(k.Item,{name:["providers",C,"request_overrides_json"],label:e("settings.providerTab.advancedRequestOverrides"),extra:t.jsxs(I,{direction:"vertical",size:4,children:[t.jsx(He,{type:"secondary",children:e("settings.providerTab.advancedRequestOverridesHelp")}),t.jsxs(He,{type:"secondary",children:[e("settings.providerTab.envVarInjection")," ",t.jsx(He,{code:!0,children:'{ "type": "env_ref", "name": "YOUR_ENV_NAME" }'})]}),w.length>0&&t.jsx(I,{wrap:!0,size:[6,6],children:w.map(B=>t.jsx(ue,{children:B},B))})]}),children:t.jsx(U.TextArea,{autoSize:{minRows:8,maxRows:20},placeholder:`{
3
3
  "common": {
4
4
  "headers": {
5
5
  "x-request-id": { "type": "generated", "generator": "uuid" },