@bigduu/lotus 2026.4.27 → 2026.4.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{App-CoDj_LmD.js → App-DXATbaBE.js} +7 -7
- package/dist/assets/{_basePickBy-DRDCNu5B.js → _basePickBy-Cx4bs_LU.js} +1 -1
- package/dist/assets/{_baseUniq-KkIHVpdg.js → _baseUniq-BKpLaFrq.js} +1 -1
- package/dist/assets/{architectureDiagram-VXUJARFQ-DGMXpntz.js → architectureDiagram-VXUJARFQ-DRHn_Xp5.js} +1 -1
- package/dist/assets/{blockDiagram-VD42YOAC-Ge0PP86S.js → blockDiagram-VD42YOAC-By0Ha7gb.js} +1 -1
- package/dist/assets/{c4Diagram-YG6GDRKO-DmvX3IoS.js → c4Diagram-YG6GDRKO-BDo4UZEQ.js} +1 -1
- package/dist/assets/{chunk-4BX2VUAB-Cpjts16E.js → chunk-4BX2VUAB-DbYjMO1M.js} +1 -1
- package/dist/assets/{chunk-55IACEB6-C-NupeTy.js → chunk-55IACEB6-CxgcRSOc.js} +1 -1
- package/dist/assets/{chunk-B4BG7PRW-BIhQxNnv.js → chunk-B4BG7PRW-Dcc5NX9p.js} +1 -1
- package/dist/assets/{chunk-DI55MBZ5-BnrY7npQ.js → chunk-DI55MBZ5-B8jxaeQi.js} +1 -1
- package/dist/assets/{chunk-FMBD7UC4-ByFSyTLj.js → chunk-FMBD7UC4-6RDpBPwt.js} +1 -1
- package/dist/assets/{chunk-QN33PNHL-BF4wk24L.js → chunk-QN33PNHL-jUt0YlMf.js} +1 -1
- package/dist/assets/{chunk-QZHKN3VN-DywM2pmV.js → chunk-QZHKN3VN-BT81dIct.js} +1 -1
- package/dist/assets/{chunk-TZMSLE5B-Cerw-8ZM.js → chunk-TZMSLE5B-d6B-0PqH.js} +1 -1
- package/dist/assets/{classDiagram-2ON5EDUG-D-BV_S4s.js → classDiagram-2ON5EDUG-DiPk_WxO.js} +1 -1
- package/dist/assets/{classDiagram-v2-WZHVMYZB-D-BV_S4s.js → classDiagram-v2-WZHVMYZB-DiPk_WxO.js} +1 -1
- package/dist/assets/clone-Cos-A75w.js +1 -0
- package/dist/assets/{cose-bilkent-S5V4N54A-UA--TZ30.js → cose-bilkent-S5V4N54A-DKXMhR49.js} +1 -1
- package/dist/assets/{dagre-6UL2VRFP-Iix4vC9g.js → dagre-6UL2VRFP-CTGHzMDX.js} +1 -1
- package/dist/assets/{diagram-PSM6KHXK-CyWT_ZUM.js → diagram-PSM6KHXK-DxVS21VI.js} +1 -1
- package/dist/assets/{diagram-QEK2KX5R-BpiEbf8H.js → diagram-QEK2KX5R-D_55duo3.js} +1 -1
- package/dist/assets/{diagram-S2PKOQOG-D2Fn-sdm.js → diagram-S2PKOQOG-DBkmOhBZ.js} +1 -1
- package/dist/assets/{erDiagram-Q2GNP2WA-zgO28LyM.js → erDiagram-Q2GNP2WA-BpmG6fvI.js} +1 -1
- package/dist/assets/{flowDiagram-NV44I4VS-BUahh1bs.js → flowDiagram-NV44I4VS-CytQSVJP.js} +1 -1
- package/dist/assets/{ganttDiagram-JELNMOA3-DrUkemqM.js → ganttDiagram-JELNMOA3-BpfpCV_Q.js} +1 -1
- package/dist/assets/{gitGraphDiagram-V2S2FVAM-Bx3mmW1g.js → gitGraphDiagram-V2S2FVAM-BtEhcZ5X.js} +1 -1
- package/dist/assets/{graph-BSJyz3Nw.js → graph-DlYUUt6U.js} +1 -1
- package/dist/assets/{index-BIPq1exu.js → index-33TAS5RK.js} +1 -1
- package/dist/assets/{index-gw2m3pxJ.js → index-BvEtlBh_.js} +1 -1
- package/dist/assets/{index-aEud9Tjx.js → index-eh17wnlp.js} +1 -1
- package/dist/assets/{infoDiagram-HS3SLOUP-PPL8VhXf.js → infoDiagram-HS3SLOUP-OZNreW-h.js} +1 -1
- package/dist/assets/{journeyDiagram-XKPGCS4Q-BcLxCqiC.js → journeyDiagram-XKPGCS4Q-DLKpQ3Q5.js} +1 -1
- package/dist/assets/{kanban-definition-3W4ZIXB7-BOYFqDzp.js → kanban-definition-3W4ZIXB7-8_41ck_Z.js} +1 -1
- package/dist/assets/{layout-33stSYwa.js → layout-BcfJS67p.js} +1 -1
- package/dist/assets/{main-CehMQ1Uh.js → main-YQiM0LtA.js} +2 -2
- package/dist/assets/{mindmap-definition-VGOIOE7T-BmV886Xx.js → mindmap-definition-VGOIOE7T-CkbPwuRb.js} +1 -1
- package/dist/assets/{pieDiagram-ADFJNKIX-DeVsO9Qi.js → pieDiagram-ADFJNKIX-DohelCM7.js} +1 -1
- package/dist/assets/{quadrantDiagram-AYHSOK5B-S89D-PQl.js → quadrantDiagram-AYHSOK5B-VmT8NGJj.js} +1 -1
- package/dist/assets/{requirementDiagram-UZGBJVZJ-B29Rebsh.js → requirementDiagram-UZGBJVZJ-DK-5fl91.js} +1 -1
- package/dist/assets/{sankeyDiagram-TZEHDZUN-DV-oSGaH.js → sankeyDiagram-TZEHDZUN-2ognTyjw.js} +1 -1
- package/dist/assets/{sequenceDiagram-WL72ISMW-CLMnp3Iv.js → sequenceDiagram-WL72ISMW-B6iGnoUK.js} +1 -1
- package/dist/assets/{stateDiagram-FKZM4ZOC-BHcyxCeX.js → stateDiagram-FKZM4ZOC-BecC3rBl.js} +1 -1
- package/dist/assets/{stateDiagram-v2-4FDKWEC3-CxioYP1s.js → stateDiagram-v2-4FDKWEC3-DqESdXsy.js} +1 -1
- package/dist/assets/{timeline-definition-IT6M3QCI-BGYO0PXi.js → timeline-definition-IT6M3QCI-BqdYAvFN.js} +1 -1
- package/dist/assets/{treemap-GDKQZRPO-BDNhT28h.js → treemap-GDKQZRPO-BjtRtT4Z.js} +1 -1
- package/dist/assets/{vendor-mermaid-CrWGhc5e.js → vendor-mermaid-Siz_U5T6.js} +3 -3
- package/dist/assets/{vendor-pdf-DrBG_eov.js → vendor-pdf-CQWTPgH8.js} +2 -2
- package/dist/assets/{xychartDiagram-PRI3JC2R-D6uTSN9b.js → xychartDiagram-PRI3JC2R-BeykaIKC.js} +1 -1
- package/dist/index.html +1 -1
- package/package.json +1 -1
- package/dist/assets/clone-BpS8FZ8E.js +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-
|
|
2
|
-
var Gb=Object.defineProperty;var Jb=(e,t,s)=>t in e?Gb(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var He=(e,t,s)=>Jb(e,typeof t!="symbol"?t+"":t,s);import{j as r,M as hs,r as Ii,h as fr,_ as Dt,S as mt,a as lf,t as cf,p as df,b as Qb,c as Qc,d as Zb,m as uf,s as ex,y as mf,e as hf,f as Zc,g as ed,i as pf}from"./vendor-markdown-DYfLXXRA.js";import{a as m,R as ut,i as es,u as ne,g as vr}from"./vendor-i18n-BNURlJ23.js";import{r as tx,A as sx}from"./main-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-BvEtlBh_.js","./vendor-markdown-DYfLXXRA.js","./vendor-i18n-BNURlJ23.js","./vendor-antd-DzhFcYgt.js","./main-YQiM0LtA.js","./main-B6snAd4S.css","./vendor-charts-BvOlsian.js","./vendor-mermaid-Siz_U5T6.js","./index-CYeT_vWc.js","./index-33TAS5RK.js","./index-Bi-vGirQ.css","./index-eh17wnlp.js","./index-B9rhKJTy.js","./index-BmjFP0ha.js","./core-Cfh-QHsP.js","./index-_XI0Qq6F.js","./vendor-pdf-CQWTPgH8.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var Gb=Object.defineProperty;var Jb=(e,t,s)=>t in e?Gb(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var He=(e,t,s)=>Jb(e,typeof t!="symbol"?t+"":t,s);import{j as r,M as hs,r as Ii,h as fr,_ as Dt,S as mt,a as lf,t as cf,p as df,b as Qb,c as Qc,d as Zb,m as uf,s as ex,y as mf,e as hf,f as Zc,g as ed,i as pf}from"./vendor-markdown-DYfLXXRA.js";import{a as m,R as ut,i as es,u as ne,g as vr}from"./vendor-i18n-BNURlJ23.js";import{r as tx,A as sx}from"./main-YQiM0LtA.js";import{S as X,B as Y,C as ee,n as le,L as nt,Y as ts,T as oe,Z as nx,$ as td,a0 as ss,l as fe,M as Lt,E as kt,a1 as Sr,t as he,a2 as sc,a3 as sd,j as ca,O as gr,a4 as ff,a5 as rx,k as dn,H as ox,p as wr,a6 as zn,a7 as ax,I as me,K as G,a8 as Wt,a9 as Ws,i as Us,aa as da,o as ke,ab as ix,ac as lx,ad as Ot,ae as gf,af as sa,ag as cx,ah as $i,A as Xe,F as Z,v as ps,ai as ui,aj as Pe,ak as it,al as Gt,am as Oe,an as At,ao as rt,ap as dx,V as Rt,aq as ns,ar as ux,as as nd,P as mi,at as ua,au as yf,av as Di,aw as lu,ax as qs,u as Ms,ay as mx,az as Li,aA as nc,aB as Pt,aC as hx,aD as Xs,aE as ot,aF as rd,aG as cu,Q as Hs,aH as Ys,aI as rc,aJ as ja,aK as px,aL as fx,G as gx,aM as Dn,aN as bf,aO as du,aP as yr,aQ as yx,aR as bx,m as br,aS as od,U as Oi,aT as xx,aU as vx,aV as xf,aW as ad,aX as vf,aY as Sx,aZ as wx,a_ as _x,a$ as Tx,b0 as kx,b1 as jx,b2 as Cx,b3 as Sf,b4 as Mx,x as wf,q as hi,b5 as id,w as Px,b6 as Ex,b7 as Rx,N as Ax,b8 as Ix,b9 as $x,ba as Dx,bb as Lx,bc as _f,bd as Ox,be as Fx,bf as zx,bg as ld,bh as Nx,bi as Bx,bj as pi,bk as uu,bl as Tf,bm as mu,bn as Wx,bo as Ux,bp as qx,bq as Hx,br as kf,bs as Yx,bt as Xx,bu as Vx,bv as hu,bw as pu}from"./vendor-antd-DzhFcYgt.js";import{Z as _r,_ as cd,$ as ma,a0 as ha,a1 as pa,a2 as Tr,a3 as dd,a4 as fi,a5 as jf,a6 as mr,a7 as Kx,a8 as Gx,a9 as Jx}from"./vendor-charts-BvOlsian.js";import{b9 as ud}from"./vendor-mermaid-Siz_U5T6.js";function Cf(e){const[t,s]=m.useState(()=>typeof window<"u"?window.matchMedia(e).matches:!1);return m.useEffect(()=>{if(typeof window>"u")return;const n=window.matchMedia(e);s(n.matches);const o=a=>{s(a.matches)};return n.addEventListener?n.addEventListener("change",o):n.addListener(o),()=>{n.removeEventListener?n.removeEventListener("change",o):n.removeListener(o)}},[e]),t}function md(){return Cf("(max-width: 768px)")}const Qx=({buttons:e,className:t,style:s,size:n="middle",align:o="right"})=>{const a={className:t,style:{width:"100%",justifyContent:o==="left"?"flex-start":o==="center"?"center":"flex-end",...s}};return r.jsx(X,{...a,children:e.map(i=>r.jsx(Y,{type:i.type||"default",disabled:i.disabled,loading:i.loading,danger:i.danger,onClick:i.onClick,size:n,icon:i.icon,children:i.text},i.key))})},Zx=(e,t)=>({key:"cancel",text:t||"Cancel",type:"default",onClick:e}),ev=(e,t)=>({key:"ok",text:(t==null?void 0:t.text)||"OK",type:"primary",disabled:t==null?void 0:t.disabled,loading:t==null?void 0:t.loading,onClick:e}),fu=e=>{let t;const s=new Set,n=(d,u)=>{const h=typeof d=="function"?d(t):d;if(!Object.is(h,t)){const p=t;t=u??(typeof h!="object"||h===null)?h:Object.assign({},t,h),s.forEach(g=>g(t,p))}},o=()=>t,l={setState:n,getState:o,getInitialState:()=>c,subscribe:d=>(s.add(d),()=>s.delete(d))},c=t=e(n,o,l);return l},tv=e=>e?fu(e):fu,sv=e=>e;function nv(e,t=sv){const s=ut.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return ut.useDebugValue(s),s}const gu=e=>{const t=tv(e),s=n=>nv(t,n);return Object.assign(s,t),s},un=e=>e?gu(e):gu,yu={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1},na=new Map,Ca=e=>{const t=na.get(e);return t?Object.fromEntries(Object.entries(t.stores).map(([s,n])=>[s,n.getState()])):{}},rv=(e,t,s)=>{if(e===void 0)return{type:"untracked",connection:t.connect(s)};const n=na.get(s.name);if(n)return{type:"tracked",store:e,...n};const o={connection:t.connect(s),stores:{}};return na.set(s.name,o),{type:"tracked",store:e,...o}},ov=(e,t)=>{if(t===void 0)return;const s=na.get(e);s&&(delete s.stores[t],Object.keys(s.stores).length===0&&na.delete(e))},av=e=>{var t,s;if(!e)return;const n=e.split(`
|
|
3
3
|
`),o=n.findIndex(i=>i.includes("api.setState"));if(o<0)return;const a=((t=n[o+1])==null?void 0:t.trim())||"";return(s=/.+ (.+) .+/.exec(a))==null?void 0:s[1]},iv=(e,t={})=>(s,n,o)=>{const{enabled:a,anonymousActionType:i,store:l,...c}=t;let d;try{d=(a??(yu?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!d)return e(s,n,o);const{connection:u,...h}=rv(l,d,c);let p=!0;o.setState=(f,v,b)=>{const x=s(f,v);if(!p)return x;const _=b===void 0?{type:i||av(new Error().stack)||"anonymous"}:typeof b=="string"?{type:b}:b;return l===void 0?(u==null||u.send(_,n()),x):(u==null||u.send({..._,type:`${l}/${_.type}`},{...Ca(c.name),[l]:o.getState()}),x)},o.devtools={cleanup:()=>{u&&typeof u.unsubscribe=="function"&&u.unsubscribe(),ov(c.name,l)}};const g=(...f)=>{const v=p;p=!1,s(...f),p=v},y=e(o.setState,n,o);if(h.type==="untracked"?u==null||u.init(y):(h.stores[h.store]=o,u==null||u.init(Object.fromEntries(Object.entries(h.stores).map(([f,v])=>[f,f===h.store?y:v.getState()])))),o.dispatchFromDevtools&&typeof o.dispatch=="function"){let f=!1;const v=o.dispatch;o.dispatch=(...b)=>{(yu?"production":void 0)!=="production"&&b[0].type==="__setState"&&!f&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),f=!0),v(...b)}}return u.subscribe(f=>{var v;switch(f.type){case"ACTION":if(typeof f.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return Qi(f.payload,b=>{if(b.type==="__setState"){if(l===void 0){g(b.state);return}Object.keys(b.state).length!==1&&console.error(`
|
|
4
4
|
[zustand devtools middleware] Unsupported __setState action format.
|
|
5
5
|
When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),
|
|
@@ -9,7 +9,7 @@ var Gb=Object.defineProperty;var Jb=(e,t,s)=>t in e?Gb(e,t,{enumerable:!0,config
|
|
|
9
9
|
|
|
10
10
|
You help users solve problems quickly and correctly. Be concise, practical, and proactive.
|
|
11
11
|
If requirements are unclear, ask focused clarifying questions before proceeding.`,isDefault:!0}),gi=()=>[jv()];class Cv{async getProviderConfig(){return xe.get("/bamboo/settings/provider")}async saveProviderConfig(t){return xe.post("/bamboo/settings/provider",t)}async reloadConfig(){return xe.post("/bamboo/settings/reload")}async getCopilotAuthStatus(){return xe.post("/bamboo/copilot/auth/status")}async startCopilotAuth(){return xe.post("/bamboo/copilot/auth/start")}async completeCopilotAuth(t){return xe.post("/bamboo/copilot/auth/complete",t)}async authenticateCopilot(){return xe.post("/bamboo/copilot/authenticate")}async logoutCopilot(){return xe.post("/bamboo/copilot/logout")}async fetchProviderModels(t){return(await xe.post("/bamboo/settings/provider/models",{provider:t})).models}async getProviderCatalog(){return xe.get("/bamboo/provider-catalog")}async fetchCatalogModels(t){const s=t?{provider:t}:{};return xe.post("/bamboo/provider-catalog/fetch-models",s)}async getEnvVars(){return xe.get("/bamboo/env-vars")}async upsertEnvVar(t){return xe.post("/bamboo/env-vars",t)}async deleteEnvVar(t){return xe.delete(`/bamboo/env-vars/${encodeURIComponent(t)}`)}async replaceEnvVars(t){return xe.post("/bamboo/env-vars/replace",{entries:t})}}const It=new Cv,Ee=un((e,t)=>({currentProvider:"copilot",providerConfig:{provider:"copilot",providers:{}},isLoading:!1,error:null,selectedModelRef:null,catalog:null,isCatalogFetching:!1,loadProviderConfig:async()=>{e({isLoading:!0,error:null});try{const s=await It.getProviderConfig();e({providerConfig:s,currentProvider:s.provider,isLoading:!1})}catch(s){console.error("Failed to load provider config:",s),e({error:s instanceof Error?s.message:"Failed to load provider config",isLoading:!1})}},setCurrentProvider:s=>{e({currentProvider:s})},updateProviderConfig:s=>{e(n=>({providerConfig:{...n.providerConfig,...s}}))},getActiveModel:()=>{const s=t(),n=s.providerConfig.providers[s.currentProvider];if(n&&"model"in n&&n.model)return n.model},getFastModel:()=>{const s=t(),n=s.providerConfig.providers[s.currentProvider];return n&&"fast_model"in n&&n.fast_model?n.fast_model:s.getActiveModel()},getVisionModel:()=>{const s=t(),n=s.providerConfig.providers[s.currentProvider];return n&&"vision_model"in n&&n.vision_model?n.vision_model:s.getActiveModel()},isProviderModelRefEnabled:()=>!0,setSelectedModelRef:s=>{e({selectedModelRef:s})},loadCatalog:async()=>{try{const s=await It.getProviderCatalog();e({catalog:s})}catch{}},fetchCatalogModels:async s=>{e({isCatalogFetching:!0});try{await It.fetchCatalogModels(s),await t().loadCatalog()}catch{}finally{e({isCatalogFetching:!1})}},getFastModelRef:()=>{const s=t(),n=s.providerConfig.providers[s.currentProvider];if(n&&"fast_model"in n&&n.fast_model)return{provider:s.currentProvider,model:n.fast_model};const o=s.getActiveModel();return o?{provider:s.currentProvider,model:o}:null},getVisionModelRef:()=>{const s=t(),n=s.providerConfig.providers[s.currentProvider];if(n&&"vision_model"in n&&n.vision_model)return{provider:s.currentProvider,model:n.vision_model};const o=s.getActiveModel();return o?{provider:s.currentProvider,model:o}:null},getModelsForProvider:s=>{const{catalog:n}=t();return n!=null&&n.models?n.models.filter(o=>o.reference.provider===s):[]}})),Mv=Object.freeze(Object.defineProperty({__proto__:null,useProviderStore:Ee},Symbol.toStringTag,{value:"Module"})),bu="copilot_auto_generate_titles",Gs=rs.getInstance(),hr=gi()[0],Pv=(hr==null?void 0:hr.id)||"general_assistant";var af;const Rf=((af=hr==null?void 0:hr.content)==null?void 0:af.trim())||"",tl="tool",xu=e=>{if(typeof e!="string"||!e.trim())return null;const t=Date.parse(e);return Number.isFinite(t)?t:null},Ev=()=>{try{const e=globalThis.crypto;if(e!=null&&e.randomUUID)return e.randomUUID()}catch{}return`id_${Date.now()}_${Math.random().toString(16).slice(2)}`},Rv=()=>{let e=kr().trim().replace(/\/+$/,"");return e.endsWith("/v1")&&(e=e.slice(0,-3)),`${e}/api/v1`},Af=e=>{const t=e.trim();if(!t.startsWith("bamboo-attachment://"))return null;const s=t.slice(20),[n,o]=s.split("/",2);return!n||!o?null:{sessionId:n,attachmentId:o}},Av=e=>{const t=Af(e);return t?`${Rv()}/sessions/${encodeURIComponent(t.sessionId)}/attachments/${encodeURIComponent(t.attachmentId)}`:e},jn=e=>{if(typeof e!="string")return;const t=e.trim();if(t&&t.toLowerCase()!=="unknown")return t},Iv=e=>{const t=(e||"").trim();if(!t)return;const s=t.match(/tool policy blocked ['"`]([^'"`]+)['"`]/i);if(s!=null&&s[1])return jn(s[1]);try{const n=JSON.parse(t);if(typeof(n==null?void 0:n.tool_name)=="string")return jn(n.tool_name)}catch{}},sl=e=>{var n,o;const t=Number.isFinite(Date.parse(e.created_at))?Date.parse(e.created_at):Date.now(),s=e.token_usage?{systemTokens:e.token_usage.system_tokens,summaryTokens:e.token_usage.summary_tokens,windowTokens:e.token_usage.window_tokens,totalTokens:e.token_usage.total_tokens,budgetLimit:e.token_usage.budget_limit,...typeof e.token_usage.max_context_tokens=="number"&&e.token_usage.max_context_tokens>0?{maxContextTokens:e.token_usage.max_context_tokens}:{},...typeof e.token_usage.prompt_cached_tool_outputs=="number"&&e.token_usage.prompt_cached_tool_outputs>0?{promptCachedToolOutputs:e.token_usage.prompt_cached_tool_outputs}:{}}:void 0;return{id:e.id,kind:e.kind,parentSessionId:e.parent_session_id??null,rootSessionId:e.root_session_id,spawnDepth:e.spawn_depth,createdByScheduleId:e.created_by_schedule_id??null,isRunning:e.is_running,updatedAt:e.updated_at,lastActivityAt:e.last_activity_at,messageCount:e.message_count,hasAttachments:e.has_attachments,lastRunStatus:e.last_run_status,lastRunError:e.last_run_error,title:e.title||es.t("chat.session.defaultTitle"),createdAt:t,pinned:e.pinned,messages:[],config:{systemPromptId:Pv,baseSystemPrompt:Rf,lastUsedEnhancedPrompt:null,model:e.model,model_ref:e.model_ref??null,reasoningEffort:e.reasoning_effort??null,tokenUsage:s,truncationOccurred:(n=e.token_usage)==null?void 0:n.truncation_occurred,segmentsRemoved:(o=e.token_usage)==null?void 0:o.segments_removed,compressionEvents:[]},currentInteraction:null}},$v=(e,t)=>{var a,i,l,c,d;const s=new Map,n=new Map;for(const u of t)u.role==="tool"&&u.tool_call_id&&u.metadata&&n.set(u.tool_call_id,u.metadata);const o=[];for(const u of t){const h=u.created_at||new Date().toISOString();if(u.role==="system"){const p={role:"system",id:u.id,createdAt:h,content:u.content||"",isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(p);continue}if(u.role==="user"){const p=new Map;for(const f of u.image_ocr||[]){const v=(a=f.image_url)==null?void 0:a.trim();if(!v)continue;const x=(f.lines||[]).map(_=>((_==null?void 0:_.text)||"").trim()).filter(Boolean);p.set(v,{ocrText:x.length?x.join(`
|
|
12
|
-
`):void 0,ocrError:f.error?String(f.error):void 0})}const g=[];for(const f of u.content_parts||[]){if(f.type!=="image_url")continue;const v=((i=f.image_url)==null?void 0:i.url)||"";if(!v)continue;const b=Av(v),x=Af(v),_=p.get(v.trim());g.push({id:Ev(),url:b,ocrText:_==null?void 0:_.ocrText,ocrError:_==null?void 0:_.ocrError,name:x?`attachment-${x.attachmentId}`:"image",size:0,type:"image/*"})}const y={role:"user",id:u.id,createdAt:h,content:u.content||"",images:g.length?g:void 0,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(y);continue}if(u.role==="assistant"){const p=u.tool_calls||[];if(p.length>0){const f=(u.content||"").trim(),v=typeof u.reasoning=="string"&&u.reasoning.trim().length>0;if(f||v){const w=v?{reasoning:u.reasoning,backendMessageId:u.id}:{backendMessageId:u.id},k={role:"assistant",type:"text",id:`${u.id}_text`,createdAt:h,content:u.content||"",metadata:w,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(k)}for(const w of p)w.id&&s.set(w.id,jn((l=w.function)==null?void 0:l.name)||tl);const b=(c=p[0])==null?void 0:c.id,x=b?n.get(b):void 0,_={role:"assistant",type:"tool_call",id:u.id,createdAt:h,toolCalls:p.map(w=>{var k;return{toolCallId:w.id,toolName:jn((k=w.function)==null?void 0:k.name)||tl,parameters:(()=>{var C,E;try{return JSON.parse(((C=w.function)==null?void 0:C.arguments)||"{}")}catch{return{raw:((E=w.function)==null?void 0:E.arguments)||""}}})(),streamingOutput:""}}),...x?{metadata:x}:{},isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(_);continue}const g=typeof u.reasoning=="string"&&u.reasoning.trim().length>0?{reasoning:u.reasoning}:{},y={role:"assistant",type:"text",id:u.id,createdAt:h,content:u.content||"",metadata:g,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(y);continue}if(u.role==="tool"){const p=((d=u.tool_call_id)==null?void 0:d.trim())||`orphan-tool-call:${u.id}`,g=jn(s.get(p))||jn(u.tool_name)||jn(u.name)||Iv(u.content)||tl,y=u.tool_success===!1||u.tool_success==null&&typeof u.content=="string"&&u.content.trimStart().startsWith("Error:"),f={role:"assistant",type:"tool_result",id:u.id,createdAt:h,toolName:g,toolCallId:p,result:{tool_name:g,result:u.content||"",display_preference:"Default"},isError:y,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(f);continue}}return o},Dv=(e,t)=>({chats:[],currentSessionId:null,latestActiveSessionId:null,processingChats:new Set,autoGenerateTitles:!0,isUpdatingAutoTitlePreference:!1,subSessionsByParent:{},addChat:async s=>{var p,g,y,f,v,b;const n=(s.title||es.t("chat.sidebar.newSession")).trim(),o=((g=(p=s.config)==null?void 0:p.baseSystemPrompt)==null?void 0:g.trim())||"",a=(y=Ee.getState().getActiveModel())==null?void 0:y.trim(),i=((v=(f=s.config)==null?void 0:f.model)==null?void 0:v.trim())||a||void 0,l=((b=s.config)==null?void 0:b.reasoningEffort)??void 0;let c,d;if(Ee.getState().isProviderModelRefEnabled()){const x=Ee.getState().selectedModelRef;if(x)c=x,d=x.provider;else{const _=Ee.getState().getActiveModel();_&&(c={provider:Ee.getState().currentProvider,model:_},d=Ee.getState().currentProvider)}}const u=await Gs.createSession({title:n,system_prompt:o||void 0,model:i,model_ref:c,provider:d,reasoning_effort:l||void 0}),h={...sl(u.session),title:n,config:{...s.config,model:u.session.model,model_ref:u.session.model_ref??null,reasoningEffort:u.session.reasoning_effort??null,baseSystemPrompt:o||Rf},messages:[],currentInteraction:null};return e(x=>{const _=[h,...x.chats.filter(w=>w.id!==h.id)];return{...x,chats:_,currentSessionId:h.id,latestActiveSessionId:h.id}}),h.id},selectSession:s=>{const n=t();n.currentSessionId===s&&n.latestActiveSessionId===s||e({currentSessionId:s,latestActiveSessionId:s})},deleteSession:async s=>{try{await Gs.deleteSession(s)}catch(n){console.error(`[ChatSlice] Failed to delete backend session ${s}:`,n)}e(n=>{var c;const o=new Set;for(const d of n.chats)d.id===s&&o.add(d.id),d.rootSessionId===s&&o.add(d.id);const a=n.chats.filter(d=>!o.has(d.id)),i=n.currentSessionId&&o.has(n.currentSessionId)?null:n.currentSessionId,l=n.latestActiveSessionId&&o.has(n.latestActiveSessionId)?((c=a[0])==null?void 0:c.id)??null:n.latestActiveSessionId;return{...n,chats:a,currentSessionId:i,latestActiveSessionId:l}})},deleteSessions:async s=>{for(const n of s)await t().deleteSession(n)},updateSession:(s,n)=>{const o=!!n.config&&(Object.prototype.hasOwnProperty.call(n.config,"model")||Object.prototype.hasOwnProperty.call(n.config,"reasoningEffort")),a=typeof n.title=="string"||typeof n.pinned=="boolean",l=o||a?new Date().toISOString():void 0;e(d=>{const u=d.chats.map(h=>h.id===s?{...h,...n,...l?{updatedAt:l}:{}}:h);return{...d,chats:u}});const c={};if(typeof n.title=="string"&&(c.title=n.title),typeof n.pinned=="boolean"&&(c.pinned=n.pinned),n.config&&Object.prototype.hasOwnProperty.call(n.config,"model")&&(c.model=n.config.model??null),n.config&&Object.prototype.hasOwnProperty.call(n.config,"model_ref")&&Ee.getState().isProviderModelRefEnabled()&&(c.model_ref=n.config.model_ref??null,n.config.model_ref&&(c.provider=n.config.model_ref.provider)),n.config&&Object.prototype.hasOwnProperty.call(n.config,"reasoningEffort")){const d=n.config.reasoningEffort;d?c.reasoning_effort=d:c.clear_reasoning_effort=!0}Object.keys(c).length>0&&Gs.patchSession(s,c).catch(d=>{console.warn(`[ChatSlice] Failed to patch session ${s}:`,d)})},pinSession:s=>{t().updateSession(s,{pinned:!0})},unpinSession:s=>{t().updateSession(s,{pinned:!1})},setMessages:(s,n)=>{t().chats.find(a=>a.id===s)&&t().updateSession(s,{messages:n})},addMessage:async(s,n)=>{const o=t().chats.find(i=>i.id===s);if(!o)return;const a=[...o.messages,n];t().updateSession(s,{messages:a})},updateMessage:(s,n,o)=>{const a=t().chats.find(l=>l.id===s);if(!a)return;const i=a.messages.map(l=>{if(l.id!==n)return l;const c={...l};return Object.keys(o).forEach(d=>{Object.prototype.hasOwnProperty.call(c,d)&&(c[d]=o[d])}),c});t().updateSession(s,{messages:i})},deleteMessage:async(s,n)=>{const o=t().chats.find(a=>a.id===s);if(!o)return{success:!1,sessionId:s,messageId:n,reason:"session_not_found"};if(!o.messages.some(a=>a.id===n))return{success:!1,sessionId:s,messageId:n,reason:"message_not_found"};try{await Gs.deleteSessionMessage(s,n)}catch(a){return console.warn(`[ChatSlice] Failed to delete message ${n} from session ${s}:`,a),a instanceof Bn?a.status===404?{success:!1,sessionId:s,messageId:n,reason:"backend_not_found",statusCode:a.status,errorMessage:a.message}:a.status===409?{success:!1,sessionId:s,messageId:n,reason:"session_running",statusCode:a.status,errorMessage:a.message}:{success:!1,sessionId:s,messageId:n,reason:"backend_error",statusCode:a.status,errorMessage:a.message}:{success:!1,sessionId:s,messageId:n,reason:"backend_error",errorMessage:a instanceof Error?a.message:void 0}}return e(a=>({...a,chats:a.chats.map(i=>i.id===s?{...i,messages:i.messages.filter(l=>l.id!==n)}:i)})),{success:!0,sessionId:s,messageId:n}},refreshChats:async()=>{const n=(await Gs.listSessions()).sessions.map(sl);e(o=>{const a=new Set(o.processingChats);n.forEach(c=>{c.isRunning&&a.add(c.id)});const i=new Map(o.chats.map(c=>[c.id,c])),l=n.map(c=>{var _,w,k,C;const d=i.get(c.id);if(!d)return c;const u=xu(d.updatedAt),h=xu(c.updatedAt),p=u!==null&&h!==null&&u>h,g=d.config||{},y=c.config||{},f=Object.prototype.hasOwnProperty.call(g,"model"),v=Object.prototype.hasOwnProperty.call(g,"model_ref"),b=Object.prototype.hasOwnProperty.call(g,"reasoningEffort"),x=Math.max(d.messageCount??0,c.messageCount??0);return{...c,title:p?d.title:c.title,pinned:p?d.pinned:c.pinned,updatedAt:p?d.updatedAt:c.updatedAt,messages:d.messages,messageCount:x,config:{...g,...y,model:p&&f?g.model:y.model,model_ref:p&&v?g.model_ref:y.model_ref,reasoningEffort:p&&b?g.reasoningEffort:y.reasoningEffort,compressionEvents:((_=d.config)==null?void 0:_.compressionEvents)??((w=c.config)==null?void 0:w.compressionEvents),syncCursor:((k=d.config)==null?void 0:k.syncCursor)??((C=c.config)==null?void 0:C.syncCursor)}}});return{...o,chats:l,processingChats:a}})},loadChats:async()=>{var c;const s=localStorage.getItem(bu),n=s===null?t().autoGenerateTitles:s==="true";let o=await Gs.listSessions();(!o.sessions||o.sessions.length===0)&&(o={sessions:[(await Gs.createSession({title:es.t("chat.sidebar.newSession")})).session]});const a=o.sessions.map(sl),i=((c=a[0])==null?void 0:c.id)??null,l=a.filter(d=>d.isRunning).map(d=>d.id);e({chats:a,latestActiveSessionId:i,currentSessionId:i,processingChats:new Set(l),autoGenerateTitles:n}),i&&await t().loadChatHistory(i)},loadChatHistory:async(s,n)=>{var l,c,d,u,h,p,g;const o=(n==null?void 0:n.mode)??"replace",a=Math.max(0,(n==null?void 0:n.retries)??0),i=Math.max(0,(n==null?void 0:n.retryDelayMs)??0);for(let y=0;y<=a;y+=1)try{const f=t().chats.find(_=>_.id===s);if(!f)return;const v=await Gs.getHistory(s),b=(l=v.messages[v.messages.length-1])==null?void 0:l.role;if(n!=null&&n.waitForAssistant&&b==="user"&&y<a){const _=i>0?i*(y+1):200*(y+1);await new Promise(w=>setTimeout(w,_));continue}const x=$v(s,v.messages);if(o==="monotonic"){const _=f.messages||[],w=_.length,k=x.length,C=(c=x[x.length-1])==null?void 0:c.role,E=(d=_[_.length-1])==null?void 0:d.role,j=_[_.length-1],R=x[x.length-1],M=j==null?void 0:j.id,T=R==null?void 0:R.id;let P=!1;if(k>w?P=!0:k===w&&(P=E==="user"&&C!=="user"||typeof M=="string"&&typeof T=="string"&&M!==T),!P){t().updateSession(s,{messageCount:Math.max(f.messageCount??0,v.messages.length)});return}}t().updateSession(s,{messages:x,messageCount:v.messages.length,config:{...f.config||{},compressionEvents:(v.compression_events||[]).map(_=>({id:_.id,createdAt:_.created_at,messagesCompressed:_.messages_compressed,segmentsRemoved:_.segments_removed})),syncCursor:{messageCount:v.messages.length,lastMessageId:((u=v.messages[v.messages.length-1])==null?void 0:u.id)??null,hasPendingQuestion:((h=t().pendingQuestionRespond)==null?void 0:h.sessionId)===s,pendingQuestionToolCallId:((p=t().pendingQuestionRespond)==null?void 0:p.sessionId)===s?((g=t().pendingQuestionRespond)==null?void 0:g.toolCallId)??null:null}}});return}catch(f){if(y>=a){console.warn(`[ChatSlice] Failed to load history for ${s}:`,f);return}const v=i>0?i*(y+1):200*(y+1);await new Promise(b=>setTimeout(b,v))}},upsertSubSessionProgress:(s,n,o)=>{e(a=>{const i=a.subSessionsByParent[s]||{},l=i[n]||{},c={...i,[n]:{...l,...o}};return{subSessionsByParent:{...a.subSessionsByParent,[s]:c}}})},clearSubSessionProgress:(s,n)=>{e(o=>{const a=o.subSessionsByParent[s];if(!a||!a[n])return{};const{[n]:i,...l}=a;return{subSessionsByParent:{...o.subSessionsByParent,[s]:l}}})},setSessionProcessing:(s,n)=>{e(o=>{const a=new Set(o.processingChats);return n?a.add(s):a.delete(s),{processingChats:a}})},isSessionProcessing:s=>t().processingChats.has(s),setAutoGenerateTitlesPreference:async s=>{const n=t().autoGenerateTitles;e({autoGenerateTitles:s,isUpdatingAutoTitlePreference:!0});try{localStorage.setItem(bu,String(s))}catch(o){throw console.warn("[ChatSlice] Failed to update auto-title preference:",o),e({autoGenerateTitles:n}),o}finally{e({isUpdatingAutoTitlePreference:!1})}}});class ac extends Error{constructor(s="Proxy authentication required"){super(s);He(this,"code","proxy_auth_required");this.name="ProxyAuthRequiredError"}}const En=class En{constructor(){}static getInstance(){return En.instance||(En.instance=new En),En.instance}resolveOpenAICompatBaseUrl(){const t=kr().trim().replace(/\/+$/,"");return t.endsWith("/openai/v1")?t:`${t.endsWith("/v1")?t.slice(0,-3):t}/openai/v1`}async getModels(){var t,s;try{return(await new pd({baseUrl:this.resolveOpenAICompatBaseUrl()}).get("models")).data.map(a=>a.id)}catch(n){if(console.error("Failed to fetch models from HTTP API:",n),n instanceof Bn){if(n.status===428)throw new ac(n.message);let o;if(n.body)try{o=JSON.parse(n.body)}catch{}if(o&&typeof o=="object"&&"error"in o&&((t=o.error)==null?void 0:t.code)==="proxy_auth_required")throw new ac(((s=o.error)==null?void 0:s.message)||n.message)}throw n}}};He(En,"instance");let ic=En;const If=ic.getInstance(),Lv=async e=>{var t;if(typeof navigator>"u"||!((t=navigator.clipboard)!=null&&t.writeText))throw new Error("navigator.clipboard.writeText is unavailable");await navigator.clipboard.writeText(e)},Ov=e=>{if(typeof document>"u")throw new Error("document is unavailable");const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly","true"),t.style.position="fixed",t.style.top="-9999px",t.style.left="-9999px",t.style.opacity="0",document.body.appendChild(t),t.focus(),t.select();const s=document.execCommand("copy");if(document.body.removeChild(t),!s)throw new Error("document.execCommand('copy') returned false")},os=async e=>{try{await Lv(e);return}catch(t){try{Ov(e);return}catch(s){const n=t instanceof Error?t.message:String(t),o=s instanceof Error?s.message:String(s);throw new Error(`Clipboard copy failed: navigator(${n}); fallback(${o})`)}}};class Fv{async copyToClipboard(t){await os(t)}async getBambooConfig(){try{return await xe.get("bamboo/config")}catch(t){return console.error("Failed to fetch Bamboo config:",t),{}}}async getBambooTools(){try{return await xe.get("bamboo/tools")}catch(t){return console.error("Failed to fetch Bamboo tools:",t),{tools:[]}}}async getModelLimitDefaults(){try{return await xe.get("bamboo/model-limits/defaults")}catch(t){return console.error("Failed to fetch model limit defaults:",t),{model_limits:[]}}}async setBambooConfig(t){return xe.post("bamboo/config",t)}async validateBambooConfigPatch(t){return xe.post("bamboo/config/validate",t)}async setProxyAuth(t){return xe.post("bamboo/proxy-auth",t)}async getProxyAuthStatus(){try{return await xe.get("bamboo/proxy-auth/status")}catch(t){return console.error("Failed to fetch proxy auth status:",t),{configured:!1,username:null}}}async clearProxyAuth(){return xe.post("bamboo/proxy-auth",{username:"",password:""})}async resetBambooConfig(){return xe.post("bamboo/config/reset",{})}async saveWorkflow(t,s){return xe.post("bamboo/workflows",{name:t,content:s})}async deleteWorkflow(t){return xe.delete(`bamboo/workflows/${encodeURIComponent(t)}`)}async getKeywordMaskingConfig(){try{return await xe.get("bamboo/keyword-masking")}catch(t){return console.error("Failed to fetch keyword masking config:",t),{entries:[]}}}async updateKeywordMaskingConfig(t){return xe.post("bamboo/keyword-masking",t)}async validateKeywordEntries(t){return xe.post("bamboo/keyword-masking/validate",t)}async getSetupStatus(){return await xe.get("bamboo/setup/status")}async markSetupComplete(){return xe.post("bamboo/setup/complete",{})}async resetSetupStatus(){await xe.post("bamboo/setup/incomplete",{})}async getAccessStatus(){return xe.get("bamboo/access/status")}async verifyAccessPassword(t){return xe.post("bamboo/access/verify",{password:t})}async updateAccessPassword(t){return xe.post("bamboo/access/password",t)}}const Rn=class Rn{constructor(){He(this,"httpUtilityService",new Fv)}static getInstance(){return Rn.instance||(Rn.instance=new Rn),Rn.instance}getUtilityService(){return{copyToClipboard:t=>this.httpUtilityService.copyToClipboard(t),getBambooConfig:()=>this.httpUtilityService.getBambooConfig(),getBambooTools:()=>this.httpUtilityService.getBambooTools(),getModelLimitDefaults:()=>this.httpUtilityService.getModelLimitDefaults(),setBambooConfig:t=>this.httpUtilityService.setBambooConfig(t),validateBambooConfigPatch:t=>this.httpUtilityService.validateBambooConfigPatch(t),setProxyAuth:t=>this.httpUtilityService.setProxyAuth(t),getProxyAuthStatus:()=>this.httpUtilityService.getProxyAuthStatus(),clearProxyAuth:()=>this.httpUtilityService.clearProxyAuth(),resetBambooConfig:()=>this.httpUtilityService.resetBambooConfig(),resetSetupStatus:()=>this.httpUtilityService.resetSetupStatus(),saveWorkflow:(t,s)=>this.httpUtilityService.saveWorkflow(t,s),deleteWorkflow:t=>this.httpUtilityService.deleteWorkflow(t),getKeywordMaskingConfig:()=>this.httpUtilityService.getKeywordMaskingConfig(),updateKeywordMaskingConfig:t=>this.httpUtilityService.updateKeywordMaskingConfig(t),validateKeywordEntries:t=>this.httpUtilityService.validateKeywordEntries(t),getSetupStatus:()=>this.httpUtilityService.getSetupStatus(),markSetupComplete:()=>this.httpUtilityService.markSetupComplete(),getAccessStatus:()=>this.httpUtilityService.getAccessStatus(),verifyAccessPassword:t=>this.httpUtilityService.verifyAccessPassword(t),updateAccessPassword:t=>this.httpUtilityService.updateAccessPassword(t)}}async copyToClipboard(t){return this.getUtilityService().copyToClipboard(t)}async getBambooConfig(){return this.getUtilityService().getBambooConfig()}async getBambooTools(){return this.getUtilityService().getBambooTools()}async getModelLimitDefaults(){return this.getUtilityService().getModelLimitDefaults()}async setBambooConfig(t){return this.getUtilityService().setBambooConfig(t)}async validateBambooConfigPatch(t){return this.getUtilityService().validateBambooConfigPatch(t)}async setProxyAuth(t){return this.getUtilityService().setProxyAuth(t)}async getProxyAuthStatus(){return this.getUtilityService().getProxyAuthStatus()}async clearProxyAuth(){return this.getUtilityService().clearProxyAuth()}async resetBambooConfig(){return this.getUtilityService().resetBambooConfig()}async resetSetupStatus(){return this.getUtilityService().resetSetupStatus()}async saveWorkflow(t,s){return this.getUtilityService().saveWorkflow(t,s)}async deleteWorkflow(t){return this.getUtilityService().deleteWorkflow(t)}async getKeywordMaskingConfig(){return this.getUtilityService().getKeywordMaskingConfig()}async updateKeywordMaskingConfig(t){return this.getUtilityService().updateKeywordMaskingConfig(t)}async validateKeywordEntries(t){return this.getUtilityService().validateKeywordEntries(t)}async getSetupStatus(){return this.getUtilityService().getSetupStatus()}async markSetupComplete(){return this.getUtilityService().markSetupComplete()}async getAccessStatus(){return this.getUtilityService().getAccessStatus()}async verifyAccessPassword(t){return this.getUtilityService().verifyAccessPassword(t)}async updateAccessPassword(t){return this.getUtilityService().updateAccessPassword(t)}};He(Rn,"instance");let fs=Rn;const et=fs.getInstance();let Ar=null,Ir=null;const nl=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,ms=un((e,t)=>({config:null,proxyAuthStatus:null,isLoadingConfig:!1,isLoadingProxyAuthStatus:!1,lastLoadedAt:null,error:null,loadConfig:async({force:s=!1}={})=>{const n=t().config;if(!s&&n)return n;if(Ar)return Ar;Ar=(async()=>{e({isLoadingConfig:!0,error:null});try{const o=await et.getBambooConfig()??{};return e({config:o,lastLoadedAt:Date.now(),error:null}),o}catch(o){const a=nl(o,"Failed to load Bamboo config");throw e({error:a}),o}finally{e({isLoadingConfig:!1})}})();try{return await Ar}finally{Ar=null}},saveConfig:async s=>{e({isLoadingConfig:!0,error:null,config:s});try{const n=await et.setBambooConfig(s);return e({config:n,lastLoadedAt:Date.now(),error:null}),n}catch(n){const o=nl(n,"Failed to save Bamboo config");throw e({error:o}),n}finally{e({isLoadingConfig:!1})}},patchConfig:async s=>{const o={...await t().loadConfig()??{},...s??{}};return t().saveConfig(o)},loadProxyAuthStatus:async({force:s=!1}={})=>{const n=t().proxyAuthStatus;if(!s&&n)return n;if(Ir)return Ir;Ir=(async()=>{e({isLoadingProxyAuthStatus:!0,error:null});try{const o=await et.getProxyAuthStatus();return e({proxyAuthStatus:o,error:null}),o}catch(o){const a=nl(o,"Failed to load proxy auth status");throw e({error:a}),o}finally{e({isLoadingProxyAuthStatus:!1})}})();try{return await Ir}finally{Ir=null}},applyProxyAuth:async s=>{await et.setProxyAuth(s),await t().loadProxyAuthStatus({force:!0})},clearProxyAuth:async()=>{await et.clearProxyAuth(),await t().loadProxyAuthStatus({force:!0})}}));let $r=null;const zv=(e,t)=>({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:null,configModel:void 0,setSelectedModel:s=>{e({selectedModel:s})},loadConfigModel:async()=>{try{const s=await ms.getState().loadConfig(),n=typeof(s==null?void 0:s.model)=="string"?s.model:void 0;n&&e({configModel:n})}catch(s){console.error("Failed to load model from config:",s)}},fetchModels:async()=>{if($r)return $r;$r=(async()=>{e({isLoadingModels:!0,modelsError:null});try{try{if(!(await et.getSetupStatus()).is_complete){st("[ModelSlice]","Setup not complete, skipping model fetch"),e({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:"Complete setup to access all models"});return}}catch(n){console.error("Failed to check setup status:",n)}const s=await If.getModels();e(n=>{const o=n.selectedModel;let a=n.selectedModel;return o&&s.includes(o)||(s.length>0?a=s[0]:a=void 0),{...n,models:s,selectedModel:a,modelsError:s.length>0?null:"No available model options"}}),t().models.length===0&&console.warn("No models available from service")}catch(s){const n=s instanceof Error?s.message:String(s);if(console.error("Failed to fetch models:",s),s instanceof ac){e(o=>({...o,models:o.models,selectedModel:o.selectedModel,modelsError:n||"Proxy authentication required. Please configure proxy auth."}));return}e(o=>({...o,models:[],selectedModel:o.selectedModel,modelsError:n}))}finally{e({isLoadingModels:!1})}})();try{await $r}finally{$r=null}}}),Nv=["system_prompt","system_prompt_selected_id"],rl=e=>({id:e.id,name:e.name||e.id,content:e.content||"",description:e.description,isDefault:!!e.is_default}),nn=class nn{constructor(){He(this,"deprecatedKeysCleanupDone",!1)}static getInstance(){return nn.instance||(nn.instance=new nn),nn.instance.cleanupDeprecatedPromptStorageKeys(),nn.instance}cleanupDeprecatedPromptStorageKeys(){if(!this.deprecatedKeysCleanupDone){this.deprecatedKeysCleanupDone=!0;try{for(const t of Nv)localStorage.removeItem(t)}catch(t){console.warn("[SystemPromptService] Failed to cleanup deprecated prompt storage keys:",t)}}}async getSystemPromptPresets(){try{const t=await pe.get("prompt-presets"),n=(Array.isArray(t==null?void 0:t.prompts)?t.prompts:[]).filter(o=>o.id&&o.id.trim().length>0).map(rl);if(n.length>0)return n}catch(t){console.error("Failed to load prompt presets from backend:",t)}return gi()}async createSystemPromptPreset(t){var o;const s={name:t.name,content:t.content};(o=t.id)!=null&&o.trim()&&(s.id=t.id.trim()),t.description!==void 0&&(s.description=t.description);const n=await pe.post("prompt-presets",s);if(!(n!=null&&n.prompt))throw new Error("Backend did not return created prompt preset");return rl(n.prompt)}async updateSystemPromptPreset(t){const s=encodeURIComponent(t.id),n={name:t.name,content:t.content,description:t.description},o=await pe.patch(`prompt-presets/${s}`,n);if(!(o!=null&&o.prompt))throw new Error("Backend did not return updated prompt preset");return rl(o.prompt)}async deleteSystemPromptPreset(t){const s=encodeURIComponent(t);await pe.delete(`prompt-presets/${s}`)}async findPresetById(t){return(await this.getSystemPromptPresets()).find(n=>n.id===t)}async getCurrentSystemPromptContent(t){const s=await this.findPresetById(t);if(s)return s.content;const n=await this.getSystemPromptPresets(),o=n.find(a=>a.isDefault)||n[0];return(o==null?void 0:o.content)||""}};He(nn,"instance");let yi=nn;const vu="copilot_last_selected_prompt_id",$f="copilot_custom_system_prompts_v2",Df="copilot_custom_system_prompts_v2_migrated_to_backend",Lf="general_assistant",fd=80,dr=yi.getInstance();let Ma=null;function gd(e){const t=e.toLowerCase().trim().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"");return t.length===0?`prompt_${Date.now()}_${Math.random().toString(36).substring(2,9)}`:t.slice(0,fd)}function Of(e){if(typeof e!="string")return null;const t=e.toLowerCase().trim().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");return t?t.slice(0,fd):null}function Ff(e,t){if(!t.has(e))return e;let s=2;for(;;){const n=`_${s}`,a=`${e.slice(0,Math.max(0,fd-n.length))}${n}`;if(!t.has(a))return a;s+=1}}function zf(){try{const e=localStorage.getItem($f);if(!e)return[];const t=JSON.parse(e);if(!Array.isArray(t))return[];const s=new Set,n=[];for(const o of t){const a=typeof(o==null?void 0:o.name)=="string"?o.name.trim():"",i=typeof(o==null?void 0:o.content)=="string"?o.content.trim():"";if(!a||!i)continue;const c=Of(o==null?void 0:o.id)||gd(a),d=Ff(c,s);d!==Lf&&(s.add(d),n.push({id:d,name:a,content:i,description:typeof(o==null?void 0:o.description)=="string"&&o.description.trim()||void 0,isDefault:!!(o!=null&&o.isDefault)}))}return n}catch(e){return console.error("[promptSlice] Failed to read legacy custom prompts:",e),[]}}function Nf(){try{return localStorage.getItem(Df)==="1"}catch(e){return console.error("[promptSlice] Failed to read migration marker:",e),!1}}function Su(){try{localStorage.setItem(Df,"1")}catch(e){console.error("[promptSlice] Failed to write migration marker:",e)}}function wu(){try{localStorage.removeItem($f)}catch(e){console.error("[promptSlice] Failed to clear legacy custom prompts:",e)}}async function Bv(){var o,a;if(Nf())return;const e=zf();if(e.length===0){wu(),Su();return}const t=await dr.getSystemPromptPresets(),s=new Set(t.map(i=>i.id));let n=!1;for(const i of e){const l=(o=i.name)==null?void 0:o.trim(),c=(a=i.content)==null?void 0:a.trim();if(!l||!c||i.id===Lf||i.isDefault)continue;const d=Of(i.id)||gd(l),u=Ff(d,s);try{const h=await dr.createSystemPromptPreset({id:u,name:l,content:c,description:i.description});s.add(h.id)}catch(h){n=!0,console.error(`[promptSlice] Failed to migrate legacy prompt '${l}' to backend:`,h)}}n||(wu(),Su())}async function Wv(){Ma||(Ma=Bv().finally(()=>{Ma=null})),await Ma}const Uv=(e,t)=>({systemPrompts:[],lastSelectedPromptId:localStorage.getItem(vu)||null,loadSystemPrompts:async()=>{try{await Wv()}catch(o){console.warn("[promptSlice] Legacy prompt migration skipped:",o)}let s=[];try{s=await dr.getSystemPromptPresets()}catch(o){console.error("Failed to load system prompts from backend:",o)}let n=s.length?s:gi();if(!Nf()){const o=zf();n=qv(n,o)}n.length===0&&(n=gi()),e({systemPrompts:n})},addSystemPrompt:async s=>{try{await dr.createSystemPromptPreset({id:gd(s.name),name:s.name,content:s.content,description:s.description}),await t().loadSystemPrompts()}catch(n){throw console.error("Failed to add system prompt:",n),n}},updateSystemPrompt:async s=>{try{await dr.updateSystemPromptPreset(s),await t().loadSystemPrompts()}catch(n){throw console.error("Failed to update system prompt:",n),n}},deleteSystemPrompt:async s=>{try{await dr.deleteSystemPromptPreset(s),await t().loadSystemPrompts()}catch(n){throw console.error("Failed to delete system prompt:",n),n}},setLastSelectedPromptId:s=>{e({lastSelectedPromptId:s});try{localStorage.setItem(vu,s)}catch(n){console.error("Failed to save last selected prompt ID to localStorage:",n)}}}),qv=(e,t)=>{const s=new Map;return e.forEach(n=>{s.set(n.id,n)}),t.forEach(n=>{s.set(n.id,n)}),Array.from(s.values())},Hv=(e,t)=>({currentRequestController:null,setCurrentRequestController:s=>{e({currentRequestController:s})},cancelCurrentRequest:()=>{var s;(s=t().currentRequestController)==null||s.abort(),t().processingChats.forEach(n=>{t().setSessionProcessing(n,!1)}),e({currentRequestController:null})}});class Yv{async listSkills(t,s){const n=new URLSearchParams;t!=null&&t.search&&n.append("search",t.search),t!=null&&t.includeDisabled&&n.append("include_disabled","true"),s&&n.append("refresh","true");const o=n.toString(),a=o?`skills?${o}`:"skills";return xe.get(a)}async getSkill(t){return xe.get(`skills/${t}`)}async getFilteredTools(t){const s=t?`?session_id=${encodeURIComponent(t)}`:"";return(await xe.get(`skills/filtered-tools${s}`)).tools??[]}}const lc=new Yv,Xv=(e,t)=>({skills:[],isLoadingSkills:!1,skillsError:null,loadSkills:async(s,n)=>{e({isLoadingSkills:!0,skillsError:null});try{const o=await lc.listSkills(s,n);e({skills:o.skills,isLoadingSkills:!1})}catch(o){e({skillsError:o instanceof Error?o.message:es.t("components.skillManager.loadFailed"),isLoadingSkills:!1})}},getSkill:async s=>{e({isLoadingSkills:!0,skillsError:null});try{const n=await lc.getSkill(s),o=t().skills,i=o.findIndex(l=>l.id===n.id)>=0?o.map(l=>l.id===n.id?n:l):[...o,n];e({skills:i,isLoadingSkills:!1})}catch(n){e({skillsError:n instanceof Error?n.message:es.t("components.skillManager.getFailed"),isLoadingSkills:!1})}},clearSkillsError:()=>{e({skillsError:null})}}),Vv=e=>({tokenUsages:{},truncationOccurred:{},segmentsRemoved:{},updateTokenUsage:(t,s)=>e(n=>({tokenUsages:{...n.tokenUsages,[t]:s}})),setTruncationInfo:(t,s,n)=>e(o=>({truncationOccurred:{...o.truncationOccurred,[t]:s},segmentsRemoved:{...o.segmentsRemoved,[t]:n}})),clearTokenUsage:t=>e(s=>{const{[t]:n,...o}=s.tokenUsages,{[t]:a,...i}=s.truncationOccurred,{[t]:l,...c}=s.segmentsRemoved;return{tokenUsages:o,truncationOccurred:i,segmentsRemoved:c}})}),Kv=(e,t)=>({taskLists:{},taskListVersions:{},activeItems:{},evaluationStates:{},setTaskList:(s,n)=>e(o=>({taskLists:{...o.taskLists,[s]:n},taskListVersions:{...o.taskListVersions,[s]:n.version||0}})),updateTaskListDelta:(s,n)=>e(o=>{const a=o.taskListVersions[s]||0;if(n.version<=a)return o;const i=o.taskLists[s];if(!i)return o;const l=i.items.map(c=>c.id===n.item_id?{...c,status:n.status,tool_calls_count:n.tool_calls_count}:c);return{taskLists:{...o.taskLists,[s]:{...i,items:l,updated_at:new Date().toISOString()}},taskListVersions:{...o.taskListVersions,[s]:n.version},activeItems:{...o.activeItems,[s]:n.status==="in_progress"?n.item_id:null}}}),clearTaskList:s=>e(n=>{const{[s]:o,...a}=n.taskLists,{[s]:i,...l}=n.taskListVersions,{[s]:c,...d}=n.activeItems,{[s]:u,...h}=n.evaluationStates;return{taskLists:a,taskListVersions:l,activeItems:d,evaluationStates:h}}),getTaskListVersion:s=>t().taskListVersions[s]||0,setEvaluationState:(s,n)=>e(o=>({evaluationStates:{...o.evaluationStates,[s]:n}})),clearEvaluationState:s=>e(n=>{const{[s]:o,...a}=n.evaluationStates;return{evaluationStates:a}})}),cc=e=>Array.isArray(e)?e.map(t=>String(t??"")):[],Ka=({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:o})=>JSON.stringify({sessionId:e??null,question:t??"",options:cc(s),allowCustom:n??!0,toolCallId:o??null}),Gv=(e,t)=>{if(!e||!t)return e===t;if((e.sessionId??null)!==(t.sessionId??null)||(e.question??"")!==(t.question??"")||(e.allowCustom??!0)!==(t.allowCustom??!0)||(e.toolCallId??null)!==(t.toolCallId??null))return!1;const s=cc(e.options),n=cc(t.options);return s.length!==n.length?!1:s.every((o,a)=>o===n[a])},Bf="chat_input_reasoning_by_session_v1",Wf="chat_input_reasoning_last_used_v1",_u={content:"",referenceText:null,attachments:[],reasoningEffort:"medium"},yd=e=>e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max",Uf=()=>{if(typeof window>"u")return{};try{const e=localStorage.getItem(Bf);if(!e)return{};const t=JSON.parse(e),s={};for(const[n,o]of Object.entries(t||{}))yd(o)&&(s[n]=o);return s}catch{return{}}},Jv=e=>{if(!(typeof window>"u"))try{localStorage.setItem(Bf,JSON.stringify(e))}catch{}},Qv=()=>{if(!(typeof window>"u"))try{const e=localStorage.getItem(Wf);return yd(e)?e:void 0}catch{return}},Zv=e=>{if(!(typeof window>"u"))try{localStorage.setItem(Wf,e)}catch{}},bd=e=>{const t=Uf();return yd(t[e])?t[e]:Qv()},Dr=e=>({..._u,reasoningEffort:bd(e)??_u.reasoningEffort}),eS=(e,t)=>({inputStates:{},pendingQuestionRespond:null,setInputContent:(s,n)=>e(o=>({inputStates:{...o.inputStates,[s]:{...o.inputStates[s]||Dr(s),content:n}}})),setReferenceText:(s,n)=>e(o=>({inputStates:{...o.inputStates,[s]:{...o.inputStates[s]||Dr(s),referenceText:n}}})),setAttachments:(s,n)=>e(o=>({inputStates:{...o.inputStates,[s]:{...o.inputStates[s]||Dr(s),attachments:n}}})),setInputReasoningEffort:(s,n)=>{e(a=>({inputStates:{...a.inputStates,[s]:{...a.inputStates[s]||Dr(s),reasoningEffort:n}}}));const o=Uf();o[s]=n,Jv(o),Zv(n)},clearInputState:s=>e(n=>{const{[s]:o,...a}=n.inputStates;return{inputStates:a}}),getInputState:s=>t().inputStates[s]||Dr(s),setPendingQuestionRespond:s=>e(n=>Gv(n.pendingQuestionRespond,s)?{}:{pendingQuestionRespond:s}),clearPendingQuestionRespondForSession:s=>e(n=>{var o;return((o=n.pendingQuestionRespond)==null?void 0:o.sessionId)!==s?{}:n.pendingQuestionRespond===null?{}:{pendingQuestionRespond:null}})}),tS="bamboo_proxy_auth",sS=()=>{try{const e=localStorage.getItem(tS);if(!e)return null;const t=JSON.parse(e);if(!t||typeof t!="object")return null;const s=typeof t.username=="string"?t.username.trim():"",n=typeof t.password=="string"?t.password:"";return s?{username:s,password:n}:null}catch{return null}},nS="auto",rS="required",oS=1e4,aS=2e3,iS=rs.getInstance();let Tu=null,Lr=null,ku=null,Or=null;const ju=new WeakMap,N=un()(lv(dv((e,t,s)=>({...Dv(e,t),...zv(e,t),...Uv(e,t),...Hv(e,t),...Xv(e,t),...Vv(e),...Kv(e,t),...eS(e,t),agentAvailability:null,setAgentAvailability:n=>{e({agentAvailability:n})},checkAgentAvailability:async()=>{if(Lr)return Lr;Lr=(async()=>{const n=await iS.healthCheck();return t().agentAvailability!==n&&e({agentAvailability:n}),n})();try{return await Lr}finally{Lr=null}},startAgentHealthCheck:()=>{Tu||(t().checkAgentAvailability(),Tu=setInterval(()=>{t().checkAgentAvailability()},oS))},refreshSessionsIndex:async()=>{if(Or)return Or;Or=(async()=>{try{await t().refreshChats()}catch(n){console.warn("[AppStore] refreshChats failed:",n)}})();try{return await Or}finally{Or=null}},startSessionsIndexSync:()=>{ku||(t().refreshSessionsIndex(),ku=setInterval(()=>{t().refreshSessionsIndex()},aS))}})),{name:"AppStore"})),qf=e=>{const t=ju.get(e);if(t)return t;const s=new Map(e.map(n=>[n.id,n]));return ju.set(e,s),s},Xn=e=>t=>e?qf(t.chats).get(e)??null:null,lS=e=>e.currentSessionId?qf(e.chats).get(e.currentSessionId)??null:null,Cu=async()=>{const e=sS();if(!e)return!1;try{return await et.setProxyAuth(e),!0}catch(t){return console.error("Failed to apply stored proxy auth during startup:",t),!1}},cS=async()=>{try{const e=await ms.getState().loadConfig();if((typeof(e==null?void 0:e.proxy_auth_mode)=="string"?e.proxy_auth_mode:nS)!==rS)return await Cu(),!1;const s=await ms.getState().loadProxyAuthStatus({force:!0});return s!=null&&s.configured||await Cu()?!1:(N.setState(o=>({...o,models:[],selectedModel:void 0,modelsError:"Proxy auth mode is set to required. Please configure proxy username/password and apply it.",isLoadingModels:!1})),!0)}catch(e){return console.error("Failed to evaluate startup proxy auth mode:",e),!1}};let Mu=!1;const dS=async(e=!1)=>{if(Mu&&!e)return;Mu=!0,N.getState().startAgentHealthCheck(),N.getState().startSessionsIndexSync(),await N.getState().loadChats(),await cS()||await N.getState().fetchModels(),await N.getState().loadSystemPrompts()},Un={'code[class*="language-"]':{background:"hsl(220, 13%, 18%)",color:"hsl(220, 14%, 71%)",textShadow:"0 1px rgba(0, 0, 0, 0.3)",fontFamily:'"Fira Code", "Fira Mono", Menlo, Consolas, "DejaVu Sans Mono", monospace',direction:"ltr",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",lineHeight:"1.5",MozTabSize:"2",OTabSize:"2",tabSize:"2",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none"},'pre[class*="language-"]':{background:"hsl(220, 13%, 18%)",color:"hsl(220, 14%, 71%)",textShadow:"0 1px rgba(0, 0, 0, 0.3)",fontFamily:'"Fira Code", "Fira Mono", Menlo, Consolas, "DejaVu Sans Mono", monospace',direction:"ltr",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",lineHeight:"1.5",MozTabSize:"2",OTabSize:"2",tabSize:"2",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",padding:"1em",margin:"0.5em 0",overflow:"auto",borderRadius:"0.3em"},'code[class*="language-"]::-moz-selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},'code[class*="language-"] *::-moz-selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},'pre[class*="language-"] *::-moz-selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},'code[class*="language-"]::selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},'code[class*="language-"] *::selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},'pre[class*="language-"] *::selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},':not(pre) > code[class*="language-"]':{padding:"0.2em 0.3em",borderRadius:"0.3em",whiteSpace:"normal"},comment:{color:"hsl(220, 10%, 40%)",fontStyle:"italic"},prolog:{color:"hsl(220, 10%, 40%)"},cdata:{color:"hsl(220, 10%, 40%)"},doctype:{color:"hsl(220, 14%, 71%)"},punctuation:{color:"hsl(220, 14%, 71%)"},entity:{color:"hsl(220, 14%, 71%)",cursor:"help"},"attr-name":{color:"hsl(29, 54%, 61%)"},"class-name":{color:"hsl(29, 54%, 61%)"},boolean:{color:"hsl(29, 54%, 61%)"},constant:{color:"hsl(29, 54%, 61%)"},number:{color:"hsl(29, 54%, 61%)"},atrule:{color:"hsl(29, 54%, 61%)"},keyword:{color:"hsl(286, 60%, 67%)"},property:{color:"hsl(355, 65%, 65%)"},tag:{color:"hsl(355, 65%, 65%)"},symbol:{color:"hsl(355, 65%, 65%)"},deleted:{color:"hsl(355, 65%, 65%)"},important:{color:"hsl(355, 65%, 65%)"},selector:{color:"hsl(95, 38%, 62%)"},string:{color:"hsl(95, 38%, 62%)"},char:{color:"hsl(95, 38%, 62%)"},builtin:{color:"hsl(95, 38%, 62%)"},inserted:{color:"hsl(95, 38%, 62%)"},regex:{color:"hsl(95, 38%, 62%)"},"attr-value":{color:"hsl(95, 38%, 62%)"},"attr-value > .token.punctuation":{color:"hsl(95, 38%, 62%)"},variable:{color:"hsl(207, 82%, 66%)"},operator:{color:"hsl(207, 82%, 66%)"},function:{color:"hsl(207, 82%, 66%)"},url:{color:"hsl(187, 47%, 55%)"},"attr-value > .token.punctuation.attr-equals":{color:"hsl(220, 14%, 71%)"},"special-attr > .token.attr-value > .token.value.css":{color:"hsl(220, 14%, 71%)"},".language-css .token.selector":{color:"hsl(355, 65%, 65%)"},".language-css .token.property":{color:"hsl(220, 14%, 71%)"},".language-css .token.function":{color:"hsl(187, 47%, 55%)"},".language-css .token.url > .token.function":{color:"hsl(187, 47%, 55%)"},".language-css .token.url > .token.string.url":{color:"hsl(95, 38%, 62%)"},".language-css .token.important":{color:"hsl(286, 60%, 67%)"},".language-css .token.atrule .token.rule":{color:"hsl(286, 60%, 67%)"},".language-javascript .token.operator":{color:"hsl(286, 60%, 67%)"},".language-javascript .token.template-string > .token.interpolation > .token.interpolation-punctuation.punctuation":{color:"hsl(5, 48%, 51%)"},".language-json .token.operator":{color:"hsl(220, 14%, 71%)"},".language-json .token.null.keyword":{color:"hsl(29, 54%, 61%)"},".language-markdown .token.url":{color:"hsl(220, 14%, 71%)"},".language-markdown .token.url > .token.operator":{color:"hsl(220, 14%, 71%)"},".language-markdown .token.url-reference.url > .token.string":{color:"hsl(220, 14%, 71%)"},".language-markdown .token.url > .token.content":{color:"hsl(207, 82%, 66%)"},".language-markdown .token.url > .token.url":{color:"hsl(187, 47%, 55%)"},".language-markdown .token.url-reference.url":{color:"hsl(187, 47%, 55%)"},".language-markdown .token.blockquote.punctuation":{color:"hsl(220, 10%, 40%)",fontStyle:"italic"},".language-markdown .token.hr.punctuation":{color:"hsl(220, 10%, 40%)",fontStyle:"italic"},".language-markdown .token.code-snippet":{color:"hsl(95, 38%, 62%)"},".language-markdown .token.bold .token.content":{color:"hsl(29, 54%, 61%)"},".language-markdown .token.italic .token.content":{color:"hsl(286, 60%, 67%)"},".language-markdown .token.strike .token.content":{color:"hsl(355, 65%, 65%)"},".language-markdown .token.strike .token.punctuation":{color:"hsl(355, 65%, 65%)"},".language-markdown .token.list.punctuation":{color:"hsl(355, 65%, 65%)"},".language-markdown .token.title.important > .token.punctuation":{color:"hsl(355, 65%, 65%)"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"},namespace:{Opacity:"0.8"},"token.tab:not(:empty):before":{color:"hsla(220, 14%, 71%, 0.15)",textShadow:"none"},"token.cr:before":{color:"hsla(220, 14%, 71%, 0.15)",textShadow:"none"},"token.lf:before":{color:"hsla(220, 14%, 71%, 0.15)",textShadow:"none"},"token.space:before":{color:"hsla(220, 14%, 71%, 0.15)",textShadow:"none"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item":{marginRight:"0.4em"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > button":{background:"hsl(220, 13%, 26%)",color:"hsl(220, 9%, 55%)",padding:"0.1em 0.4em",borderRadius:"0.3em"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > a":{background:"hsl(220, 13%, 26%)",color:"hsl(220, 9%, 55%)",padding:"0.1em 0.4em",borderRadius:"0.3em"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > span":{background:"hsl(220, 13%, 26%)",color:"hsl(220, 9%, 55%)",padding:"0.1em 0.4em",borderRadius:"0.3em"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > button:hover":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > button:focus":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > a:hover":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > a:focus":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > span:hover":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > span:focus":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},".line-highlight.line-highlight":{background:"hsla(220, 100%, 80%, 0.04)"},".line-highlight.line-highlight:before":{background:"hsl(220, 13%, 26%)",color:"hsl(220, 14%, 71%)",padding:"0.1em 0.6em",borderRadius:"0.3em",boxShadow:"0 2px 0 0 rgba(0, 0, 0, 0.2)"},".line-highlight.line-highlight[data-end]:after":{background:"hsl(220, 13%, 26%)",color:"hsl(220, 14%, 71%)",padding:"0.1em 0.6em",borderRadius:"0.3em",boxShadow:"0 2px 0 0 rgba(0, 0, 0, 0.2)"},"pre[id].linkable-line-numbers.linkable-line-numbers span.line-numbers-rows > span:hover:before":{backgroundColor:"hsla(220, 100%, 80%, 0.04)"},".line-numbers.line-numbers .line-numbers-rows":{borderRightColor:"hsla(220, 14%, 71%, 0.15)"},".command-line .command-line-prompt":{borderRightColor:"hsla(220, 14%, 71%, 0.15)"},".line-numbers .line-numbers-rows > span:before":{color:"hsl(220, 14%, 45%)"},".command-line .command-line-prompt > span:before":{color:"hsl(220, 14%, 45%)"},".rainbow-braces .token.token.punctuation.brace-level-1":{color:"hsl(355, 65%, 65%)"},".rainbow-braces .token.token.punctuation.brace-level-5":{color:"hsl(355, 65%, 65%)"},".rainbow-braces .token.token.punctuation.brace-level-9":{color:"hsl(355, 65%, 65%)"},".rainbow-braces .token.token.punctuation.brace-level-2":{color:"hsl(95, 38%, 62%)"},".rainbow-braces .token.token.punctuation.brace-level-6":{color:"hsl(95, 38%, 62%)"},".rainbow-braces .token.token.punctuation.brace-level-10":{color:"hsl(95, 38%, 62%)"},".rainbow-braces .token.token.punctuation.brace-level-3":{color:"hsl(207, 82%, 66%)"},".rainbow-braces .token.token.punctuation.brace-level-7":{color:"hsl(207, 82%, 66%)"},".rainbow-braces .token.token.punctuation.brace-level-11":{color:"hsl(207, 82%, 66%)"},".rainbow-braces .token.token.punctuation.brace-level-4":{color:"hsl(286, 60%, 67%)"},".rainbow-braces .token.token.punctuation.brace-level-8":{color:"hsl(286, 60%, 67%)"},".rainbow-braces .token.token.punctuation.brace-level-12":{color:"hsl(286, 60%, 67%)"},"pre.diff-highlight > code .token.token.deleted:not(.prefix)":{backgroundColor:"hsla(353, 100%, 66%, 0.15)"},"pre > code.diff-highlight .token.token.deleted:not(.prefix)":{backgroundColor:"hsla(353, 100%, 66%, 0.15)"},"pre.diff-highlight > code .token.token.deleted:not(.prefix)::-moz-selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre.diff-highlight > code .token.token.deleted:not(.prefix) *::-moz-selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre > code.diff-highlight .token.token.deleted:not(.prefix)::-moz-selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre > code.diff-highlight .token.token.deleted:not(.prefix) *::-moz-selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre.diff-highlight > code .token.token.deleted:not(.prefix)::selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre.diff-highlight > code .token.token.deleted:not(.prefix) *::selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre > code.diff-highlight .token.token.deleted:not(.prefix)::selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre > code.diff-highlight .token.token.deleted:not(.prefix) *::selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre.diff-highlight > code .token.token.inserted:not(.prefix)":{backgroundColor:"hsla(137, 100%, 55%, 0.15)"},"pre > code.diff-highlight .token.token.inserted:not(.prefix)":{backgroundColor:"hsla(137, 100%, 55%, 0.15)"},"pre.diff-highlight > code .token.token.inserted:not(.prefix)::-moz-selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre.diff-highlight > code .token.token.inserted:not(.prefix) *::-moz-selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre > code.diff-highlight .token.token.inserted:not(.prefix)::-moz-selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre > code.diff-highlight .token.token.inserted:not(.prefix) *::-moz-selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre.diff-highlight > code .token.token.inserted:not(.prefix)::selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre.diff-highlight > code .token.token.inserted:not(.prefix) *::selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre > code.diff-highlight .token.token.inserted:not(.prefix)::selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre > code.diff-highlight .token.token.inserted:not(.prefix) *::selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},".prism-previewer.prism-previewer:before":{borderColor:"hsl(224, 13%, 17%)"},".prism-previewer-gradient.prism-previewer-gradient div":{borderColor:"hsl(224, 13%, 17%)",borderRadius:"0.3em"},".prism-previewer-color.prism-previewer-color:before":{borderRadius:"0.3em"},".prism-previewer-easing.prism-previewer-easing:before":{borderRadius:"0.3em"},".prism-previewer.prism-previewer:after":{borderTopColor:"hsl(224, 13%, 17%)"},".prism-previewer-flipped.prism-previewer-flipped.after":{borderBottomColor:"hsl(224, 13%, 17%)"},".prism-previewer-angle.prism-previewer-angle:before":{background:"hsl(219, 13%, 22%)"},".prism-previewer-time.prism-previewer-time:before":{background:"hsl(219, 13%, 22%)"},".prism-previewer-easing.prism-previewer-easing":{background:"hsl(219, 13%, 22%)"},".prism-previewer-angle.prism-previewer-angle circle":{stroke:"hsl(220, 14%, 71%)",strokeOpacity:"1"},".prism-previewer-time.prism-previewer-time circle":{stroke:"hsl(220, 14%, 71%)",strokeOpacity:"1"},".prism-previewer-easing.prism-previewer-easing circle":{stroke:"hsl(220, 14%, 71%)",fill:"transparent"},".prism-previewer-easing.prism-previewer-easing path":{stroke:"hsl(220, 14%, 71%)"},".prism-previewer-easing.prism-previewer-easing line":{stroke:"hsl(220, 14%, 71%)"}},{Text:Pu,Paragraph:uS}=le,mS=({content:e,token:t,showGradient:s,onClick:n})=>r.jsx(ee,{size:"small",style:{marginLeft:t.marginLG,marginTop:t.marginXS,backgroundColor:t.colorBgLayout,borderColor:t.colorBorderSecondary},bodyStyle:{padding:t.paddingMD},onClick:n,children:r.jsxs("div",{style:{maxHeight:"60vh",overflowY:"auto",position:"relative",paddingRight:t.paddingXS},children:[r.jsx(hs,{remarkPlugins:[Ii],components:{p:({children:o})=>r.jsx(uS,{style:{marginBottom:t.marginSM},children:o}),ol:({children:o})=>r.jsx("ol",{style:{marginBottom:t.marginSM,paddingLeft:t.paddingLG},children:o}),ul:({children:o})=>r.jsx("ul",{style:{marginBottom:t.marginSM,paddingLeft:t.paddingLG},children:o}),li:({children:o})=>r.jsx("li",{style:{marginBottom:t.marginXS},children:o}),h1:({children:o})=>r.jsx(Pu,{strong:!0,style:{fontSize:t.fontSizeHeading3,marginBottom:t.marginSM,display:"block"},children:o}),h2:({children:o})=>r.jsx(Pu,{strong:!0,style:{fontSize:t.fontSizeHeading4,marginBottom:t.marginSM,display:"block"},children:o}),code:({inline:o,className:a,children:i,...l})=>{const c=/language-(\w+)/.exec(a||"");return o?r.jsx("code",{className:a,style:{backgroundColor:t.colorFillTertiary,padding:"0 4px",borderRadius:t.borderRadiusSM,fontSize:t.fontSizeSM},...l,children:i}):r.jsx(fr,{style:Un,language:(c==null?void 0:c[1])||"text",PreTag:"div",wrapLongLines:!0,children:String(i).replace(/\n$/,"")})}},children:e||"No content available."}),s?r.jsx("div",{style:{position:"sticky",bottom:0,height:48,background:`linear-gradient(180deg, transparent, ${t.colorBgLayout})`,pointerEvents:"none",marginTop:-48}}):null]})}),{Text:ol,Paragraph:hS}=le,pS=({prompt:e,token:t,isSelected:s,isExpanded:n,onSelect:o,onToggleExpand:a,onCopy:i})=>{const{t:l}=ne(),c=e.content||"",{nonEmptyLineCount:d,wordCount:u,characterCount:h,showGradient:p}=m.useMemo(()=>{const y=(c?c.split(/\r?\n/):[]).filter(b=>b.trim().length>0).length,f=c.trim()?c.trim().split(/\s+/).filter(Boolean).length:0,v=c.length;return{nonEmptyLineCount:y,wordCount:f,characterCount:v,showGradient:!n&&v>600}},[c,n]);return r.jsx(nt.Item,{style:{cursor:"pointer",padding:t.paddingMD,borderRadius:t.borderRadius,border:s?`2px solid ${t.colorPrimary}`:`1px solid ${t.colorBorderSecondary}`,marginBottom:t.marginXS,backgroundColor:s?t.colorPrimaryBg:t.colorBgContainer,transition:"all 0.2s ease"},onClick:()=>o(e.id),children:r.jsxs(X,{direction:"vertical",style:{width:"100%"},size:t.marginSM,children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",width:"100%",gap:t.marginSM},children:[r.jsxs(X,{align:"start",children:[r.jsx(ts,{checked:s,onChange:()=>o(e.id),onClick:g=>g.stopPropagation()}),r.jsxs("div",{children:[r.jsx(ol,{strong:!0,children:e.name||e.id}),r.jsx("div",{children:r.jsx(ol,{code:!0,style:{fontSize:t.fontSizeSM,color:t.colorTextSecondary},children:e.id})})]}),e.isDefault?r.jsx(oe,{color:"warning",children:l("chat.systemPromptSelector.defaultTag")}):null]}),r.jsxs(X,{size:"small",children:[r.jsx(Y,{type:"text",size:"small",icon:n?r.jsx(nx,{}):r.jsx(td,{}),onClick:g=>{g.stopPropagation(),a(e.id)},children:l(n?"chat.systemPromptSelector.hide":"chat.systemPromptSelector.preview")}),r.jsx(Y,{type:"text",size:"small",icon:r.jsx(ss,{}),onClick:g=>i(g,e),children:l("chat.systemPromptSelector.copy")})]})]}),e.description?r.jsx(ol,{type:"secondary",style:{marginLeft:t.marginLG,fontSize:t.fontSizeSM},children:e.description}):null,r.jsxs(X,{size:"small",wrap:!0,style:{marginLeft:t.marginLG},children:[r.jsx(oe,{color:"processing",children:l("chat.systemPromptSelector.lines",{count:d})}),r.jsx(oe,{color:"purple",children:l("chat.systemPromptSelector.words",{count:u})}),r.jsx(oe,{color:"success",children:l("chat.systemPromptSelector.chars",{count:h})})]}),n?r.jsx(mS,{content:c,token:t,showGradient:p,onClick:g=>g.stopPropagation()}):r.jsx(hS,{type:"secondary",ellipsis:{rows:3},style:{marginLeft:t.marginLG,marginBottom:0,color:t.colorTextSecondary},children:c||l("chat.systemPromptSelector.noContent")})]})},e.id)},{Text:fS}=le,{useToken:gS}=he,yS=({open:e,onClose:t,onSelect:s,prompts:n,title:o,showCancelButton:a=!0})=>{const{t:i}=ne(),{token:l}=gS(),[c,d]=fe.useMessage(),u=N(k=>k.lastSelectedPromptId),h=N(k=>k.setLastSelectedPromptId),[p,g]=m.useState(null),[y,f]=m.useState(null),v=m.useMemo(()=>n.filter(k=>k.id&&k.id.trim()!==""),[n]),b=async(k,C)=>{k.stopPropagation();const E=C.content??"";try{await os(E),c.success(i("success.promptCopied",{name:C.name}))}catch(j){console.error("[SystemPromptSelector] Failed to copy prompt:",j),c.error(i("error.copyPromptFailed"))}},x=o??i("chat.prompt.selectorTitle");m.useEffect(()=>{if(e){const k=v.find(E=>E.isDefault),C=u||(k==null?void 0:k.id)||(v.length>0?v[0].id:null);g(C)}},[e,u,v.length]);const _=k=>{g(k.id),h(k.id),s(k),t()},w=()=>{t()};return r.jsxs(r.Fragment,{children:[d,r.jsxs(Lt,{title:r.jsxs(X,{children:[r.jsx(Sr,{}),x]}),open:e,onCancel:w,width:700,footer:r.jsx(Qx,{buttons:[...a?[Zx(w)]:[],ev(()=>{const k=v.find(C=>C.id===p);k&&_(k)},{text:i("chat.prompt.createButton"),disabled:!p})]}),styles:{body:{maxHeight:"70vh",overflowY:"auto",padding:l.paddingMD}},children:[r.jsx("div",{style:{marginBottom:l.marginMD},children:r.jsx(fS,{type:"secondary",style:{fontSize:l.fontSizeSM},children:i("chat.prompt.helperText")})}),v.length===0?r.jsx(kt,{description:i("chat.prompt.emptyDescription"),style:{margin:l.marginLG}}):r.jsx("div",{children:v.map(k=>r.jsx(pS,{prompt:k,token:l,isSelected:p===k.id,isExpanded:y===k.id,onSelect:C=>g(C),onToggleExpand:C=>f(y===C?null:C),onCopy:b},k.id))})]})]})},bS=({chat:e,isSelected:t,onSelect:s,onDelete:n,onPin:o,onUnpin:a,onEdit:i,onGenerateTitle:l,onRunProjectDream:c,isGeneratingTitle:d,isRunningProjectDream:u,titleGenerationError:h})=>{const{t:p}=ne(),[g,y]=m.useState(!1),[f,v]=m.useState(e.title),[b,x]=m.useState(!1),[_,w]=m.useState(!1),{token:k}=he.useToken(),C=m.useCallback(S=>{S.stopPropagation(),i&&f.trim()&&i(e.id,f.trim()),y(!1)},[e.id,f,i]),E=m.useCallback(S=>{S.stopPropagation(),v(e.title),y(!1)},[e.title]),j=[{key:"pin",icon:e.pinned?r.jsx(sc,{style:{color:k.colorWarning}}):r.jsx(sd,{}),label:e.pinned?p("chat.actions.unpin"):p("chat.actions.pin"),onClick:({domEvent:S})=>{S.stopPropagation(),e.pinned?a(e.id):o(e.id)}},{key:"edit",icon:r.jsx(ca,{}),label:p("chat.chatItem.edit"),onClick:({domEvent:S})=>{S.stopPropagation(),y(!0)}},...l?[{key:"generate-title",icon:d?r.jsx(gr,{}):r.jsx(ff,{style:h?{color:k.colorError}:void 0}),label:h||p("chat.actions.generateTitle"),disabled:d,onClick:({domEvent:S})=>{S.stopPropagation(),l(e.id)}}]:[],...c?[{key:"run-project-dream",icon:u?r.jsx(gr,{}):r.jsx(rx,{}),label:p("chat.actions.runProjectDream"),disabled:u,onClick:({domEvent:S})=>{S.stopPropagation(),c(e.id)}}]:[],{type:"divider"},{key:"delete",icon:r.jsx(dn,{}),label:p("common.delete"),danger:!0,onClick:({domEvent:S})=>{S.stopPropagation(),n(e.id)}}],R={padding:"8px 12px",borderRadius:k.borderRadiusSM,marginBottom:k.marginXXS,cursor:"pointer",transition:"all 0.2s cubic-bezier(0.4, 0, 0.2, 1)",backgroundColor:t?"var(--lotus-primary-soft)":b||_?"var(--lotus-item-hover-bg)":"transparent",border:"1px solid transparent",borderColor:t?"var(--lotus-tool-card-border)":b||_?k.colorBorderSecondary:"transparent",position:"relative",overflow:"visible",boxShadow:t?"var(--lotus-tool-card-shadow)":"none",transform:b&&!t?"translateX(2px)":"none"},M={flex:1,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",fontSize:13,fontWeight:t?600:500,color:t?"var(--lotus-primary)":k.colorText},T={flex:1,fontSize:k.fontSizeSM,marginRight:k.marginSM},P=g?[r.jsx(Y,{type:"text",size:"small",icon:r.jsx(ox,{style:{color:k.colorSuccess}}),onClick:C,"aria-label":p("common.save")},"save"),r.jsx(Y,{type:"text",size:"small",icon:r.jsx(wr,{style:{color:k.colorError}}),onClick:E,"aria-label":p("common.cancel")},"cancel")]:b||_?[r.jsx(zn,{menu:{items:j,className:"lotus-sidebar-actions-menu"},trigger:["click"],placement:"bottomRight",overlayClassName:"lotus-sidebar-actions-dropdown",open:_,onOpenChange:S=>w(S),children:r.jsx(Y,{type:"text",size:"small",icon:r.jsx(ax,{}),"aria-label":p("common.moreActions","More actions"),onClick:S=>S.stopPropagation(),style:{color:k.colorTextSecondary,borderRadius:k.borderRadiusSM,background:k.colorFillTertiary,width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center"}})},"more")]:[];return r.jsx(nt.Item,{style:R,tabIndex:0,onClick:()=>!g&&s(e.id),onKeyDown:S=>{S.key==="Enter"&&!g?(S.preventDefault(),s(e.id)):(S.key==="Delete"||S.key==="Backspace")&&!g&&S.metaKey&&(S.preventDefault(),n(e.id))},onMouseEnter:()=>x(!0),onMouseLeave:()=>{_||x(!1)},onFocus:()=>x(!0),onBlur:()=>{_||x(!1)},actions:P,"data-testid":"chat-item",role:"option","aria-selected":t,"aria-label":e.title||p("chat.sidebar.untitledChat"),children:r.jsx(nt.Item.Meta,{title:g?r.jsx(me,{value:f,onChange:S=>v(S.target.value),onClick:S=>S.stopPropagation(),onPressEnter:S=>{S.preventDefault(),C(S)},autoFocus:!0,style:T,variant:"borderless",size:"small"}):r.jsxs("div",{style:{...M,display:"flex",alignItems:"center",gap:k.marginXS,minWidth:0},children:[e.pinned&&r.jsx(sc,{style:{color:k.colorWarning,fontSize:11,flexShrink:0}}),r.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.title}),e.kind==="child"?r.jsx(oe,{color:"processing",style:{marginInlineEnd:0,flex:"0 0 auto"},children:p("chat.chatItem.childTag")}):null]})})})},xS=(e,t)=>e.chat.id===t.chat.id&&e.chat.title===t.chat.title&&e.chat.pinned===t.chat.pinned&&e.isSelected===t.isSelected&&e.isGeneratingTitle===t.isGeneratingTitle&&e.isRunningProjectDream===t.isRunningProjectDream&&e.titleGenerationError===t.titleGenerationError,dc=m.memo(bS,xS);dc.displayName="ChatItem";const Eu=e=>({Today:0,Yesterday:1,"This Week":2,"This Month":3})[e]??4,vS=e=>{const t={},s=e.filter(o=>o.pinned);s.length>0&&(t.Pinned=s.sort((o,a)=>a.createdAt-o.createdAt));const n=e.filter(o=>!o.pinned&&!!o.createdByScheduleId);return n.length>0&&(t.Scheduled=n.sort((o,a)=>a.createdAt-o.createdAt)),e.filter(o=>!o.pinned&&!o.createdByScheduleId).forEach(o=>{const i=new Date(o.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"});t[i]||(t[i]=[]),t[i].push(o)}),Object.keys(t).forEach(o=>{t[o].sort((a,i)=>i.createdAt-a.createdAt)}),t},SS=e=>{const t=s=>Array.isArray(s)?s.reduce((n,o)=>Math.max(n,o.createdAt),0):Object.values(s).reduce((n,o)=>{const a=o.reduce((i,l)=>Math.max(i,l.createdAt),0);return Math.max(n,a)},0);return Object.keys(e).sort((s,n)=>{if(s==="Pinned")return-1;if(n==="Pinned")return 1;if(s==="Scheduled")return-1;if(n==="Scheduled")return 1;const o=e[s],a=e[n];if(!o||!a)return 0;const i=t(o),l=t(a);return i!==l?l-i:Eu(s)-Eu(n)})},wS=(e,t)=>e[t]?e[t].map(s=>s.id):[],Hf=(e,t)=>e[t]?e[t].length:0,Ru=e=>e.pinned?"Pinned":e.createdByScheduleId?"Scheduled":new Date(e.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),Au=(e,t)=>{const n={Today:"chat.sidebar.dateGroups.today",Yesterday:"chat.sidebar.dateGroups.yesterday","This Week":"chat.sidebar.dateGroups.thisWeek","This Month":"chat.sidebar.dateGroups.thisMonth",Pinned:"chat.sidebar.dateGroups.pinned",Scheduled:"chat.sidebar.dateGroups.scheduled"}[e];return n?t(n):e},_S=({groupedChatsByDate:e,childrenByRoot:t,expandedRootIds:s,onToggleRootExpanded:n,sortedDateKeys:o,expandedKeys:a,onCollapseChange:i,currentSessionId:l,onSelectChat:c,onDeleteChat:d,onDeleteByDate:u,onPinChat:h,onUnpinChat:p,onEditTitle:g,onGenerateTitle:y,onRunProjectDream:f,titleGenerationState:v,projectDreamState:b,token:x,hasActiveFilters:_})=>{const{t:w}=ne(),k=m.useMemo(()=>o.length?o.map(E=>{const j=e[E],R=Hf(e,E);return{dateKey:E,dateGroup:j,totalChatsInDate:R}}):[],[e,o]);if(!o.length)return r.jsx(kt,{image:kt.PRESENTED_IMAGE_SIMPLE,description:r.jsxs(X,{direction:"vertical",size:4,align:"center",children:[r.jsx("span",{style:{color:x.colorTextSecondary},children:_?w("chat.sidebar.empty.noMatches","No matching sessions"):w("chat.sidebar.empty.noSessions")}),r.jsx("span",{style:{color:x.colorTextSecondary,fontSize:12},children:_?w("chat.sidebar.empty.filterHint","Try adjusting your search or filters"):w("chat.sidebar.empty.hint")}),_&&r.jsx(Y,{size:"small",type:"link",onClick:()=>{var j;const E=document.querySelector('[data-testid="sidebar-search-input"] input, .lotus-sidebar-search input');if(E){const R=(j=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value"))==null?void 0:j.set;R==null||R.call(E,""),E.dispatchEvent(new Event("input",{bubbles:!0}))}},children:w("chat.sidebar.empty.clearFilters","Clear filters")})]})});const C=new Set(a);return r.jsx(X,{direction:"vertical",size:"small",style:{width:"100%"},children:k.map(({dateKey:E,dateGroup:j,totalChatsInDate:R})=>{const M=C.has(E);return r.jsxs("div",{style:{borderRadius:x.borderRadiusSM,background:M?x.colorFillTertiary:"transparent",padding:4},children:[r.jsxs(G,{align:"center",justify:"space-between",style:{cursor:"pointer",padding:"8px 12px",borderRadius:x.borderRadiusSM,transition:"all 0.2s ease",border:"1px solid transparent"},role:"button",tabIndex:0,"aria-expanded":M,"aria-label":`${Au(E,w)} (${R})`,onKeyDown:T=>{if(T.key==="Enter"||T.key===" "){T.preventDefault();const P=new Set(C);P.has(E)?P.delete(E):P.add(E),i(Array.from(P))}},onMouseEnter:T=>{T.currentTarget.style.background="var(--lotus-sidebar-item-hover-bg, rgba(204, 251, 241, 0.92))",T.currentTarget.style.borderColor="var(--lotus-sidebar-item-hover-border, rgba(13, 148, 136, 0.28))";const P=T.currentTarget.querySelector(".chat-sidebar-date-group-delete");P&&(P.style.opacity="1")},onMouseLeave:T=>{T.currentTarget.style.background="transparent",T.currentTarget.style.borderColor="transparent";const P=T.currentTarget.querySelector(".chat-sidebar-date-group-delete");P&&(P.style.opacity="0")},onClick:()=>{const T=new Set(C);T.has(E)?T.delete(E):T.add(E),i(Array.from(T))},className:"chat-sidebar-date-group-header",children:[r.jsxs(G,{align:"center",gap:"small",style:{minWidth:0},children:[M?r.jsx(Wt,{style:{fontSize:12,opacity:.6}}):r.jsx(Ws,{style:{fontSize:12,opacity:.6}}),r.jsxs("span",{style:{fontSize:12,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:E==="Today"?"var(--lotus-primary)":x.colorTextSecondary,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[Au(E,w)," (",R,")"]})]}),r.jsx(Y,{type:"text",size:"small",icon:r.jsx(dn,{}),className:"chat-sidebar-date-group-delete",style:{color:x.colorTextTertiary,opacity:0,transition:"opacity 0.2s ease"},onClick:T=>{T.stopPropagation(),u(E)}})]}),M?r.jsx("div",{style:{marginTop:4},children:r.jsx(nt,{itemLayout:"horizontal",dataSource:j,split:!1,renderItem:T=>{var P,S,L,$,I,W;return r.jsxs("div",{children:[r.jsxs(G,{align:"center",gap:6,children:[(P=t[T.id])!=null&&P.length?r.jsx(Y,{size:"small",type:"text",style:{padding:0,width:22},"aria-label":s.has(T.id)?w("chat.sidebar.actions.collapseChildren"):w("chat.sidebar.actions.expandChildren"),onClick:A=>{A.preventDefault(),A.stopPropagation(),n(T.id)},children:s.has(T.id)?r.jsx(Wt,{}):r.jsx(Ws,{})}):r.jsx("div",{style:{width:22}}),r.jsx("div",{style:{flex:1,minWidth:0},children:r.jsx(dc,{chat:T,isSelected:T.id===l,onSelect:c,onDelete:d,onPin:h,onUnpin:p,onEdit:g,onGenerateTitle:y,onRunProjectDream:f,isGeneratingTitle:((S=v[T.id])==null?void 0:S.status)==="loading",isRunningProjectDream:((L=b[T.id])==null?void 0:L.status)==="loading",titleGenerationError:(($=v[T.id])==null?void 0:$.status)==="error"?(I=v[T.id])==null?void 0:I.error:void 0})})]}),s.has(T.id)&&(((W=t[T.id])==null?void 0:W.length)??0)>0?r.jsx("div",{style:{marginLeft:22,marginTop:2},children:r.jsx(nt,{itemLayout:"horizontal",dataSource:t[T.id],split:!1,renderItem:A=>{var O,D,H,B;return r.jsx("div",{style:{paddingLeft:12},children:r.jsx(dc,{chat:A,isSelected:A.id===l,onSelect:c,onDelete:d,onPin:h,onUnpin:p,onEdit:g,onGenerateTitle:y,onRunProjectDream:f,isGeneratingTitle:((O=v[A.id])==null?void 0:O.status)==="loading",isRunningProjectDream:((D=b[A.id])==null?void 0:D.status)==="loading",titleGenerationError:((H=v[A.id])==null?void 0:H.status)==="error"?(B=v[A.id])==null?void 0:B.error:void 0})},A.id)}})}):null]},T.id)}})}):null]},E)})})},TS="copilot_ui_theme_v1";function kS(){var e;try{const t=localStorage.getItem(TS);if(t==="light"||t==="dark")return t}catch{}return(e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}const qn=un(e=>({themeMode:kS(),setThemeMode:t=>e({themeMode:t}),toggleTheme:()=>e(t=>({themeMode:t.themeMode==="dark"?"light":"dark"}))})),jS="2026.4.27",CS={version:jS},xd=CS.version,{Text:MS}=le,PS=({collapsed:e,onNewChat:t,onOpenSettings:s,screens:n,token:o})=>{const{t:a}=ne(),i=qn(h=>h.themeMode),l=qn(h=>h.toggleTheme),c=a("chat.sidebar.newSession"),d=a("settings.page.title"),u=i==="dark"?a("settings.app.lightMode","Light mode"):a("settings.app.darkMode","Dark mode");return r.jsxs(G,{vertical:!0,gap:e?"small":"middle",style:{padding:e?10:16,background:"transparent",borderTop:`1px solid ${o.colorBorderSecondary}`},children:[r.jsx(Y,{"data-testid":"new-chat","data-tour-id":"new-session",type:"primary",icon:r.jsx(Us,{}),onClick:t,block:!e,shape:"default",size:e?"large":n.xs?"small":"middle",title:c,"aria-label":c,className:"lotus-primary-cta",style:{...e?{width:"44px",height:"44px",margin:"0 auto"}:{},borderRadius:o.borderRadiusLG,minHeight:e?44:46,fontWeight:600},children:!e&&c}),r.jsxs(G,{gap:8,align:"center",children:[r.jsx(Y,{"data-testid":"open-settings","data-tour-id":"open-settings",icon:r.jsx(da,{}),onClick:s,block:!e,shape:"default",size:e?"large":n.xs?"small":"middle",title:d,"aria-label":d,className:"lotus-secondary-button",style:{...e?{width:"44px",height:"44px",margin:"0 auto"}:{},borderRadius:o.borderRadiusLG,minHeight:44,flex:e?void 0:1},children:!e&&d}),!e&&r.jsx(ke,{title:u,placement:"top",children:r.jsx(Y,{"data-testid":"toggle-theme",type:"text",icon:i==="dark"?r.jsx(ix,{}):r.jsx(lx,{}),onClick:l,"aria-label":u,className:"lotus-toolbar-icon",style:{width:44,height:44,borderRadius:o.borderRadiusLG,flexShrink:0}})})]}),!e&&r.jsxs(MS,{type:"secondary","data-testid":"app-version-badge",style:{fontSize:o.fontSizeSM,textAlign:"center",userSelect:"text"},children:[a("settings.appTab.runningVersion","Running version"),": v",xd]})]})},Iu="provider",Bs=un(e=>({isOpen:!1,origin:"chat",activeTabKey:Iu,open:(t,s=Iu)=>e({isOpen:!0,origin:t,activeTabKey:s}),close:()=>e({isOpen:!1}),setActiveTabKey:t=>e({activeTabKey:t})}));function ve(e,t,s,n,o){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,s),s}function q(e,t,s,n){if(s==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return s==="m"?n:s==="a"?n.call(e):n?n.value:t.get(e)}let Yf=function(){const{crypto:e}=globalThis;if(e!=null&&e.randomUUID)return Yf=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),s=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^s()&15>>+n/4).toString(16))};function uc(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const mc=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};class Se extends Error{}class St extends Se{constructor(t,s,n,o){super(`${St.makeMessage(t,s,n)}`),this.status=t,this.headers=o,this.requestID=o==null?void 0:o.get("x-request-id"),this.error=s;const a=s;this.code=a==null?void 0:a.code,this.param=a==null?void 0:a.param,this.type=a==null?void 0:a.type}static makeMessage(t,s,n){const o=s!=null&&s.message?typeof s.message=="string"?s.message:JSON.stringify(s.message):s?JSON.stringify(s):n;return t&&o?`${t} ${o}`:t?`${t} status code (no body)`:o||"(no status code or body)"}static generate(t,s,n,o){if(!t||!o)return new Fi({message:n,cause:mc(s)});const a=s==null?void 0:s.error;return t===400?new Xf(t,a,n,o):t===401?new Vf(t,a,n,o):t===403?new Kf(t,a,n,o):t===404?new Gf(t,a,n,o):t===409?new Jf(t,a,n,o):t===422?new Qf(t,a,n,o):t===429?new Zf(t,a,n,o):t>=500?new eg(t,a,n,o):new St(t,a,n,o)}}class Qt extends St{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}}class Fi extends St{constructor({message:t,cause:s}){super(void 0,void 0,t||"Connection error.",void 0),s&&(this.cause=s)}}class vd extends Fi{constructor({message:t}={}){super({message:t??"Request timed out."})}}class Xf extends St{}class Vf extends St{}class Kf extends St{}class Gf extends St{}class Jf extends St{}class Qf extends St{}class Zf extends St{}class eg extends St{}class tg extends Se{constructor(){super("Could not parse response content as the length limit was reached")}}class sg extends Se{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Lo extends Error{constructor(t){super(t)}}const ES=/^[a-z][a-z0-9+.-]*:/i,RS=e=>ES.test(e);let $t=e=>($t=Array.isArray,$t(e)),$u=$t;function AS(e){return typeof e!="object"?{}:e??{}}function IS(e){if(!e)return!0;for(const t in e)return!1;return!0}function $S(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function al(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}const DS=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new Se(`${e} must be an integer`);if(t<0)throw new Se(`${e} must be a positive integer`);return t},LS=e=>{try{return JSON.parse(e)}catch{return}},ga=e=>new Promise(t=>setTimeout(t,e)),ir="5.10.2",OS=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function FS(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const zS=()=>{var s;const e=FS();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ir,"X-Stainless-OS":Lu(Deno.build.os),"X-Stainless-Arch":Du(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((s=Deno.version)==null?void 0:s.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ir,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ir,"X-Stainless-OS":Lu(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Du(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=NS();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ir,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ir,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function NS(){if(typeof navigator>"u"||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:s}of e){const n=s.exec(navigator.userAgent);if(n){const o=n[1]||0,a=n[2]||0,i=n[3]||0;return{browser:t,version:`${o}.${a}.${i}`}}}return null}const Du=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",Lu=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown");let Ou;const BS=()=>Ou??(Ou=zS());function WS(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function ng(...e){const t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function rg(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return ng({start(){},async pull(s){const{done:n,value:o}=await t.next();n?s.close():s.enqueue(o)},async cancel(){var s;await((s=t.return)==null?void 0:s.call(t))}})}function og(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const s=await t.read();return s!=null&&s.done&&t.releaseLock(),s}catch(s){throw t.releaseLock(),s}},async return(){const s=t.cancel();return t.releaseLock(),await s,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function US(e){var n,o;if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await((o=(n=e[Symbol.asyncIterator]()).return)==null?void 0:o.call(n));return}const t=e.getReader(),s=t.cancel();t.releaseLock(),await s}const qS=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),ag="RFC3986",ig=e=>String(e),Fu={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:ig},HS="RFC1738";let hc=(e,t)=>(hc=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),hc(e,t));const xs=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),il=1024,YS=(e,t,s,n,o)=>{if(e.length===0)return e;let a=e;if(typeof e=="symbol"?a=Symbol.prototype.toString.call(e):typeof e!="string"&&(a=String(e)),s==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let i="";for(let l=0;l<a.length;l+=il){const c=a.length>=il?a.slice(l,l+il):a,d=[];for(let u=0;u<c.length;++u){let h=c.charCodeAt(u);if(h===45||h===46||h===95||h===126||h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||o===HS&&(h===40||h===41)){d[d.length]=c.charAt(u);continue}if(h<128){d[d.length]=xs[h];continue}if(h<2048){d[d.length]=xs[192|h>>6]+xs[128|h&63];continue}if(h<55296||h>=57344){d[d.length]=xs[224|h>>12]+xs[128|h>>6&63]+xs[128|h&63];continue}u+=1,h=65536+((h&1023)<<10|c.charCodeAt(u)&1023),d[d.length]=xs[240|h>>18]+xs[128|h>>12&63]+xs[128|h>>6&63]+xs[128|h&63]}i+=d.join("")}return i};function XS(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function zu(e,t){if($t(e)){const s=[];for(let n=0;n<e.length;n+=1)s.push(t(e[n]));return s}return t(e)}const lg={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},cg=function(e,t){Array.prototype.push.apply(e,$t(t)?t:[t])};let Nu;const dt={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:YS,encodeValuesOnly:!1,format:ag,formatter:ig,indices:!1,serializeDate(e){return(Nu??(Nu=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function VS(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}const ll={};function dg(e,t,s,n,o,a,i,l,c,d,u,h,p,g,y,f,v,b){let x=e,_=b,w=0,k=!1;for(;(_=_.get(ll))!==void 0&&!k;){const M=_.get(e);if(w+=1,typeof M<"u"){if(M===w)throw new RangeError("Cyclic object value");k=!0}typeof _.get(ll)>"u"&&(w=0)}if(typeof d=="function"?x=d(t,x):x instanceof Date?x=p==null?void 0:p(x):s==="comma"&&$t(x)&&(x=zu(x,function(M){return M instanceof Date?p==null?void 0:p(M):M})),x===null){if(a)return c&&!f?c(t,dt.encoder,v,"key",g):t;x=""}if(VS(x)||XS(x)){if(c){const M=f?t:c(t,dt.encoder,v,"key",g);return[(y==null?void 0:y(M))+"="+(y==null?void 0:y(c(x,dt.encoder,v,"value",g)))]}return[(y==null?void 0:y(t))+"="+(y==null?void 0:y(String(x)))]}const C=[];if(typeof x>"u")return C;let E;if(s==="comma"&&$t(x))f&&c&&(x=zu(x,c)),E=[{value:x.length>0?x.join(",")||null:void 0}];else if($t(d))E=d;else{const M=Object.keys(x);E=u?M.sort(u):M}const j=l?String(t).replace(/\./g,"%2E"):String(t),R=n&&$t(x)&&x.length===1?j+"[]":j;if(o&&$t(x)&&x.length===0)return R+"[]";for(let M=0;M<E.length;++M){const T=E[M],P=typeof T=="object"&&typeof T.value<"u"?T.value:x[T];if(i&&P===null)continue;const S=h&&l?T.replace(/\./g,"%2E"):T,L=$t(x)?typeof s=="function"?s(R,S):R:R+(h?"."+S:"["+S+"]");b.set(e,w);const $=new WeakMap;$.set(ll,b),cg(C,dg(P,L,s,n,o,a,i,l,s==="comma"&&f&&$t(x)?null:c,d,u,h,p,g,y,f,v,$))}return C}function KS(e=dt){if(typeof e.allowEmptyArrays<"u"&&typeof e.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof e.encodeDotInKeys<"u"&&typeof e.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&typeof e.encoder<"u"&&typeof e.encoder!="function")throw new TypeError("Encoder has to be a function.");const t=e.charset||dt.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let s=ag;if(typeof e.format<"u"){if(!hc(Fu,e.format))throw new TypeError("Unknown format option provided.");s=e.format}const n=Fu[s];let o=dt.filter;(typeof e.filter=="function"||$t(e.filter))&&(o=e.filter);let a;if(e.arrayFormat&&e.arrayFormat in lg?a=e.arrayFormat:"indices"in e?a=e.indices?"indices":"repeat":a=dt.arrayFormat,"commaRoundTrip"in e&&typeof e.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof e.allowDots>"u"?e.encodeDotInKeys?!0:dt.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:dt.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:dt.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:dt.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?dt.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:dt.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:dt.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:dt.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:dt.encodeValuesOnly,filter:o,format:s,formatter:n,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:dt.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:dt.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:dt.strictNullHandling}}function GS(e,t={}){let s=e;const n=KS(t);let o,a;typeof n.filter=="function"?(a=n.filter,s=a("",s)):$t(n.filter)&&(a=n.filter,o=a);const i=[];if(typeof s!="object"||s===null)return"";const l=lg[n.arrayFormat],c=l==="comma"&&n.commaRoundTrip;o||(o=Object.keys(s)),n.sort&&o.sort(n.sort);const d=new WeakMap;for(let p=0;p<o.length;++p){const g=o[p];n.skipNulls&&s[g]===null||cg(i,dg(s[g],g,l,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,d))}const u=i.join(n.delimiter);let h=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),u.length>0?h+u:""}function JS(e){let t=0;for(const o of e)t+=o.length;const s=new Uint8Array(t);let n=0;for(const o of e)s.set(o,n),n+=o.length;return s}let Bu;function Sd(e){let t;return(Bu??(t=new globalThis.TextEncoder,Bu=t.encode.bind(t)))(e)}let Wu;function Uu(e){let t;return(Wu??(t=new globalThis.TextDecoder,Wu=t.decode.bind(t)))(e)}var Ft,zt;class zi{constructor(){Ft.set(this,void 0),zt.set(this,void 0),ve(this,Ft,new Uint8Array),ve(this,zt,null)}decode(t){if(t==null)return[];const s=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Sd(t):t;ve(this,Ft,JS([q(this,Ft,"f"),s]));const n=[];let o;for(;(o=QS(q(this,Ft,"f"),q(this,zt,"f")))!=null;){if(o.carriage&&q(this,zt,"f")==null){ve(this,zt,o.index);continue}if(q(this,zt,"f")!=null&&(o.index!==q(this,zt,"f")+1||o.carriage)){n.push(Uu(q(this,Ft,"f").subarray(0,q(this,zt,"f")-1))),ve(this,Ft,q(this,Ft,"f").subarray(q(this,zt,"f"))),ve(this,zt,null);continue}const a=q(this,zt,"f")!==null?o.preceding-1:o.preceding,i=Uu(q(this,Ft,"f").subarray(0,a));n.push(i),ve(this,Ft,q(this,Ft,"f").subarray(o.index)),ve(this,zt,null)}return n}flush(){return q(this,Ft,"f").length?this.decode(`
|
|
12
|
+
`):void 0,ocrError:f.error?String(f.error):void 0})}const g=[];for(const f of u.content_parts||[]){if(f.type!=="image_url")continue;const v=((i=f.image_url)==null?void 0:i.url)||"";if(!v)continue;const b=Av(v),x=Af(v),_=p.get(v.trim());g.push({id:Ev(),url:b,ocrText:_==null?void 0:_.ocrText,ocrError:_==null?void 0:_.ocrError,name:x?`attachment-${x.attachmentId}`:"image",size:0,type:"image/*"})}const y={role:"user",id:u.id,createdAt:h,content:u.content||"",images:g.length?g:void 0,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(y);continue}if(u.role==="assistant"){const p=u.tool_calls||[];if(p.length>0){const f=(u.content||"").trim(),v=typeof u.reasoning=="string"&&u.reasoning.trim().length>0;if(f||v){const w=v?{reasoning:u.reasoning,backendMessageId:u.id}:{backendMessageId:u.id},k={role:"assistant",type:"text",id:`${u.id}_text`,createdAt:h,content:u.content||"",metadata:w,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(k)}for(const w of p)w.id&&s.set(w.id,jn((l=w.function)==null?void 0:l.name)||tl);const b=(c=p[0])==null?void 0:c.id,x=b?n.get(b):void 0,_={role:"assistant",type:"tool_call",id:u.id,createdAt:h,toolCalls:p.map(w=>{var k;return{toolCallId:w.id,toolName:jn((k=w.function)==null?void 0:k.name)||tl,parameters:(()=>{var C,E;try{return JSON.parse(((C=w.function)==null?void 0:C.arguments)||"{}")}catch{return{raw:((E=w.function)==null?void 0:E.arguments)||""}}})(),streamingOutput:""}}),...x?{metadata:x}:{},isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(_);continue}const g=typeof u.reasoning=="string"&&u.reasoning.trim().length>0?{reasoning:u.reasoning}:{},y={role:"assistant",type:"text",id:u.id,createdAt:h,content:u.content||"",metadata:g,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(y);continue}if(u.role==="tool"){const p=((d=u.tool_call_id)==null?void 0:d.trim())||`orphan-tool-call:${u.id}`,g=jn(s.get(p))||jn(u.tool_name)||jn(u.name)||Iv(u.content)||tl,y=u.tool_success===!1||u.tool_success==null&&typeof u.content=="string"&&u.content.trimStart().startsWith("Error:"),f={role:"assistant",type:"tool_result",id:u.id,createdAt:h,toolName:g,toolCallId:p,result:{tool_name:g,result:u.content||"",display_preference:"Default"},isError:y,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(f);continue}}return o},Dv=(e,t)=>({chats:[],currentSessionId:null,latestActiveSessionId:null,processingChats:new Set,autoGenerateTitles:!0,isUpdatingAutoTitlePreference:!1,subSessionsByParent:{},addChat:async s=>{var p,g,y,f,v,b;const n=(s.title||es.t("chat.sidebar.newSession")).trim(),o=((g=(p=s.config)==null?void 0:p.baseSystemPrompt)==null?void 0:g.trim())||"",a=(y=Ee.getState().getActiveModel())==null?void 0:y.trim(),i=((v=(f=s.config)==null?void 0:f.model)==null?void 0:v.trim())||a||void 0,l=((b=s.config)==null?void 0:b.reasoningEffort)??void 0;let c,d;if(Ee.getState().isProviderModelRefEnabled()){const x=Ee.getState().selectedModelRef;if(x)c=x,d=x.provider;else{const _=Ee.getState().getActiveModel();_&&(c={provider:Ee.getState().currentProvider,model:_},d=Ee.getState().currentProvider)}}const u=await Gs.createSession({title:n,system_prompt:o||void 0,model:i,model_ref:c,provider:d,reasoning_effort:l||void 0}),h={...sl(u.session),title:n,config:{...s.config,model:u.session.model,model_ref:u.session.model_ref??null,reasoningEffort:u.session.reasoning_effort??null,baseSystemPrompt:o||Rf},messages:[],currentInteraction:null};return e(x=>{const _=[h,...x.chats.filter(w=>w.id!==h.id)];return{...x,chats:_,currentSessionId:h.id,latestActiveSessionId:h.id}}),h.id},selectSession:s=>{const n=t();n.currentSessionId===s&&n.latestActiveSessionId===s||e({currentSessionId:s,latestActiveSessionId:s})},deleteSession:async s=>{try{await Gs.deleteSession(s)}catch(n){console.error(`[ChatSlice] Failed to delete backend session ${s}:`,n)}e(n=>{var c;const o=new Set;for(const d of n.chats)d.id===s&&o.add(d.id),d.rootSessionId===s&&o.add(d.id);const a=n.chats.filter(d=>!o.has(d.id)),i=n.currentSessionId&&o.has(n.currentSessionId)?null:n.currentSessionId,l=n.latestActiveSessionId&&o.has(n.latestActiveSessionId)?((c=a[0])==null?void 0:c.id)??null:n.latestActiveSessionId;return{...n,chats:a,currentSessionId:i,latestActiveSessionId:l}})},deleteSessions:async s=>{for(const n of s)await t().deleteSession(n)},updateSession:(s,n)=>{const o=!!n.config&&(Object.prototype.hasOwnProperty.call(n.config,"model")||Object.prototype.hasOwnProperty.call(n.config,"reasoningEffort")),a=typeof n.title=="string"||typeof n.pinned=="boolean",l=o||a?new Date().toISOString():void 0;e(d=>{const u=d.chats.map(h=>h.id===s?{...h,...n,...l?{updatedAt:l}:{}}:h);return{...d,chats:u}});const c={};if(typeof n.title=="string"&&(c.title=n.title),typeof n.pinned=="boolean"&&(c.pinned=n.pinned),n.config&&Object.prototype.hasOwnProperty.call(n.config,"model")&&(c.model=n.config.model??null),n.config&&Object.prototype.hasOwnProperty.call(n.config,"model_ref")&&Ee.getState().isProviderModelRefEnabled()&&(c.model_ref=n.config.model_ref??null,n.config.model_ref&&(c.provider=n.config.model_ref.provider)),n.config&&Object.prototype.hasOwnProperty.call(n.config,"reasoningEffort")){const d=n.config.reasoningEffort;d?c.reasoning_effort=d:c.clear_reasoning_effort=!0}Object.keys(c).length>0&&Gs.patchSession(s,c).catch(d=>{console.warn(`[ChatSlice] Failed to patch session ${s}:`,d)})},pinSession:s=>{t().updateSession(s,{pinned:!0})},unpinSession:s=>{t().updateSession(s,{pinned:!1})},setMessages:(s,n)=>{t().chats.find(a=>a.id===s)&&t().updateSession(s,{messages:n})},addMessage:async(s,n)=>{const o=t().chats.find(i=>i.id===s);if(!o)return;const a=[...o.messages,n];t().updateSession(s,{messages:a})},updateMessage:(s,n,o)=>{const a=t().chats.find(l=>l.id===s);if(!a)return;const i=a.messages.map(l=>{if(l.id!==n)return l;const c={...l};return Object.keys(o).forEach(d=>{Object.prototype.hasOwnProperty.call(c,d)&&(c[d]=o[d])}),c});t().updateSession(s,{messages:i})},deleteMessage:async(s,n)=>{const o=t().chats.find(a=>a.id===s);if(!o)return{success:!1,sessionId:s,messageId:n,reason:"session_not_found"};if(!o.messages.some(a=>a.id===n))return{success:!1,sessionId:s,messageId:n,reason:"message_not_found"};try{await Gs.deleteSessionMessage(s,n)}catch(a){return console.warn(`[ChatSlice] Failed to delete message ${n} from session ${s}:`,a),a instanceof Bn?a.status===404?{success:!1,sessionId:s,messageId:n,reason:"backend_not_found",statusCode:a.status,errorMessage:a.message}:a.status===409?{success:!1,sessionId:s,messageId:n,reason:"session_running",statusCode:a.status,errorMessage:a.message}:{success:!1,sessionId:s,messageId:n,reason:"backend_error",statusCode:a.status,errorMessage:a.message}:{success:!1,sessionId:s,messageId:n,reason:"backend_error",errorMessage:a instanceof Error?a.message:void 0}}return e(a=>({...a,chats:a.chats.map(i=>i.id===s?{...i,messages:i.messages.filter(l=>l.id!==n)}:i)})),{success:!0,sessionId:s,messageId:n}},refreshChats:async()=>{const n=(await Gs.listSessions()).sessions.map(sl);e(o=>{const a=new Set(o.processingChats);n.forEach(c=>{c.isRunning&&a.add(c.id)});const i=new Map(o.chats.map(c=>[c.id,c])),l=n.map(c=>{var _,w,k,C;const d=i.get(c.id);if(!d)return c;const u=xu(d.updatedAt),h=xu(c.updatedAt),p=u!==null&&h!==null&&u>h,g=d.config||{},y=c.config||{},f=Object.prototype.hasOwnProperty.call(g,"model"),v=Object.prototype.hasOwnProperty.call(g,"model_ref"),b=Object.prototype.hasOwnProperty.call(g,"reasoningEffort"),x=Math.max(d.messageCount??0,c.messageCount??0);return{...c,title:p?d.title:c.title,pinned:p?d.pinned:c.pinned,updatedAt:p?d.updatedAt:c.updatedAt,messages:d.messages,messageCount:x,config:{...g,...y,model:p&&f?g.model:y.model,model_ref:p&&v?g.model_ref:y.model_ref,reasoningEffort:p&&b?g.reasoningEffort:y.reasoningEffort,compressionEvents:((_=d.config)==null?void 0:_.compressionEvents)??((w=c.config)==null?void 0:w.compressionEvents),syncCursor:((k=d.config)==null?void 0:k.syncCursor)??((C=c.config)==null?void 0:C.syncCursor)}}});return{...o,chats:l,processingChats:a}})},loadChats:async()=>{var c;const s=localStorage.getItem(bu),n=s===null?t().autoGenerateTitles:s==="true";let o=await Gs.listSessions();(!o.sessions||o.sessions.length===0)&&(o={sessions:[(await Gs.createSession({title:es.t("chat.sidebar.newSession")})).session]});const a=o.sessions.map(sl),i=((c=a[0])==null?void 0:c.id)??null,l=a.filter(d=>d.isRunning).map(d=>d.id);e({chats:a,latestActiveSessionId:i,currentSessionId:i,processingChats:new Set(l),autoGenerateTitles:n}),i&&await t().loadChatHistory(i)},loadChatHistory:async(s,n)=>{var l,c,d,u,h,p,g;const o=(n==null?void 0:n.mode)??"replace",a=Math.max(0,(n==null?void 0:n.retries)??0),i=Math.max(0,(n==null?void 0:n.retryDelayMs)??0);for(let y=0;y<=a;y+=1)try{const f=t().chats.find(_=>_.id===s);if(!f)return;const v=await Gs.getHistory(s),b=(l=v.messages[v.messages.length-1])==null?void 0:l.role;if(n!=null&&n.waitForAssistant&&b==="user"&&y<a){const _=i>0?i*(y+1):200*(y+1);await new Promise(w=>setTimeout(w,_));continue}const x=$v(s,v.messages);if(o==="monotonic"){const _=f.messages||[],w=_.length,k=x.length,C=(c=x[x.length-1])==null?void 0:c.role,E=(d=_[_.length-1])==null?void 0:d.role,j=_[_.length-1],R=x[x.length-1],M=j==null?void 0:j.id,T=R==null?void 0:R.id;let P=!1;if(k>w?P=!0:k===w&&(P=E==="user"&&C!=="user"||typeof M=="string"&&typeof T=="string"&&M!==T),!P){t().updateSession(s,{messageCount:Math.max(f.messageCount??0,v.messages.length)});return}}t().updateSession(s,{messages:x,messageCount:v.messages.length,config:{...f.config||{},compressionEvents:(v.compression_events||[]).map(_=>({id:_.id,createdAt:_.created_at,messagesCompressed:_.messages_compressed,segmentsRemoved:_.segments_removed})),syncCursor:{messageCount:v.messages.length,lastMessageId:((u=v.messages[v.messages.length-1])==null?void 0:u.id)??null,hasPendingQuestion:((h=t().pendingQuestionRespond)==null?void 0:h.sessionId)===s,pendingQuestionToolCallId:((p=t().pendingQuestionRespond)==null?void 0:p.sessionId)===s?((g=t().pendingQuestionRespond)==null?void 0:g.toolCallId)??null:null}}});return}catch(f){if(y>=a){console.warn(`[ChatSlice] Failed to load history for ${s}:`,f);return}const v=i>0?i*(y+1):200*(y+1);await new Promise(b=>setTimeout(b,v))}},upsertSubSessionProgress:(s,n,o)=>{e(a=>{const i=a.subSessionsByParent[s]||{},l=i[n]||{},c={...i,[n]:{...l,...o}};return{subSessionsByParent:{...a.subSessionsByParent,[s]:c}}})},clearSubSessionProgress:(s,n)=>{e(o=>{const a=o.subSessionsByParent[s];if(!a||!a[n])return{};const{[n]:i,...l}=a;return{subSessionsByParent:{...o.subSessionsByParent,[s]:l}}})},setSessionProcessing:(s,n)=>{e(o=>{const a=new Set(o.processingChats);return n?a.add(s):a.delete(s),{processingChats:a}})},isSessionProcessing:s=>t().processingChats.has(s),setAutoGenerateTitlesPreference:async s=>{const n=t().autoGenerateTitles;e({autoGenerateTitles:s,isUpdatingAutoTitlePreference:!0});try{localStorage.setItem(bu,String(s))}catch(o){throw console.warn("[ChatSlice] Failed to update auto-title preference:",o),e({autoGenerateTitles:n}),o}finally{e({isUpdatingAutoTitlePreference:!1})}}});class ac extends Error{constructor(s="Proxy authentication required"){super(s);He(this,"code","proxy_auth_required");this.name="ProxyAuthRequiredError"}}const En=class En{constructor(){}static getInstance(){return En.instance||(En.instance=new En),En.instance}resolveOpenAICompatBaseUrl(){const t=kr().trim().replace(/\/+$/,"");return t.endsWith("/openai/v1")?t:`${t.endsWith("/v1")?t.slice(0,-3):t}/openai/v1`}async getModels(){var t,s;try{return(await new pd({baseUrl:this.resolveOpenAICompatBaseUrl()}).get("models")).data.map(a=>a.id)}catch(n){if(console.error("Failed to fetch models from HTTP API:",n),n instanceof Bn){if(n.status===428)throw new ac(n.message);let o;if(n.body)try{o=JSON.parse(n.body)}catch{}if(o&&typeof o=="object"&&"error"in o&&((t=o.error)==null?void 0:t.code)==="proxy_auth_required")throw new ac(((s=o.error)==null?void 0:s.message)||n.message)}throw n}}};He(En,"instance");let ic=En;const If=ic.getInstance(),Lv=async e=>{var t;if(typeof navigator>"u"||!((t=navigator.clipboard)!=null&&t.writeText))throw new Error("navigator.clipboard.writeText is unavailable");await navigator.clipboard.writeText(e)},Ov=e=>{if(typeof document>"u")throw new Error("document is unavailable");const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly","true"),t.style.position="fixed",t.style.top="-9999px",t.style.left="-9999px",t.style.opacity="0",document.body.appendChild(t),t.focus(),t.select();const s=document.execCommand("copy");if(document.body.removeChild(t),!s)throw new Error("document.execCommand('copy') returned false")},os=async e=>{try{await Lv(e);return}catch(t){try{Ov(e);return}catch(s){const n=t instanceof Error?t.message:String(t),o=s instanceof Error?s.message:String(s);throw new Error(`Clipboard copy failed: navigator(${n}); fallback(${o})`)}}};class Fv{async copyToClipboard(t){await os(t)}async getBambooConfig(){try{return await xe.get("bamboo/config")}catch(t){return console.error("Failed to fetch Bamboo config:",t),{}}}async getBambooTools(){try{return await xe.get("bamboo/tools")}catch(t){return console.error("Failed to fetch Bamboo tools:",t),{tools:[]}}}async getModelLimitDefaults(){try{return await xe.get("bamboo/model-limits/defaults")}catch(t){return console.error("Failed to fetch model limit defaults:",t),{model_limits:[]}}}async setBambooConfig(t){return xe.post("bamboo/config",t)}async validateBambooConfigPatch(t){return xe.post("bamboo/config/validate",t)}async setProxyAuth(t){return xe.post("bamboo/proxy-auth",t)}async getProxyAuthStatus(){try{return await xe.get("bamboo/proxy-auth/status")}catch(t){return console.error("Failed to fetch proxy auth status:",t),{configured:!1,username:null}}}async clearProxyAuth(){return xe.post("bamboo/proxy-auth",{username:"",password:""})}async resetBambooConfig(){return xe.post("bamboo/config/reset",{})}async saveWorkflow(t,s){return xe.post("bamboo/workflows",{name:t,content:s})}async deleteWorkflow(t){return xe.delete(`bamboo/workflows/${encodeURIComponent(t)}`)}async getKeywordMaskingConfig(){try{return await xe.get("bamboo/keyword-masking")}catch(t){return console.error("Failed to fetch keyword masking config:",t),{entries:[]}}}async updateKeywordMaskingConfig(t){return xe.post("bamboo/keyword-masking",t)}async validateKeywordEntries(t){return xe.post("bamboo/keyword-masking/validate",t)}async getSetupStatus(){return await xe.get("bamboo/setup/status")}async markSetupComplete(){return xe.post("bamboo/setup/complete",{})}async resetSetupStatus(){await xe.post("bamboo/setup/incomplete",{})}async getAccessStatus(){return xe.get("bamboo/access/status")}async verifyAccessPassword(t){return xe.post("bamboo/access/verify",{password:t})}async updateAccessPassword(t){return xe.post("bamboo/access/password",t)}}const Rn=class Rn{constructor(){He(this,"httpUtilityService",new Fv)}static getInstance(){return Rn.instance||(Rn.instance=new Rn),Rn.instance}getUtilityService(){return{copyToClipboard:t=>this.httpUtilityService.copyToClipboard(t),getBambooConfig:()=>this.httpUtilityService.getBambooConfig(),getBambooTools:()=>this.httpUtilityService.getBambooTools(),getModelLimitDefaults:()=>this.httpUtilityService.getModelLimitDefaults(),setBambooConfig:t=>this.httpUtilityService.setBambooConfig(t),validateBambooConfigPatch:t=>this.httpUtilityService.validateBambooConfigPatch(t),setProxyAuth:t=>this.httpUtilityService.setProxyAuth(t),getProxyAuthStatus:()=>this.httpUtilityService.getProxyAuthStatus(),clearProxyAuth:()=>this.httpUtilityService.clearProxyAuth(),resetBambooConfig:()=>this.httpUtilityService.resetBambooConfig(),resetSetupStatus:()=>this.httpUtilityService.resetSetupStatus(),saveWorkflow:(t,s)=>this.httpUtilityService.saveWorkflow(t,s),deleteWorkflow:t=>this.httpUtilityService.deleteWorkflow(t),getKeywordMaskingConfig:()=>this.httpUtilityService.getKeywordMaskingConfig(),updateKeywordMaskingConfig:t=>this.httpUtilityService.updateKeywordMaskingConfig(t),validateKeywordEntries:t=>this.httpUtilityService.validateKeywordEntries(t),getSetupStatus:()=>this.httpUtilityService.getSetupStatus(),markSetupComplete:()=>this.httpUtilityService.markSetupComplete(),getAccessStatus:()=>this.httpUtilityService.getAccessStatus(),verifyAccessPassword:t=>this.httpUtilityService.verifyAccessPassword(t),updateAccessPassword:t=>this.httpUtilityService.updateAccessPassword(t)}}async copyToClipboard(t){return this.getUtilityService().copyToClipboard(t)}async getBambooConfig(){return this.getUtilityService().getBambooConfig()}async getBambooTools(){return this.getUtilityService().getBambooTools()}async getModelLimitDefaults(){return this.getUtilityService().getModelLimitDefaults()}async setBambooConfig(t){return this.getUtilityService().setBambooConfig(t)}async validateBambooConfigPatch(t){return this.getUtilityService().validateBambooConfigPatch(t)}async setProxyAuth(t){return this.getUtilityService().setProxyAuth(t)}async getProxyAuthStatus(){return this.getUtilityService().getProxyAuthStatus()}async clearProxyAuth(){return this.getUtilityService().clearProxyAuth()}async resetBambooConfig(){return this.getUtilityService().resetBambooConfig()}async resetSetupStatus(){return this.getUtilityService().resetSetupStatus()}async saveWorkflow(t,s){return this.getUtilityService().saveWorkflow(t,s)}async deleteWorkflow(t){return this.getUtilityService().deleteWorkflow(t)}async getKeywordMaskingConfig(){return this.getUtilityService().getKeywordMaskingConfig()}async updateKeywordMaskingConfig(t){return this.getUtilityService().updateKeywordMaskingConfig(t)}async validateKeywordEntries(t){return this.getUtilityService().validateKeywordEntries(t)}async getSetupStatus(){return this.getUtilityService().getSetupStatus()}async markSetupComplete(){return this.getUtilityService().markSetupComplete()}async getAccessStatus(){return this.getUtilityService().getAccessStatus()}async verifyAccessPassword(t){return this.getUtilityService().verifyAccessPassword(t)}async updateAccessPassword(t){return this.getUtilityService().updateAccessPassword(t)}};He(Rn,"instance");let fs=Rn;const et=fs.getInstance();let Ar=null,Ir=null;const nl=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,ms=un((e,t)=>({config:null,proxyAuthStatus:null,isLoadingConfig:!1,isLoadingProxyAuthStatus:!1,lastLoadedAt:null,error:null,loadConfig:async({force:s=!1}={})=>{const n=t().config;if(!s&&n)return n;if(Ar)return Ar;Ar=(async()=>{e({isLoadingConfig:!0,error:null});try{const o=await et.getBambooConfig()??{};return e({config:o,lastLoadedAt:Date.now(),error:null}),o}catch(o){const a=nl(o,"Failed to load Bamboo config");throw e({error:a}),o}finally{e({isLoadingConfig:!1})}})();try{return await Ar}finally{Ar=null}},saveConfig:async s=>{e({isLoadingConfig:!0,error:null,config:s});try{const n=await et.setBambooConfig(s);return e({config:n,lastLoadedAt:Date.now(),error:null}),n}catch(n){const o=nl(n,"Failed to save Bamboo config");throw e({error:o}),n}finally{e({isLoadingConfig:!1})}},patchConfig:async s=>{const o={...await t().loadConfig()??{},...s??{}};return t().saveConfig(o)},loadProxyAuthStatus:async({force:s=!1}={})=>{const n=t().proxyAuthStatus;if(!s&&n)return n;if(Ir)return Ir;Ir=(async()=>{e({isLoadingProxyAuthStatus:!0,error:null});try{const o=await et.getProxyAuthStatus();return e({proxyAuthStatus:o,error:null}),o}catch(o){const a=nl(o,"Failed to load proxy auth status");throw e({error:a}),o}finally{e({isLoadingProxyAuthStatus:!1})}})();try{return await Ir}finally{Ir=null}},applyProxyAuth:async s=>{await et.setProxyAuth(s),await t().loadProxyAuthStatus({force:!0})},clearProxyAuth:async()=>{await et.clearProxyAuth(),await t().loadProxyAuthStatus({force:!0})}}));let $r=null;const zv=(e,t)=>({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:null,configModel:void 0,setSelectedModel:s=>{e({selectedModel:s})},loadConfigModel:async()=>{try{const s=await ms.getState().loadConfig(),n=typeof(s==null?void 0:s.model)=="string"?s.model:void 0;n&&e({configModel:n})}catch(s){console.error("Failed to load model from config:",s)}},fetchModels:async()=>{if($r)return $r;$r=(async()=>{e({isLoadingModels:!0,modelsError:null});try{try{if(!(await et.getSetupStatus()).is_complete){st("[ModelSlice]","Setup not complete, skipping model fetch"),e({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:"Complete setup to access all models"});return}}catch(n){console.error("Failed to check setup status:",n)}const s=await If.getModels();e(n=>{const o=n.selectedModel;let a=n.selectedModel;return o&&s.includes(o)||(s.length>0?a=s[0]:a=void 0),{...n,models:s,selectedModel:a,modelsError:s.length>0?null:"No available model options"}}),t().models.length===0&&console.warn("No models available from service")}catch(s){const n=s instanceof Error?s.message:String(s);if(console.error("Failed to fetch models:",s),s instanceof ac){e(o=>({...o,models:o.models,selectedModel:o.selectedModel,modelsError:n||"Proxy authentication required. Please configure proxy auth."}));return}e(o=>({...o,models:[],selectedModel:o.selectedModel,modelsError:n}))}finally{e({isLoadingModels:!1})}})();try{await $r}finally{$r=null}}}),Nv=["system_prompt","system_prompt_selected_id"],rl=e=>({id:e.id,name:e.name||e.id,content:e.content||"",description:e.description,isDefault:!!e.is_default}),nn=class nn{constructor(){He(this,"deprecatedKeysCleanupDone",!1)}static getInstance(){return nn.instance||(nn.instance=new nn),nn.instance.cleanupDeprecatedPromptStorageKeys(),nn.instance}cleanupDeprecatedPromptStorageKeys(){if(!this.deprecatedKeysCleanupDone){this.deprecatedKeysCleanupDone=!0;try{for(const t of Nv)localStorage.removeItem(t)}catch(t){console.warn("[SystemPromptService] Failed to cleanup deprecated prompt storage keys:",t)}}}async getSystemPromptPresets(){try{const t=await pe.get("prompt-presets"),n=(Array.isArray(t==null?void 0:t.prompts)?t.prompts:[]).filter(o=>o.id&&o.id.trim().length>0).map(rl);if(n.length>0)return n}catch(t){console.error("Failed to load prompt presets from backend:",t)}return gi()}async createSystemPromptPreset(t){var o;const s={name:t.name,content:t.content};(o=t.id)!=null&&o.trim()&&(s.id=t.id.trim()),t.description!==void 0&&(s.description=t.description);const n=await pe.post("prompt-presets",s);if(!(n!=null&&n.prompt))throw new Error("Backend did not return created prompt preset");return rl(n.prompt)}async updateSystemPromptPreset(t){const s=encodeURIComponent(t.id),n={name:t.name,content:t.content,description:t.description},o=await pe.patch(`prompt-presets/${s}`,n);if(!(o!=null&&o.prompt))throw new Error("Backend did not return updated prompt preset");return rl(o.prompt)}async deleteSystemPromptPreset(t){const s=encodeURIComponent(t);await pe.delete(`prompt-presets/${s}`)}async findPresetById(t){return(await this.getSystemPromptPresets()).find(n=>n.id===t)}async getCurrentSystemPromptContent(t){const s=await this.findPresetById(t);if(s)return s.content;const n=await this.getSystemPromptPresets(),o=n.find(a=>a.isDefault)||n[0];return(o==null?void 0:o.content)||""}};He(nn,"instance");let yi=nn;const vu="copilot_last_selected_prompt_id",$f="copilot_custom_system_prompts_v2",Df="copilot_custom_system_prompts_v2_migrated_to_backend",Lf="general_assistant",fd=80,dr=yi.getInstance();let Ma=null;function gd(e){const t=e.toLowerCase().trim().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"");return t.length===0?`prompt_${Date.now()}_${Math.random().toString(36).substring(2,9)}`:t.slice(0,fd)}function Of(e){if(typeof e!="string")return null;const t=e.toLowerCase().trim().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");return t?t.slice(0,fd):null}function Ff(e,t){if(!t.has(e))return e;let s=2;for(;;){const n=`_${s}`,a=`${e.slice(0,Math.max(0,fd-n.length))}${n}`;if(!t.has(a))return a;s+=1}}function zf(){try{const e=localStorage.getItem($f);if(!e)return[];const t=JSON.parse(e);if(!Array.isArray(t))return[];const s=new Set,n=[];for(const o of t){const a=typeof(o==null?void 0:o.name)=="string"?o.name.trim():"",i=typeof(o==null?void 0:o.content)=="string"?o.content.trim():"";if(!a||!i)continue;const c=Of(o==null?void 0:o.id)||gd(a),d=Ff(c,s);d!==Lf&&(s.add(d),n.push({id:d,name:a,content:i,description:typeof(o==null?void 0:o.description)=="string"&&o.description.trim()||void 0,isDefault:!!(o!=null&&o.isDefault)}))}return n}catch(e){return console.error("[promptSlice] Failed to read legacy custom prompts:",e),[]}}function Nf(){try{return localStorage.getItem(Df)==="1"}catch(e){return console.error("[promptSlice] Failed to read migration marker:",e),!1}}function Su(){try{localStorage.setItem(Df,"1")}catch(e){console.error("[promptSlice] Failed to write migration marker:",e)}}function wu(){try{localStorage.removeItem($f)}catch(e){console.error("[promptSlice] Failed to clear legacy custom prompts:",e)}}async function Bv(){var o,a;if(Nf())return;const e=zf();if(e.length===0){wu(),Su();return}const t=await dr.getSystemPromptPresets(),s=new Set(t.map(i=>i.id));let n=!1;for(const i of e){const l=(o=i.name)==null?void 0:o.trim(),c=(a=i.content)==null?void 0:a.trim();if(!l||!c||i.id===Lf||i.isDefault)continue;const d=Of(i.id)||gd(l),u=Ff(d,s);try{const h=await dr.createSystemPromptPreset({id:u,name:l,content:c,description:i.description});s.add(h.id)}catch(h){n=!0,console.error(`[promptSlice] Failed to migrate legacy prompt '${l}' to backend:`,h)}}n||(wu(),Su())}async function Wv(){Ma||(Ma=Bv().finally(()=>{Ma=null})),await Ma}const Uv=(e,t)=>({systemPrompts:[],lastSelectedPromptId:localStorage.getItem(vu)||null,loadSystemPrompts:async()=>{try{await Wv()}catch(o){console.warn("[promptSlice] Legacy prompt migration skipped:",o)}let s=[];try{s=await dr.getSystemPromptPresets()}catch(o){console.error("Failed to load system prompts from backend:",o)}let n=s.length?s:gi();if(!Nf()){const o=zf();n=qv(n,o)}n.length===0&&(n=gi()),e({systemPrompts:n})},addSystemPrompt:async s=>{try{await dr.createSystemPromptPreset({id:gd(s.name),name:s.name,content:s.content,description:s.description}),await t().loadSystemPrompts()}catch(n){throw console.error("Failed to add system prompt:",n),n}},updateSystemPrompt:async s=>{try{await dr.updateSystemPromptPreset(s),await t().loadSystemPrompts()}catch(n){throw console.error("Failed to update system prompt:",n),n}},deleteSystemPrompt:async s=>{try{await dr.deleteSystemPromptPreset(s),await t().loadSystemPrompts()}catch(n){throw console.error("Failed to delete system prompt:",n),n}},setLastSelectedPromptId:s=>{e({lastSelectedPromptId:s});try{localStorage.setItem(vu,s)}catch(n){console.error("Failed to save last selected prompt ID to localStorage:",n)}}}),qv=(e,t)=>{const s=new Map;return e.forEach(n=>{s.set(n.id,n)}),t.forEach(n=>{s.set(n.id,n)}),Array.from(s.values())},Hv=(e,t)=>({currentRequestController:null,setCurrentRequestController:s=>{e({currentRequestController:s})},cancelCurrentRequest:()=>{var s;(s=t().currentRequestController)==null||s.abort(),t().processingChats.forEach(n=>{t().setSessionProcessing(n,!1)}),e({currentRequestController:null})}});class Yv{async listSkills(t,s){const n=new URLSearchParams;t!=null&&t.search&&n.append("search",t.search),t!=null&&t.includeDisabled&&n.append("include_disabled","true"),s&&n.append("refresh","true");const o=n.toString(),a=o?`skills?${o}`:"skills";return xe.get(a)}async getSkill(t){return xe.get(`skills/${t}`)}async getFilteredTools(t){const s=t?`?session_id=${encodeURIComponent(t)}`:"";return(await xe.get(`skills/filtered-tools${s}`)).tools??[]}}const lc=new Yv,Xv=(e,t)=>({skills:[],isLoadingSkills:!1,skillsError:null,loadSkills:async(s,n)=>{e({isLoadingSkills:!0,skillsError:null});try{const o=await lc.listSkills(s,n);e({skills:o.skills,isLoadingSkills:!1})}catch(o){e({skillsError:o instanceof Error?o.message:es.t("components.skillManager.loadFailed"),isLoadingSkills:!1})}},getSkill:async s=>{e({isLoadingSkills:!0,skillsError:null});try{const n=await lc.getSkill(s),o=t().skills,i=o.findIndex(l=>l.id===n.id)>=0?o.map(l=>l.id===n.id?n:l):[...o,n];e({skills:i,isLoadingSkills:!1})}catch(n){e({skillsError:n instanceof Error?n.message:es.t("components.skillManager.getFailed"),isLoadingSkills:!1})}},clearSkillsError:()=>{e({skillsError:null})}}),Vv=e=>({tokenUsages:{},truncationOccurred:{},segmentsRemoved:{},updateTokenUsage:(t,s)=>e(n=>({tokenUsages:{...n.tokenUsages,[t]:s}})),setTruncationInfo:(t,s,n)=>e(o=>({truncationOccurred:{...o.truncationOccurred,[t]:s},segmentsRemoved:{...o.segmentsRemoved,[t]:n}})),clearTokenUsage:t=>e(s=>{const{[t]:n,...o}=s.tokenUsages,{[t]:a,...i}=s.truncationOccurred,{[t]:l,...c}=s.segmentsRemoved;return{tokenUsages:o,truncationOccurred:i,segmentsRemoved:c}})}),Kv=(e,t)=>({taskLists:{},taskListVersions:{},activeItems:{},evaluationStates:{},setTaskList:(s,n)=>e(o=>({taskLists:{...o.taskLists,[s]:n},taskListVersions:{...o.taskListVersions,[s]:n.version||0}})),updateTaskListDelta:(s,n)=>e(o=>{const a=o.taskListVersions[s]||0;if(n.version<=a)return o;const i=o.taskLists[s];if(!i)return o;const l=i.items.map(c=>c.id===n.item_id?{...c,status:n.status,tool_calls_count:n.tool_calls_count}:c);return{taskLists:{...o.taskLists,[s]:{...i,items:l,updated_at:new Date().toISOString()}},taskListVersions:{...o.taskListVersions,[s]:n.version},activeItems:{...o.activeItems,[s]:n.status==="in_progress"?n.item_id:null}}}),clearTaskList:s=>e(n=>{const{[s]:o,...a}=n.taskLists,{[s]:i,...l}=n.taskListVersions,{[s]:c,...d}=n.activeItems,{[s]:u,...h}=n.evaluationStates;return{taskLists:a,taskListVersions:l,activeItems:d,evaluationStates:h}}),getTaskListVersion:s=>t().taskListVersions[s]||0,setEvaluationState:(s,n)=>e(o=>({evaluationStates:{...o.evaluationStates,[s]:n}})),clearEvaluationState:s=>e(n=>{const{[s]:o,...a}=n.evaluationStates;return{evaluationStates:a}})}),cc=e=>Array.isArray(e)?e.map(t=>String(t??"")):[],Ka=({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:o})=>JSON.stringify({sessionId:e??null,question:t??"",options:cc(s),allowCustom:n??!0,toolCallId:o??null}),Gv=(e,t)=>{if(!e||!t)return e===t;if((e.sessionId??null)!==(t.sessionId??null)||(e.question??"")!==(t.question??"")||(e.allowCustom??!0)!==(t.allowCustom??!0)||(e.toolCallId??null)!==(t.toolCallId??null))return!1;const s=cc(e.options),n=cc(t.options);return s.length!==n.length?!1:s.every((o,a)=>o===n[a])},Bf="chat_input_reasoning_by_session_v1",Wf="chat_input_reasoning_last_used_v1",_u={content:"",referenceText:null,attachments:[],reasoningEffort:"medium"},yd=e=>e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max",Uf=()=>{if(typeof window>"u")return{};try{const e=localStorage.getItem(Bf);if(!e)return{};const t=JSON.parse(e),s={};for(const[n,o]of Object.entries(t||{}))yd(o)&&(s[n]=o);return s}catch{return{}}},Jv=e=>{if(!(typeof window>"u"))try{localStorage.setItem(Bf,JSON.stringify(e))}catch{}},Qv=()=>{if(!(typeof window>"u"))try{const e=localStorage.getItem(Wf);return yd(e)?e:void 0}catch{return}},Zv=e=>{if(!(typeof window>"u"))try{localStorage.setItem(Wf,e)}catch{}},bd=e=>{const t=Uf();return yd(t[e])?t[e]:Qv()},Dr=e=>({..._u,reasoningEffort:bd(e)??_u.reasoningEffort}),eS=(e,t)=>({inputStates:{},pendingQuestionRespond:null,setInputContent:(s,n)=>e(o=>({inputStates:{...o.inputStates,[s]:{...o.inputStates[s]||Dr(s),content:n}}})),setReferenceText:(s,n)=>e(o=>({inputStates:{...o.inputStates,[s]:{...o.inputStates[s]||Dr(s),referenceText:n}}})),setAttachments:(s,n)=>e(o=>({inputStates:{...o.inputStates,[s]:{...o.inputStates[s]||Dr(s),attachments:n}}})),setInputReasoningEffort:(s,n)=>{e(a=>({inputStates:{...a.inputStates,[s]:{...a.inputStates[s]||Dr(s),reasoningEffort:n}}}));const o=Uf();o[s]=n,Jv(o),Zv(n)},clearInputState:s=>e(n=>{const{[s]:o,...a}=n.inputStates;return{inputStates:a}}),getInputState:s=>t().inputStates[s]||Dr(s),setPendingQuestionRespond:s=>e(n=>Gv(n.pendingQuestionRespond,s)?{}:{pendingQuestionRespond:s}),clearPendingQuestionRespondForSession:s=>e(n=>{var o;return((o=n.pendingQuestionRespond)==null?void 0:o.sessionId)!==s?{}:n.pendingQuestionRespond===null?{}:{pendingQuestionRespond:null}})}),tS="bamboo_proxy_auth",sS=()=>{try{const e=localStorage.getItem(tS);if(!e)return null;const t=JSON.parse(e);if(!t||typeof t!="object")return null;const s=typeof t.username=="string"?t.username.trim():"",n=typeof t.password=="string"?t.password:"";return s?{username:s,password:n}:null}catch{return null}},nS="auto",rS="required",oS=1e4,aS=2e3,iS=rs.getInstance();let Tu=null,Lr=null,ku=null,Or=null;const ju=new WeakMap,N=un()(lv(dv((e,t,s)=>({...Dv(e,t),...zv(e,t),...Uv(e,t),...Hv(e,t),...Xv(e,t),...Vv(e),...Kv(e,t),...eS(e,t),agentAvailability:null,setAgentAvailability:n=>{e({agentAvailability:n})},checkAgentAvailability:async()=>{if(Lr)return Lr;Lr=(async()=>{const n=await iS.healthCheck();return t().agentAvailability!==n&&e({agentAvailability:n}),n})();try{return await Lr}finally{Lr=null}},startAgentHealthCheck:()=>{Tu||(t().checkAgentAvailability(),Tu=setInterval(()=>{t().checkAgentAvailability()},oS))},refreshSessionsIndex:async()=>{if(Or)return Or;Or=(async()=>{try{await t().refreshChats()}catch(n){console.warn("[AppStore] refreshChats failed:",n)}})();try{return await Or}finally{Or=null}},startSessionsIndexSync:()=>{ku||(t().refreshSessionsIndex(),ku=setInterval(()=>{t().refreshSessionsIndex()},aS))}})),{name:"AppStore"})),qf=e=>{const t=ju.get(e);if(t)return t;const s=new Map(e.map(n=>[n.id,n]));return ju.set(e,s),s},Xn=e=>t=>e?qf(t.chats).get(e)??null:null,lS=e=>e.currentSessionId?qf(e.chats).get(e.currentSessionId)??null:null,Cu=async()=>{const e=sS();if(!e)return!1;try{return await et.setProxyAuth(e),!0}catch(t){return console.error("Failed to apply stored proxy auth during startup:",t),!1}},cS=async()=>{try{const e=await ms.getState().loadConfig();if((typeof(e==null?void 0:e.proxy_auth_mode)=="string"?e.proxy_auth_mode:nS)!==rS)return await Cu(),!1;const s=await ms.getState().loadProxyAuthStatus({force:!0});return s!=null&&s.configured||await Cu()?!1:(N.setState(o=>({...o,models:[],selectedModel:void 0,modelsError:"Proxy auth mode is set to required. Please configure proxy username/password and apply it.",isLoadingModels:!1})),!0)}catch(e){return console.error("Failed to evaluate startup proxy auth mode:",e),!1}};let Mu=!1;const dS=async(e=!1)=>{if(Mu&&!e)return;Mu=!0,N.getState().startAgentHealthCheck(),N.getState().startSessionsIndexSync(),await N.getState().loadChats(),await cS()||await N.getState().fetchModels(),await N.getState().loadSystemPrompts()},Un={'code[class*="language-"]':{background:"hsl(220, 13%, 18%)",color:"hsl(220, 14%, 71%)",textShadow:"0 1px rgba(0, 0, 0, 0.3)",fontFamily:'"Fira Code", "Fira Mono", Menlo, Consolas, "DejaVu Sans Mono", monospace',direction:"ltr",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",lineHeight:"1.5",MozTabSize:"2",OTabSize:"2",tabSize:"2",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none"},'pre[class*="language-"]':{background:"hsl(220, 13%, 18%)",color:"hsl(220, 14%, 71%)",textShadow:"0 1px rgba(0, 0, 0, 0.3)",fontFamily:'"Fira Code", "Fira Mono", Menlo, Consolas, "DejaVu Sans Mono", monospace',direction:"ltr",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",lineHeight:"1.5",MozTabSize:"2",OTabSize:"2",tabSize:"2",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",padding:"1em",margin:"0.5em 0",overflow:"auto",borderRadius:"0.3em"},'code[class*="language-"]::-moz-selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},'code[class*="language-"] *::-moz-selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},'pre[class*="language-"] *::-moz-selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},'code[class*="language-"]::selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},'code[class*="language-"] *::selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},'pre[class*="language-"] *::selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},':not(pre) > code[class*="language-"]':{padding:"0.2em 0.3em",borderRadius:"0.3em",whiteSpace:"normal"},comment:{color:"hsl(220, 10%, 40%)",fontStyle:"italic"},prolog:{color:"hsl(220, 10%, 40%)"},cdata:{color:"hsl(220, 10%, 40%)"},doctype:{color:"hsl(220, 14%, 71%)"},punctuation:{color:"hsl(220, 14%, 71%)"},entity:{color:"hsl(220, 14%, 71%)",cursor:"help"},"attr-name":{color:"hsl(29, 54%, 61%)"},"class-name":{color:"hsl(29, 54%, 61%)"},boolean:{color:"hsl(29, 54%, 61%)"},constant:{color:"hsl(29, 54%, 61%)"},number:{color:"hsl(29, 54%, 61%)"},atrule:{color:"hsl(29, 54%, 61%)"},keyword:{color:"hsl(286, 60%, 67%)"},property:{color:"hsl(355, 65%, 65%)"},tag:{color:"hsl(355, 65%, 65%)"},symbol:{color:"hsl(355, 65%, 65%)"},deleted:{color:"hsl(355, 65%, 65%)"},important:{color:"hsl(355, 65%, 65%)"},selector:{color:"hsl(95, 38%, 62%)"},string:{color:"hsl(95, 38%, 62%)"},char:{color:"hsl(95, 38%, 62%)"},builtin:{color:"hsl(95, 38%, 62%)"},inserted:{color:"hsl(95, 38%, 62%)"},regex:{color:"hsl(95, 38%, 62%)"},"attr-value":{color:"hsl(95, 38%, 62%)"},"attr-value > .token.punctuation":{color:"hsl(95, 38%, 62%)"},variable:{color:"hsl(207, 82%, 66%)"},operator:{color:"hsl(207, 82%, 66%)"},function:{color:"hsl(207, 82%, 66%)"},url:{color:"hsl(187, 47%, 55%)"},"attr-value > .token.punctuation.attr-equals":{color:"hsl(220, 14%, 71%)"},"special-attr > .token.attr-value > .token.value.css":{color:"hsl(220, 14%, 71%)"},".language-css .token.selector":{color:"hsl(355, 65%, 65%)"},".language-css .token.property":{color:"hsl(220, 14%, 71%)"},".language-css .token.function":{color:"hsl(187, 47%, 55%)"},".language-css .token.url > .token.function":{color:"hsl(187, 47%, 55%)"},".language-css .token.url > .token.string.url":{color:"hsl(95, 38%, 62%)"},".language-css .token.important":{color:"hsl(286, 60%, 67%)"},".language-css .token.atrule .token.rule":{color:"hsl(286, 60%, 67%)"},".language-javascript .token.operator":{color:"hsl(286, 60%, 67%)"},".language-javascript .token.template-string > .token.interpolation > .token.interpolation-punctuation.punctuation":{color:"hsl(5, 48%, 51%)"},".language-json .token.operator":{color:"hsl(220, 14%, 71%)"},".language-json .token.null.keyword":{color:"hsl(29, 54%, 61%)"},".language-markdown .token.url":{color:"hsl(220, 14%, 71%)"},".language-markdown .token.url > .token.operator":{color:"hsl(220, 14%, 71%)"},".language-markdown .token.url-reference.url > .token.string":{color:"hsl(220, 14%, 71%)"},".language-markdown .token.url > .token.content":{color:"hsl(207, 82%, 66%)"},".language-markdown .token.url > .token.url":{color:"hsl(187, 47%, 55%)"},".language-markdown .token.url-reference.url":{color:"hsl(187, 47%, 55%)"},".language-markdown .token.blockquote.punctuation":{color:"hsl(220, 10%, 40%)",fontStyle:"italic"},".language-markdown .token.hr.punctuation":{color:"hsl(220, 10%, 40%)",fontStyle:"italic"},".language-markdown .token.code-snippet":{color:"hsl(95, 38%, 62%)"},".language-markdown .token.bold .token.content":{color:"hsl(29, 54%, 61%)"},".language-markdown .token.italic .token.content":{color:"hsl(286, 60%, 67%)"},".language-markdown .token.strike .token.content":{color:"hsl(355, 65%, 65%)"},".language-markdown .token.strike .token.punctuation":{color:"hsl(355, 65%, 65%)"},".language-markdown .token.list.punctuation":{color:"hsl(355, 65%, 65%)"},".language-markdown .token.title.important > .token.punctuation":{color:"hsl(355, 65%, 65%)"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"},namespace:{Opacity:"0.8"},"token.tab:not(:empty):before":{color:"hsla(220, 14%, 71%, 0.15)",textShadow:"none"},"token.cr:before":{color:"hsla(220, 14%, 71%, 0.15)",textShadow:"none"},"token.lf:before":{color:"hsla(220, 14%, 71%, 0.15)",textShadow:"none"},"token.space:before":{color:"hsla(220, 14%, 71%, 0.15)",textShadow:"none"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item":{marginRight:"0.4em"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > button":{background:"hsl(220, 13%, 26%)",color:"hsl(220, 9%, 55%)",padding:"0.1em 0.4em",borderRadius:"0.3em"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > a":{background:"hsl(220, 13%, 26%)",color:"hsl(220, 9%, 55%)",padding:"0.1em 0.4em",borderRadius:"0.3em"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > span":{background:"hsl(220, 13%, 26%)",color:"hsl(220, 9%, 55%)",padding:"0.1em 0.4em",borderRadius:"0.3em"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > button:hover":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > button:focus":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > a:hover":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > a:focus":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > span:hover":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > span:focus":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},".line-highlight.line-highlight":{background:"hsla(220, 100%, 80%, 0.04)"},".line-highlight.line-highlight:before":{background:"hsl(220, 13%, 26%)",color:"hsl(220, 14%, 71%)",padding:"0.1em 0.6em",borderRadius:"0.3em",boxShadow:"0 2px 0 0 rgba(0, 0, 0, 0.2)"},".line-highlight.line-highlight[data-end]:after":{background:"hsl(220, 13%, 26%)",color:"hsl(220, 14%, 71%)",padding:"0.1em 0.6em",borderRadius:"0.3em",boxShadow:"0 2px 0 0 rgba(0, 0, 0, 0.2)"},"pre[id].linkable-line-numbers.linkable-line-numbers span.line-numbers-rows > span:hover:before":{backgroundColor:"hsla(220, 100%, 80%, 0.04)"},".line-numbers.line-numbers .line-numbers-rows":{borderRightColor:"hsla(220, 14%, 71%, 0.15)"},".command-line .command-line-prompt":{borderRightColor:"hsla(220, 14%, 71%, 0.15)"},".line-numbers .line-numbers-rows > span:before":{color:"hsl(220, 14%, 45%)"},".command-line .command-line-prompt > span:before":{color:"hsl(220, 14%, 45%)"},".rainbow-braces .token.token.punctuation.brace-level-1":{color:"hsl(355, 65%, 65%)"},".rainbow-braces .token.token.punctuation.brace-level-5":{color:"hsl(355, 65%, 65%)"},".rainbow-braces .token.token.punctuation.brace-level-9":{color:"hsl(355, 65%, 65%)"},".rainbow-braces .token.token.punctuation.brace-level-2":{color:"hsl(95, 38%, 62%)"},".rainbow-braces .token.token.punctuation.brace-level-6":{color:"hsl(95, 38%, 62%)"},".rainbow-braces .token.token.punctuation.brace-level-10":{color:"hsl(95, 38%, 62%)"},".rainbow-braces .token.token.punctuation.brace-level-3":{color:"hsl(207, 82%, 66%)"},".rainbow-braces .token.token.punctuation.brace-level-7":{color:"hsl(207, 82%, 66%)"},".rainbow-braces .token.token.punctuation.brace-level-11":{color:"hsl(207, 82%, 66%)"},".rainbow-braces .token.token.punctuation.brace-level-4":{color:"hsl(286, 60%, 67%)"},".rainbow-braces .token.token.punctuation.brace-level-8":{color:"hsl(286, 60%, 67%)"},".rainbow-braces .token.token.punctuation.brace-level-12":{color:"hsl(286, 60%, 67%)"},"pre.diff-highlight > code .token.token.deleted:not(.prefix)":{backgroundColor:"hsla(353, 100%, 66%, 0.15)"},"pre > code.diff-highlight .token.token.deleted:not(.prefix)":{backgroundColor:"hsla(353, 100%, 66%, 0.15)"},"pre.diff-highlight > code .token.token.deleted:not(.prefix)::-moz-selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre.diff-highlight > code .token.token.deleted:not(.prefix) *::-moz-selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre > code.diff-highlight .token.token.deleted:not(.prefix)::-moz-selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre > code.diff-highlight .token.token.deleted:not(.prefix) *::-moz-selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre.diff-highlight > code .token.token.deleted:not(.prefix)::selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre.diff-highlight > code .token.token.deleted:not(.prefix) *::selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre > code.diff-highlight .token.token.deleted:not(.prefix)::selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre > code.diff-highlight .token.token.deleted:not(.prefix) *::selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre.diff-highlight > code .token.token.inserted:not(.prefix)":{backgroundColor:"hsla(137, 100%, 55%, 0.15)"},"pre > code.diff-highlight .token.token.inserted:not(.prefix)":{backgroundColor:"hsla(137, 100%, 55%, 0.15)"},"pre.diff-highlight > code .token.token.inserted:not(.prefix)::-moz-selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre.diff-highlight > code .token.token.inserted:not(.prefix) *::-moz-selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre > code.diff-highlight .token.token.inserted:not(.prefix)::-moz-selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre > code.diff-highlight .token.token.inserted:not(.prefix) *::-moz-selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre.diff-highlight > code .token.token.inserted:not(.prefix)::selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre.diff-highlight > code .token.token.inserted:not(.prefix) *::selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre > code.diff-highlight .token.token.inserted:not(.prefix)::selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre > code.diff-highlight .token.token.inserted:not(.prefix) *::selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},".prism-previewer.prism-previewer:before":{borderColor:"hsl(224, 13%, 17%)"},".prism-previewer-gradient.prism-previewer-gradient div":{borderColor:"hsl(224, 13%, 17%)",borderRadius:"0.3em"},".prism-previewer-color.prism-previewer-color:before":{borderRadius:"0.3em"},".prism-previewer-easing.prism-previewer-easing:before":{borderRadius:"0.3em"},".prism-previewer.prism-previewer:after":{borderTopColor:"hsl(224, 13%, 17%)"},".prism-previewer-flipped.prism-previewer-flipped.after":{borderBottomColor:"hsl(224, 13%, 17%)"},".prism-previewer-angle.prism-previewer-angle:before":{background:"hsl(219, 13%, 22%)"},".prism-previewer-time.prism-previewer-time:before":{background:"hsl(219, 13%, 22%)"},".prism-previewer-easing.prism-previewer-easing":{background:"hsl(219, 13%, 22%)"},".prism-previewer-angle.prism-previewer-angle circle":{stroke:"hsl(220, 14%, 71%)",strokeOpacity:"1"},".prism-previewer-time.prism-previewer-time circle":{stroke:"hsl(220, 14%, 71%)",strokeOpacity:"1"},".prism-previewer-easing.prism-previewer-easing circle":{stroke:"hsl(220, 14%, 71%)",fill:"transparent"},".prism-previewer-easing.prism-previewer-easing path":{stroke:"hsl(220, 14%, 71%)"},".prism-previewer-easing.prism-previewer-easing line":{stroke:"hsl(220, 14%, 71%)"}},{Text:Pu,Paragraph:uS}=le,mS=({content:e,token:t,showGradient:s,onClick:n})=>r.jsx(ee,{size:"small",style:{marginLeft:t.marginLG,marginTop:t.marginXS,backgroundColor:t.colorBgLayout,borderColor:t.colorBorderSecondary},bodyStyle:{padding:t.paddingMD},onClick:n,children:r.jsxs("div",{style:{maxHeight:"60vh",overflowY:"auto",position:"relative",paddingRight:t.paddingXS},children:[r.jsx(hs,{remarkPlugins:[Ii],components:{p:({children:o})=>r.jsx(uS,{style:{marginBottom:t.marginSM},children:o}),ol:({children:o})=>r.jsx("ol",{style:{marginBottom:t.marginSM,paddingLeft:t.paddingLG},children:o}),ul:({children:o})=>r.jsx("ul",{style:{marginBottom:t.marginSM,paddingLeft:t.paddingLG},children:o}),li:({children:o})=>r.jsx("li",{style:{marginBottom:t.marginXS},children:o}),h1:({children:o})=>r.jsx(Pu,{strong:!0,style:{fontSize:t.fontSizeHeading3,marginBottom:t.marginSM,display:"block"},children:o}),h2:({children:o})=>r.jsx(Pu,{strong:!0,style:{fontSize:t.fontSizeHeading4,marginBottom:t.marginSM,display:"block"},children:o}),code:({inline:o,className:a,children:i,...l})=>{const c=/language-(\w+)/.exec(a||"");return o?r.jsx("code",{className:a,style:{backgroundColor:t.colorFillTertiary,padding:"0 4px",borderRadius:t.borderRadiusSM,fontSize:t.fontSizeSM},...l,children:i}):r.jsx(fr,{style:Un,language:(c==null?void 0:c[1])||"text",PreTag:"div",wrapLongLines:!0,children:String(i).replace(/\n$/,"")})}},children:e||"No content available."}),s?r.jsx("div",{style:{position:"sticky",bottom:0,height:48,background:`linear-gradient(180deg, transparent, ${t.colorBgLayout})`,pointerEvents:"none",marginTop:-48}}):null]})}),{Text:ol,Paragraph:hS}=le,pS=({prompt:e,token:t,isSelected:s,isExpanded:n,onSelect:o,onToggleExpand:a,onCopy:i})=>{const{t:l}=ne(),c=e.content||"",{nonEmptyLineCount:d,wordCount:u,characterCount:h,showGradient:p}=m.useMemo(()=>{const y=(c?c.split(/\r?\n/):[]).filter(b=>b.trim().length>0).length,f=c.trim()?c.trim().split(/\s+/).filter(Boolean).length:0,v=c.length;return{nonEmptyLineCount:y,wordCount:f,characterCount:v,showGradient:!n&&v>600}},[c,n]);return r.jsx(nt.Item,{style:{cursor:"pointer",padding:t.paddingMD,borderRadius:t.borderRadius,border:s?`2px solid ${t.colorPrimary}`:`1px solid ${t.colorBorderSecondary}`,marginBottom:t.marginXS,backgroundColor:s?t.colorPrimaryBg:t.colorBgContainer,transition:"all 0.2s ease"},onClick:()=>o(e.id),children:r.jsxs(X,{direction:"vertical",style:{width:"100%"},size:t.marginSM,children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",width:"100%",gap:t.marginSM},children:[r.jsxs(X,{align:"start",children:[r.jsx(ts,{checked:s,onChange:()=>o(e.id),onClick:g=>g.stopPropagation()}),r.jsxs("div",{children:[r.jsx(ol,{strong:!0,children:e.name||e.id}),r.jsx("div",{children:r.jsx(ol,{code:!0,style:{fontSize:t.fontSizeSM,color:t.colorTextSecondary},children:e.id})})]}),e.isDefault?r.jsx(oe,{color:"warning",children:l("chat.systemPromptSelector.defaultTag")}):null]}),r.jsxs(X,{size:"small",children:[r.jsx(Y,{type:"text",size:"small",icon:n?r.jsx(nx,{}):r.jsx(td,{}),onClick:g=>{g.stopPropagation(),a(e.id)},children:l(n?"chat.systemPromptSelector.hide":"chat.systemPromptSelector.preview")}),r.jsx(Y,{type:"text",size:"small",icon:r.jsx(ss,{}),onClick:g=>i(g,e),children:l("chat.systemPromptSelector.copy")})]})]}),e.description?r.jsx(ol,{type:"secondary",style:{marginLeft:t.marginLG,fontSize:t.fontSizeSM},children:e.description}):null,r.jsxs(X,{size:"small",wrap:!0,style:{marginLeft:t.marginLG},children:[r.jsx(oe,{color:"processing",children:l("chat.systemPromptSelector.lines",{count:d})}),r.jsx(oe,{color:"purple",children:l("chat.systemPromptSelector.words",{count:u})}),r.jsx(oe,{color:"success",children:l("chat.systemPromptSelector.chars",{count:h})})]}),n?r.jsx(mS,{content:c,token:t,showGradient:p,onClick:g=>g.stopPropagation()}):r.jsx(hS,{type:"secondary",ellipsis:{rows:3},style:{marginLeft:t.marginLG,marginBottom:0,color:t.colorTextSecondary},children:c||l("chat.systemPromptSelector.noContent")})]})},e.id)},{Text:fS}=le,{useToken:gS}=he,yS=({open:e,onClose:t,onSelect:s,prompts:n,title:o,showCancelButton:a=!0})=>{const{t:i}=ne(),{token:l}=gS(),[c,d]=fe.useMessage(),u=N(k=>k.lastSelectedPromptId),h=N(k=>k.setLastSelectedPromptId),[p,g]=m.useState(null),[y,f]=m.useState(null),v=m.useMemo(()=>n.filter(k=>k.id&&k.id.trim()!==""),[n]),b=async(k,C)=>{k.stopPropagation();const E=C.content??"";try{await os(E),c.success(i("success.promptCopied",{name:C.name}))}catch(j){console.error("[SystemPromptSelector] Failed to copy prompt:",j),c.error(i("error.copyPromptFailed"))}},x=o??i("chat.prompt.selectorTitle");m.useEffect(()=>{if(e){const k=v.find(E=>E.isDefault),C=u||(k==null?void 0:k.id)||(v.length>0?v[0].id:null);g(C)}},[e,u,v.length]);const _=k=>{g(k.id),h(k.id),s(k),t()},w=()=>{t()};return r.jsxs(r.Fragment,{children:[d,r.jsxs(Lt,{title:r.jsxs(X,{children:[r.jsx(Sr,{}),x]}),open:e,onCancel:w,width:700,footer:r.jsx(Qx,{buttons:[...a?[Zx(w)]:[],ev(()=>{const k=v.find(C=>C.id===p);k&&_(k)},{text:i("chat.prompt.createButton"),disabled:!p})]}),styles:{body:{maxHeight:"70vh",overflowY:"auto",padding:l.paddingMD}},children:[r.jsx("div",{style:{marginBottom:l.marginMD},children:r.jsx(fS,{type:"secondary",style:{fontSize:l.fontSizeSM},children:i("chat.prompt.helperText")})}),v.length===0?r.jsx(kt,{description:i("chat.prompt.emptyDescription"),style:{margin:l.marginLG}}):r.jsx("div",{children:v.map(k=>r.jsx(pS,{prompt:k,token:l,isSelected:p===k.id,isExpanded:y===k.id,onSelect:C=>g(C),onToggleExpand:C=>f(y===C?null:C),onCopy:b},k.id))})]})]})},bS=({chat:e,isSelected:t,onSelect:s,onDelete:n,onPin:o,onUnpin:a,onEdit:i,onGenerateTitle:l,onRunProjectDream:c,isGeneratingTitle:d,isRunningProjectDream:u,titleGenerationError:h})=>{const{t:p}=ne(),[g,y]=m.useState(!1),[f,v]=m.useState(e.title),[b,x]=m.useState(!1),[_,w]=m.useState(!1),{token:k}=he.useToken(),C=m.useCallback(S=>{S.stopPropagation(),i&&f.trim()&&i(e.id,f.trim()),y(!1)},[e.id,f,i]),E=m.useCallback(S=>{S.stopPropagation(),v(e.title),y(!1)},[e.title]),j=[{key:"pin",icon:e.pinned?r.jsx(sc,{style:{color:k.colorWarning}}):r.jsx(sd,{}),label:e.pinned?p("chat.actions.unpin"):p("chat.actions.pin"),onClick:({domEvent:S})=>{S.stopPropagation(),e.pinned?a(e.id):o(e.id)}},{key:"edit",icon:r.jsx(ca,{}),label:p("chat.chatItem.edit"),onClick:({domEvent:S})=>{S.stopPropagation(),y(!0)}},...l?[{key:"generate-title",icon:d?r.jsx(gr,{}):r.jsx(ff,{style:h?{color:k.colorError}:void 0}),label:h||p("chat.actions.generateTitle"),disabled:d,onClick:({domEvent:S})=>{S.stopPropagation(),l(e.id)}}]:[],...c?[{key:"run-project-dream",icon:u?r.jsx(gr,{}):r.jsx(rx,{}),label:p("chat.actions.runProjectDream"),disabled:u,onClick:({domEvent:S})=>{S.stopPropagation(),c(e.id)}}]:[],{type:"divider"},{key:"delete",icon:r.jsx(dn,{}),label:p("common.delete"),danger:!0,onClick:({domEvent:S})=>{S.stopPropagation(),n(e.id)}}],R={padding:"8px 12px",borderRadius:k.borderRadiusSM,marginBottom:k.marginXXS,cursor:"pointer",transition:"all 0.2s cubic-bezier(0.4, 0, 0.2, 1)",backgroundColor:t?"var(--lotus-primary-soft)":b||_?"var(--lotus-item-hover-bg)":"transparent",border:"1px solid transparent",borderColor:t?"var(--lotus-tool-card-border)":b||_?k.colorBorderSecondary:"transparent",position:"relative",overflow:"visible",boxShadow:t?"var(--lotus-tool-card-shadow)":"none",transform:b&&!t?"translateX(2px)":"none"},M={flex:1,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",fontSize:13,fontWeight:t?600:500,color:t?"var(--lotus-primary)":k.colorText},T={flex:1,fontSize:k.fontSizeSM,marginRight:k.marginSM},P=g?[r.jsx(Y,{type:"text",size:"small",icon:r.jsx(ox,{style:{color:k.colorSuccess}}),onClick:C,"aria-label":p("common.save")},"save"),r.jsx(Y,{type:"text",size:"small",icon:r.jsx(wr,{style:{color:k.colorError}}),onClick:E,"aria-label":p("common.cancel")},"cancel")]:b||_?[r.jsx(zn,{menu:{items:j,className:"lotus-sidebar-actions-menu"},trigger:["click"],placement:"bottomRight",overlayClassName:"lotus-sidebar-actions-dropdown",open:_,onOpenChange:S=>w(S),children:r.jsx(Y,{type:"text",size:"small",icon:r.jsx(ax,{}),"aria-label":p("common.moreActions","More actions"),onClick:S=>S.stopPropagation(),style:{color:k.colorTextSecondary,borderRadius:k.borderRadiusSM,background:k.colorFillTertiary,width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center"}})},"more")]:[];return r.jsx(nt.Item,{style:R,tabIndex:0,onClick:()=>!g&&s(e.id),onKeyDown:S=>{S.key==="Enter"&&!g?(S.preventDefault(),s(e.id)):(S.key==="Delete"||S.key==="Backspace")&&!g&&S.metaKey&&(S.preventDefault(),n(e.id))},onMouseEnter:()=>x(!0),onMouseLeave:()=>{_||x(!1)},onFocus:()=>x(!0),onBlur:()=>{_||x(!1)},actions:P,"data-testid":"chat-item",role:"option","aria-selected":t,"aria-label":e.title||p("chat.sidebar.untitledChat"),children:r.jsx(nt.Item.Meta,{title:g?r.jsx(me,{value:f,onChange:S=>v(S.target.value),onClick:S=>S.stopPropagation(),onPressEnter:S=>{S.preventDefault(),C(S)},autoFocus:!0,style:T,variant:"borderless",size:"small"}):r.jsxs("div",{style:{...M,display:"flex",alignItems:"center",gap:k.marginXS,minWidth:0},children:[e.pinned&&r.jsx(sc,{style:{color:k.colorWarning,fontSize:11,flexShrink:0}}),r.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.title}),e.kind==="child"?r.jsx(oe,{color:"processing",style:{marginInlineEnd:0,flex:"0 0 auto"},children:p("chat.chatItem.childTag")}):null]})})})},xS=(e,t)=>e.chat.id===t.chat.id&&e.chat.title===t.chat.title&&e.chat.pinned===t.chat.pinned&&e.isSelected===t.isSelected&&e.isGeneratingTitle===t.isGeneratingTitle&&e.isRunningProjectDream===t.isRunningProjectDream&&e.titleGenerationError===t.titleGenerationError,dc=m.memo(bS,xS);dc.displayName="ChatItem";const Eu=e=>({Today:0,Yesterday:1,"This Week":2,"This Month":3})[e]??4,vS=e=>{const t={},s=e.filter(o=>o.pinned);s.length>0&&(t.Pinned=s.sort((o,a)=>a.createdAt-o.createdAt));const n=e.filter(o=>!o.pinned&&!!o.createdByScheduleId);return n.length>0&&(t.Scheduled=n.sort((o,a)=>a.createdAt-o.createdAt)),e.filter(o=>!o.pinned&&!o.createdByScheduleId).forEach(o=>{const i=new Date(o.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"});t[i]||(t[i]=[]),t[i].push(o)}),Object.keys(t).forEach(o=>{t[o].sort((a,i)=>i.createdAt-a.createdAt)}),t},SS=e=>{const t=s=>Array.isArray(s)?s.reduce((n,o)=>Math.max(n,o.createdAt),0):Object.values(s).reduce((n,o)=>{const a=o.reduce((i,l)=>Math.max(i,l.createdAt),0);return Math.max(n,a)},0);return Object.keys(e).sort((s,n)=>{if(s==="Pinned")return-1;if(n==="Pinned")return 1;if(s==="Scheduled")return-1;if(n==="Scheduled")return 1;const o=e[s],a=e[n];if(!o||!a)return 0;const i=t(o),l=t(a);return i!==l?l-i:Eu(s)-Eu(n)})},wS=(e,t)=>e[t]?e[t].map(s=>s.id):[],Hf=(e,t)=>e[t]?e[t].length:0,Ru=e=>e.pinned?"Pinned":e.createdByScheduleId?"Scheduled":new Date(e.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),Au=(e,t)=>{const n={Today:"chat.sidebar.dateGroups.today",Yesterday:"chat.sidebar.dateGroups.yesterday","This Week":"chat.sidebar.dateGroups.thisWeek","This Month":"chat.sidebar.dateGroups.thisMonth",Pinned:"chat.sidebar.dateGroups.pinned",Scheduled:"chat.sidebar.dateGroups.scheduled"}[e];return n?t(n):e},_S=({groupedChatsByDate:e,childrenByRoot:t,expandedRootIds:s,onToggleRootExpanded:n,sortedDateKeys:o,expandedKeys:a,onCollapseChange:i,currentSessionId:l,onSelectChat:c,onDeleteChat:d,onDeleteByDate:u,onPinChat:h,onUnpinChat:p,onEditTitle:g,onGenerateTitle:y,onRunProjectDream:f,titleGenerationState:v,projectDreamState:b,token:x,hasActiveFilters:_})=>{const{t:w}=ne(),k=m.useMemo(()=>o.length?o.map(E=>{const j=e[E],R=Hf(e,E);return{dateKey:E,dateGroup:j,totalChatsInDate:R}}):[],[e,o]);if(!o.length)return r.jsx(kt,{image:kt.PRESENTED_IMAGE_SIMPLE,description:r.jsxs(X,{direction:"vertical",size:4,align:"center",children:[r.jsx("span",{style:{color:x.colorTextSecondary},children:_?w("chat.sidebar.empty.noMatches","No matching sessions"):w("chat.sidebar.empty.noSessions")}),r.jsx("span",{style:{color:x.colorTextSecondary,fontSize:12},children:_?w("chat.sidebar.empty.filterHint","Try adjusting your search or filters"):w("chat.sidebar.empty.hint")}),_&&r.jsx(Y,{size:"small",type:"link",onClick:()=>{var j;const E=document.querySelector('[data-testid="sidebar-search-input"] input, .lotus-sidebar-search input');if(E){const R=(j=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value"))==null?void 0:j.set;R==null||R.call(E,""),E.dispatchEvent(new Event("input",{bubbles:!0}))}},children:w("chat.sidebar.empty.clearFilters","Clear filters")})]})});const C=new Set(a);return r.jsx(X,{direction:"vertical",size:"small",style:{width:"100%"},children:k.map(({dateKey:E,dateGroup:j,totalChatsInDate:R})=>{const M=C.has(E);return r.jsxs("div",{style:{borderRadius:x.borderRadiusSM,background:M?x.colorFillTertiary:"transparent",padding:4},children:[r.jsxs(G,{align:"center",justify:"space-between",style:{cursor:"pointer",padding:"8px 12px",borderRadius:x.borderRadiusSM,transition:"all 0.2s ease",border:"1px solid transparent"},role:"button",tabIndex:0,"aria-expanded":M,"aria-label":`${Au(E,w)} (${R})`,onKeyDown:T=>{if(T.key==="Enter"||T.key===" "){T.preventDefault();const P=new Set(C);P.has(E)?P.delete(E):P.add(E),i(Array.from(P))}},onMouseEnter:T=>{T.currentTarget.style.background="var(--lotus-sidebar-item-hover-bg, rgba(204, 251, 241, 0.92))",T.currentTarget.style.borderColor="var(--lotus-sidebar-item-hover-border, rgba(13, 148, 136, 0.28))";const P=T.currentTarget.querySelector(".chat-sidebar-date-group-delete");P&&(P.style.opacity="1")},onMouseLeave:T=>{T.currentTarget.style.background="transparent",T.currentTarget.style.borderColor="transparent";const P=T.currentTarget.querySelector(".chat-sidebar-date-group-delete");P&&(P.style.opacity="0")},onClick:()=>{const T=new Set(C);T.has(E)?T.delete(E):T.add(E),i(Array.from(T))},className:"chat-sidebar-date-group-header",children:[r.jsxs(G,{align:"center",gap:"small",style:{minWidth:0},children:[M?r.jsx(Wt,{style:{fontSize:12,opacity:.6}}):r.jsx(Ws,{style:{fontSize:12,opacity:.6}}),r.jsxs("span",{style:{fontSize:12,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:E==="Today"?"var(--lotus-primary)":x.colorTextSecondary,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[Au(E,w)," (",R,")"]})]}),r.jsx(Y,{type:"text",size:"small",icon:r.jsx(dn,{}),className:"chat-sidebar-date-group-delete",style:{color:x.colorTextTertiary,opacity:0,transition:"opacity 0.2s ease"},onClick:T=>{T.stopPropagation(),u(E)}})]}),M?r.jsx("div",{style:{marginTop:4},children:r.jsx(nt,{itemLayout:"horizontal",dataSource:j,split:!1,renderItem:T=>{var P,S,L,$,I,W;return r.jsxs("div",{children:[r.jsxs(G,{align:"center",gap:6,children:[(P=t[T.id])!=null&&P.length?r.jsx(Y,{size:"small",type:"text",style:{padding:0,width:22},"aria-label":s.has(T.id)?w("chat.sidebar.actions.collapseChildren"):w("chat.sidebar.actions.expandChildren"),onClick:A=>{A.preventDefault(),A.stopPropagation(),n(T.id)},children:s.has(T.id)?r.jsx(Wt,{}):r.jsx(Ws,{})}):r.jsx("div",{style:{width:22}}),r.jsx("div",{style:{flex:1,minWidth:0},children:r.jsx(dc,{chat:T,isSelected:T.id===l,onSelect:c,onDelete:d,onPin:h,onUnpin:p,onEdit:g,onGenerateTitle:y,onRunProjectDream:f,isGeneratingTitle:((S=v[T.id])==null?void 0:S.status)==="loading",isRunningProjectDream:((L=b[T.id])==null?void 0:L.status)==="loading",titleGenerationError:(($=v[T.id])==null?void 0:$.status)==="error"?(I=v[T.id])==null?void 0:I.error:void 0})})]}),s.has(T.id)&&(((W=t[T.id])==null?void 0:W.length)??0)>0?r.jsx("div",{style:{marginLeft:22,marginTop:2},children:r.jsx(nt,{itemLayout:"horizontal",dataSource:t[T.id],split:!1,renderItem:A=>{var O,D,H,B;return r.jsx("div",{style:{paddingLeft:12},children:r.jsx(dc,{chat:A,isSelected:A.id===l,onSelect:c,onDelete:d,onPin:h,onUnpin:p,onEdit:g,onGenerateTitle:y,onRunProjectDream:f,isGeneratingTitle:((O=v[A.id])==null?void 0:O.status)==="loading",isRunningProjectDream:((D=b[A.id])==null?void 0:D.status)==="loading",titleGenerationError:((H=v[A.id])==null?void 0:H.status)==="error"?(B=v[A.id])==null?void 0:B.error:void 0})},A.id)}})}):null]},T.id)}})}):null]},E)})})},TS="copilot_ui_theme_v1";function kS(){var e;try{const t=localStorage.getItem(TS);if(t==="light"||t==="dark")return t}catch{}return(e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}const qn=un(e=>({themeMode:kS(),setThemeMode:t=>e({themeMode:t}),toggleTheme:()=>e(t=>({themeMode:t.themeMode==="dark"?"light":"dark"}))})),jS="2026.4.29",CS={version:jS},xd=CS.version,{Text:MS}=le,PS=({collapsed:e,onNewChat:t,onOpenSettings:s,screens:n,token:o})=>{const{t:a}=ne(),i=qn(h=>h.themeMode),l=qn(h=>h.toggleTheme),c=a("chat.sidebar.newSession"),d=a("settings.page.title"),u=i==="dark"?a("settings.app.lightMode","Light mode"):a("settings.app.darkMode","Dark mode");return r.jsxs(G,{vertical:!0,gap:e?"small":"middle",style:{padding:e?10:16,background:"transparent",borderTop:`1px solid ${o.colorBorderSecondary}`},children:[r.jsx(Y,{"data-testid":"new-chat","data-tour-id":"new-session",type:"primary",icon:r.jsx(Us,{}),onClick:t,block:!e,shape:"default",size:e?"large":n.xs?"small":"middle",title:c,"aria-label":c,className:"lotus-primary-cta",style:{...e?{width:"44px",height:"44px",margin:"0 auto"}:{},borderRadius:o.borderRadiusLG,minHeight:e?44:46,fontWeight:600},children:!e&&c}),r.jsxs(G,{gap:8,align:"center",children:[r.jsx(Y,{"data-testid":"open-settings","data-tour-id":"open-settings",icon:r.jsx(da,{}),onClick:s,block:!e,shape:"default",size:e?"large":n.xs?"small":"middle",title:d,"aria-label":d,className:"lotus-secondary-button",style:{...e?{width:"44px",height:"44px",margin:"0 auto"}:{},borderRadius:o.borderRadiusLG,minHeight:44,flex:e?void 0:1},children:!e&&d}),!e&&r.jsx(ke,{title:u,placement:"top",children:r.jsx(Y,{"data-testid":"toggle-theme",type:"text",icon:i==="dark"?r.jsx(ix,{}):r.jsx(lx,{}),onClick:l,"aria-label":u,className:"lotus-toolbar-icon",style:{width:44,height:44,borderRadius:o.borderRadiusLG,flexShrink:0}})})]}),!e&&r.jsxs(MS,{type:"secondary","data-testid":"app-version-badge",style:{fontSize:o.fontSizeSM,textAlign:"center",userSelect:"text"},children:[a("settings.appTab.runningVersion","Running version"),": v",xd]})]})},Iu="provider",Bs=un(e=>({isOpen:!1,origin:"chat",activeTabKey:Iu,open:(t,s=Iu)=>e({isOpen:!0,origin:t,activeTabKey:s}),close:()=>e({isOpen:!1}),setActiveTabKey:t=>e({activeTabKey:t})}));function ve(e,t,s,n,o){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,s),s}function q(e,t,s,n){if(s==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return s==="m"?n:s==="a"?n.call(e):n?n.value:t.get(e)}let Yf=function(){const{crypto:e}=globalThis;if(e!=null&&e.randomUUID)return Yf=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),s=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^s()&15>>+n/4).toString(16))};function uc(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const mc=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};class Se extends Error{}class St extends Se{constructor(t,s,n,o){super(`${St.makeMessage(t,s,n)}`),this.status=t,this.headers=o,this.requestID=o==null?void 0:o.get("x-request-id"),this.error=s;const a=s;this.code=a==null?void 0:a.code,this.param=a==null?void 0:a.param,this.type=a==null?void 0:a.type}static makeMessage(t,s,n){const o=s!=null&&s.message?typeof s.message=="string"?s.message:JSON.stringify(s.message):s?JSON.stringify(s):n;return t&&o?`${t} ${o}`:t?`${t} status code (no body)`:o||"(no status code or body)"}static generate(t,s,n,o){if(!t||!o)return new Fi({message:n,cause:mc(s)});const a=s==null?void 0:s.error;return t===400?new Xf(t,a,n,o):t===401?new Vf(t,a,n,o):t===403?new Kf(t,a,n,o):t===404?new Gf(t,a,n,o):t===409?new Jf(t,a,n,o):t===422?new Qf(t,a,n,o):t===429?new Zf(t,a,n,o):t>=500?new eg(t,a,n,o):new St(t,a,n,o)}}class Qt extends St{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}}class Fi extends St{constructor({message:t,cause:s}){super(void 0,void 0,t||"Connection error.",void 0),s&&(this.cause=s)}}class vd extends Fi{constructor({message:t}={}){super({message:t??"Request timed out."})}}class Xf extends St{}class Vf extends St{}class Kf extends St{}class Gf extends St{}class Jf extends St{}class Qf extends St{}class Zf extends St{}class eg extends St{}class tg extends Se{constructor(){super("Could not parse response content as the length limit was reached")}}class sg extends Se{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Lo extends Error{constructor(t){super(t)}}const ES=/^[a-z][a-z0-9+.-]*:/i,RS=e=>ES.test(e);let $t=e=>($t=Array.isArray,$t(e)),$u=$t;function AS(e){return typeof e!="object"?{}:e??{}}function IS(e){if(!e)return!0;for(const t in e)return!1;return!0}function $S(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function al(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}const DS=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new Se(`${e} must be an integer`);if(t<0)throw new Se(`${e} must be a positive integer`);return t},LS=e=>{try{return JSON.parse(e)}catch{return}},ga=e=>new Promise(t=>setTimeout(t,e)),ir="5.10.2",OS=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function FS(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const zS=()=>{var s;const e=FS();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ir,"X-Stainless-OS":Lu(Deno.build.os),"X-Stainless-Arch":Du(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((s=Deno.version)==null?void 0:s.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ir,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ir,"X-Stainless-OS":Lu(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Du(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=NS();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ir,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ir,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function NS(){if(typeof navigator>"u"||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:s}of e){const n=s.exec(navigator.userAgent);if(n){const o=n[1]||0,a=n[2]||0,i=n[3]||0;return{browser:t,version:`${o}.${a}.${i}`}}}return null}const Du=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",Lu=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown");let Ou;const BS=()=>Ou??(Ou=zS());function WS(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function ng(...e){const t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function rg(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return ng({start(){},async pull(s){const{done:n,value:o}=await t.next();n?s.close():s.enqueue(o)},async cancel(){var s;await((s=t.return)==null?void 0:s.call(t))}})}function og(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const s=await t.read();return s!=null&&s.done&&t.releaseLock(),s}catch(s){throw t.releaseLock(),s}},async return(){const s=t.cancel();return t.releaseLock(),await s,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function US(e){var n,o;if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await((o=(n=e[Symbol.asyncIterator]()).return)==null?void 0:o.call(n));return}const t=e.getReader(),s=t.cancel();t.releaseLock(),await s}const qS=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),ag="RFC3986",ig=e=>String(e),Fu={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:ig},HS="RFC1738";let hc=(e,t)=>(hc=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),hc(e,t));const xs=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),il=1024,YS=(e,t,s,n,o)=>{if(e.length===0)return e;let a=e;if(typeof e=="symbol"?a=Symbol.prototype.toString.call(e):typeof e!="string"&&(a=String(e)),s==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let i="";for(let l=0;l<a.length;l+=il){const c=a.length>=il?a.slice(l,l+il):a,d=[];for(let u=0;u<c.length;++u){let h=c.charCodeAt(u);if(h===45||h===46||h===95||h===126||h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||o===HS&&(h===40||h===41)){d[d.length]=c.charAt(u);continue}if(h<128){d[d.length]=xs[h];continue}if(h<2048){d[d.length]=xs[192|h>>6]+xs[128|h&63];continue}if(h<55296||h>=57344){d[d.length]=xs[224|h>>12]+xs[128|h>>6&63]+xs[128|h&63];continue}u+=1,h=65536+((h&1023)<<10|c.charCodeAt(u)&1023),d[d.length]=xs[240|h>>18]+xs[128|h>>12&63]+xs[128|h>>6&63]+xs[128|h&63]}i+=d.join("")}return i};function XS(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function zu(e,t){if($t(e)){const s=[];for(let n=0;n<e.length;n+=1)s.push(t(e[n]));return s}return t(e)}const lg={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},cg=function(e,t){Array.prototype.push.apply(e,$t(t)?t:[t])};let Nu;const dt={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:YS,encodeValuesOnly:!1,format:ag,formatter:ig,indices:!1,serializeDate(e){return(Nu??(Nu=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function VS(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}const ll={};function dg(e,t,s,n,o,a,i,l,c,d,u,h,p,g,y,f,v,b){let x=e,_=b,w=0,k=!1;for(;(_=_.get(ll))!==void 0&&!k;){const M=_.get(e);if(w+=1,typeof M<"u"){if(M===w)throw new RangeError("Cyclic object value");k=!0}typeof _.get(ll)>"u"&&(w=0)}if(typeof d=="function"?x=d(t,x):x instanceof Date?x=p==null?void 0:p(x):s==="comma"&&$t(x)&&(x=zu(x,function(M){return M instanceof Date?p==null?void 0:p(M):M})),x===null){if(a)return c&&!f?c(t,dt.encoder,v,"key",g):t;x=""}if(VS(x)||XS(x)){if(c){const M=f?t:c(t,dt.encoder,v,"key",g);return[(y==null?void 0:y(M))+"="+(y==null?void 0:y(c(x,dt.encoder,v,"value",g)))]}return[(y==null?void 0:y(t))+"="+(y==null?void 0:y(String(x)))]}const C=[];if(typeof x>"u")return C;let E;if(s==="comma"&&$t(x))f&&c&&(x=zu(x,c)),E=[{value:x.length>0?x.join(",")||null:void 0}];else if($t(d))E=d;else{const M=Object.keys(x);E=u?M.sort(u):M}const j=l?String(t).replace(/\./g,"%2E"):String(t),R=n&&$t(x)&&x.length===1?j+"[]":j;if(o&&$t(x)&&x.length===0)return R+"[]";for(let M=0;M<E.length;++M){const T=E[M],P=typeof T=="object"&&typeof T.value<"u"?T.value:x[T];if(i&&P===null)continue;const S=h&&l?T.replace(/\./g,"%2E"):T,L=$t(x)?typeof s=="function"?s(R,S):R:R+(h?"."+S:"["+S+"]");b.set(e,w);const $=new WeakMap;$.set(ll,b),cg(C,dg(P,L,s,n,o,a,i,l,s==="comma"&&f&&$t(x)?null:c,d,u,h,p,g,y,f,v,$))}return C}function KS(e=dt){if(typeof e.allowEmptyArrays<"u"&&typeof e.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof e.encodeDotInKeys<"u"&&typeof e.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&typeof e.encoder<"u"&&typeof e.encoder!="function")throw new TypeError("Encoder has to be a function.");const t=e.charset||dt.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let s=ag;if(typeof e.format<"u"){if(!hc(Fu,e.format))throw new TypeError("Unknown format option provided.");s=e.format}const n=Fu[s];let o=dt.filter;(typeof e.filter=="function"||$t(e.filter))&&(o=e.filter);let a;if(e.arrayFormat&&e.arrayFormat in lg?a=e.arrayFormat:"indices"in e?a=e.indices?"indices":"repeat":a=dt.arrayFormat,"commaRoundTrip"in e&&typeof e.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof e.allowDots>"u"?e.encodeDotInKeys?!0:dt.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:dt.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:dt.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:dt.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?dt.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:dt.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:dt.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:dt.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:dt.encodeValuesOnly,filter:o,format:s,formatter:n,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:dt.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:dt.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:dt.strictNullHandling}}function GS(e,t={}){let s=e;const n=KS(t);let o,a;typeof n.filter=="function"?(a=n.filter,s=a("",s)):$t(n.filter)&&(a=n.filter,o=a);const i=[];if(typeof s!="object"||s===null)return"";const l=lg[n.arrayFormat],c=l==="comma"&&n.commaRoundTrip;o||(o=Object.keys(s)),n.sort&&o.sort(n.sort);const d=new WeakMap;for(let p=0;p<o.length;++p){const g=o[p];n.skipNulls&&s[g]===null||cg(i,dg(s[g],g,l,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,d))}const u=i.join(n.delimiter);let h=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),u.length>0?h+u:""}function JS(e){let t=0;for(const o of e)t+=o.length;const s=new Uint8Array(t);let n=0;for(const o of e)s.set(o,n),n+=o.length;return s}let Bu;function Sd(e){let t;return(Bu??(t=new globalThis.TextEncoder,Bu=t.encode.bind(t)))(e)}let Wu;function Uu(e){let t;return(Wu??(t=new globalThis.TextDecoder,Wu=t.decode.bind(t)))(e)}var Ft,zt;class zi{constructor(){Ft.set(this,void 0),zt.set(this,void 0),ve(this,Ft,new Uint8Array),ve(this,zt,null)}decode(t){if(t==null)return[];const s=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Sd(t):t;ve(this,Ft,JS([q(this,Ft,"f"),s]));const n=[];let o;for(;(o=QS(q(this,Ft,"f"),q(this,zt,"f")))!=null;){if(o.carriage&&q(this,zt,"f")==null){ve(this,zt,o.index);continue}if(q(this,zt,"f")!=null&&(o.index!==q(this,zt,"f")+1||o.carriage)){n.push(Uu(q(this,Ft,"f").subarray(0,q(this,zt,"f")-1))),ve(this,Ft,q(this,Ft,"f").subarray(q(this,zt,"f"))),ve(this,zt,null);continue}const a=q(this,zt,"f")!==null?o.preceding-1:o.preceding,i=Uu(q(this,Ft,"f").subarray(0,a));n.push(i),ve(this,Ft,q(this,Ft,"f").subarray(o.index)),ve(this,zt,null)}return n}flush(){return q(this,Ft,"f").length?this.decode(`
|
|
13
13
|
`):[]}}Ft=new WeakMap,zt=new WeakMap;zi.NEWLINE_CHARS=new Set([`
|
|
14
14
|
`,"\r"]);zi.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function QS(e,t){for(let o=t??0;o<e.length;o++){if(e[o]===10)return{preceding:o,index:o+1,carriage:!1};if(e[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function ZS(e){for(let n=0;n<e.length-1;n++){if(e[n]===10&&e[n+1]===10||e[n]===13&&e[n+1]===13)return n+2;if(e[n]===13&&e[n+1]===10&&n+3<e.length&&e[n+2]===13&&e[n+3]===10)return n+4}return-1}const bi={off:0,error:200,warn:300,info:400,debug:500},qu=(e,t,s)=>{if(e){if($S(bi,e))return e;xt(s).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(bi))}`)}};function Oo(){}function Pa(e,t,s){return!t||bi[e]>bi[s]?Oo:t[e].bind(t)}const ew={error:Oo,warn:Oo,info:Oo,debug:Oo};let Hu=new WeakMap;function xt(e){const t=e.logger,s=e.logLevel??"off";if(!t)return ew;const n=Hu.get(t);if(n&&n[0]===s)return n[1];const o={error:Pa("error",t,s),warn:Pa("warn",t,s),info:Pa("info",t,s),debug:Pa("debug",t,s)};return Hu.set(t,[s,o]),o}const _n=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,s])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":s]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);var Fr;class Cs{constructor(t,s,n){this.iterator=t,Fr.set(this,void 0),this.controller=s,ve(this,Fr,n)}static fromSSEResponse(t,s,n){let o=!1;const a=n?xt(n):console;async function*i(){if(o)throw new Se("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let l=!1;try{for await(const c of tw(t,s))if(!l){if(c.data.startsWith("[DONE]")){l=!0;continue}if(c.event===null||c.event.startsWith("response.")||c.event.startsWith("image_edit.")||c.event.startsWith("image_generation.")||c.event.startsWith("transcript.")){let d;try{d=JSON.parse(c.data)}catch(u){throw a.error("Could not parse message into JSON:",c.data),a.error("From chunk:",c.raw),u}if(d&&d.error)throw new St(void 0,d.error,void 0,t.headers);yield d}else{let d;try{d=JSON.parse(c.data)}catch(u){throw console.error("Could not parse message into JSON:",c.data),console.error("From chunk:",c.raw),u}if(c.event=="error")throw new St(void 0,d.error,d.message,void 0);yield{event:c.event,data:d}}}l=!0}catch(c){if(uc(c))return;throw c}finally{l||s.abort()}}return new Cs(i,s,n)}static fromReadableStream(t,s,n){let o=!1;async function*a(){const l=new zi,c=og(t);for await(const d of c)for(const u of l.decode(d))yield u;for(const d of l.flush())yield d}async function*i(){if(o)throw new Se("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let l=!1;try{for await(const c of a())l||c&&(yield JSON.parse(c));l=!0}catch(c){if(uc(c))return;throw c}finally{l||s.abort()}}return new Cs(i,s,n)}[(Fr=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const t=[],s=[],n=this.iterator(),o=a=>({next:()=>{if(a.length===0){const i=n.next();t.push(i),s.push(i)}return a.shift()}});return[new Cs(()=>o(t),this.controller,q(this,Fr,"f")),new Cs(()=>o(s),this.controller,q(this,Fr,"f"))]}toReadableStream(){const t=this;let s;return ng({async start(){s=t[Symbol.asyncIterator]()},async pull(n){try{const{value:o,done:a}=await s.next();if(a)return n.close();const i=Sd(JSON.stringify(o)+`
|
|
15
15
|
`);n.enqueue(i)}catch(o){n.error(o)}},async cancel(){var n;await((n=s.return)==null?void 0:n.call(s))}})}}async function*tw(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Se("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new Se("Attempted to iterate over a response with no body");const s=new nw,n=new zi,o=og(e.body);for await(const a of sw(o))for(const i of n.decode(a)){const l=s.decode(i);l&&(yield l)}for(const a of n.flush()){const i=s.decode(a);i&&(yield i)}}async function*sw(e){let t=new Uint8Array;for await(const s of e){if(s==null)continue;const n=s instanceof ArrayBuffer?new Uint8Array(s):typeof s=="string"?Sd(s):s;let o=new Uint8Array(t.length+n.length);o.set(t),o.set(n,t.length),t=o;let a;for(;(a=ZS(t))!==-1;)yield t.slice(0,a),t=t.slice(a)}t.length>0&&(yield t)}class nw{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(t){if(t.endsWith("\r")&&(t=t.substring(0,t.length-1)),!t){if(!this.event&&!this.data.length)return null;const a={event:this.event,data:this.data.join(`
|
|
@@ -109,7 +109,7 @@ You are running on **${h_(e)}**.`;return e==="windows"?s+`
|
|
|
109
109
|
|
|
110
110
|
`),jy=()=>{try{return localStorage.getItem(ky)??""}catch(e){return console.error("Failed to load system prompt enhancement:",e),""}},v_=e=>{try{const t=e.trim()?e:"";localStorage.setItem(ky,t)}catch(t){console.error("Failed to save system prompt enhancement:",t)}},S_=e=>{const t=[];t.push(p_().trim()),t.push(b_().trim());const s=jy().trim();return s&&t.push(s),Cc()&&t.push(c_().trim()),Pc()&&t.push(m_().trim()),(e??"").trim().toLowerCase()==="copilot"&&ki()&&t.push(g_().trim()),t},w_=e=>x_(S_(e)),Ec=e=>{const t=(e??"").trim().toLowerCase();return t.includes("completion policy violation")&&t.includes("conclusion_with_options")},Rc=e=>{const t=(e??"").trim(),s=t?`
|
|
111
111
|
|
|
112
|
-
Raw error: ${t}`:"";return["Bamboo stopped this completion because Copilot conclusion_with_options confirmation is enabled for this session.","The assistant tried to finish with plain text instead of calling conclusion_with_options.","Next steps: retry the request, shorten or clarify the prompt, or temporarily disable the Copilot conclusion_with_options enhancement for this session if you do not want enforced confirmation."].join(" ")+s};function Cy(e){var R;const{modal:t,message:s}=Ot.useApp(),{t:n}=ne(),o=m.useRef(null),a=m.useRef(null),i=m.useRef(""),l=m.useRef(new rs),c=N(M=>M.agentAvailability),d=N(M=>M.setAgentAvailability),u=N(M=>M.checkAgentAvailability),h=N(M=>M.startAgentHealthCheck),p=Hi(e.sessionId),g=Ee(M=>M.currentProvider),y=N(M=>e.sessionId&&M.chats.find(T=>T.id===e.sessionId)||null),f=Bd((R=y==null?void 0:y.config)==null?void 0:R.model_ref);m.useEffect(()=>{h()},[h]);const v=m.useCallback(()=>{var T;(T=o.current)==null||T.abort();const M=y==null?void 0:y.id;M&&l.current.stopGeneration(M).catch(P=>{console.error("[useMessageStreaming] Failed to stop generation:",P)})},[y==null?void 0:y.id]),b=m.useCallback(M=>{var O;const T=N.getState(),S=(Array.isArray(T.chats)?T.chats:[]).find(D=>D.id===M),L=T.pendingQuestionRespond,$=(L==null?void 0:L.sessionId)===M?L:null,I=(O=S==null?void 0:S.config)==null?void 0:O.syncCursor,W=!!$||!!(I!=null&&I.hasPendingQuestion),A=($==null?void 0:$.toolCallId)??(I==null?void 0:I.pendingQuestionToolCallId)??null;return{client_message_count:(I==null?void 0:I.messageCount)??(S==null?void 0:S.messageCount)??0,client_last_message_id:(I==null?void 0:I.lastMessageId)??null,client_has_pending_question:W,client_pending_question_tool_call_id:A}},[]),x=m.useCallback((M,T)=>{const P=T.sync;if(!P)return;const S=N.getState(),$=(Array.isArray(S.chats)?S.chats:[]).find(I=>I.id===M);$&&e.updateSession(M,{messageCount:P.server_message_count,config:{...$.config||{},syncCursor:{messageCount:P.server_message_count,lastMessageId:P.server_last_message_id??null,hasPendingQuestion:P.has_pending_question,pendingQuestionToolCallId:P.pending_question_tool_call_id??null}}})},[e]),_=m.useCallback(async M=>{try{return await pe.get(`respond/${M}/pending`)}catch(T){return console.warn(`[useMessageStreaming] Failed to fetch pending question for ${M}:`,T),{has_pending_question:!1}}},[]),w=m.useCallback(async(M,T,P)=>{var A,O;e.setSessionProcessing(M,!1),await N.getState().loadChatHistory(M,{mode:"replace"});const S=await _(M),L=N.getState().setPendingQuestionRespond,$=N.getState().clearPendingQuestionRespondForSession;if(S.has_pending_question){L({sessionId:M,question:S.question||"",options:S.options||[],allowCustom:S.allow_custom??!0,toolCallId:S.tool_call_id??null});const D=N.getState().chats.find(H=>H.id===M);return D&&e.updateSession(M,{config:{...D.config||{},syncCursor:{messageCount:D.messageCount??D.messages.length,lastMessageId:((O=(A=D.config)==null?void 0:A.syncCursor)==null?void 0:O.lastMessageId)??null,hasPendingQuestion:!0,pendingQuestionToolCallId:S.tool_call_id??null}}}),null}if($(M),!((T==null?void 0:T.has_pending_user_message)??!1))return null;e.setSessionProcessing(M,!0),await new Promise(D=>setTimeout(D,0));const W=P?await l.current.execute(M,void 0,P,b(M),f??void 0):await l.current.execute(M,void 0,void 0,b(M),f??void 0);return x(M,W),W},[f,x,b,e,_]),k=m.useCallback(async(M,T,P)=>{var I,W;let S=T;x(M,S);const L=2;let $=0;for(;(I=S.sync)!=null&&I.need_sync&&$<L;){const A=await w(M,S.sync,P);if($+=1,!A){e.setSessionProcessing(M,!1);return}S=A,x(M,S)}if((W=S.sync)!=null&&W.need_sync){console.warn(`[useMessageStreaming] Execute remains out-of-sync after ${L} recovery attempt(s) for session ${M}.`,S.sync),e.setSessionProcessing(M,!1);return}if(!["started","already_running"].includes(S.status)){if(S.status==="completed"){st("[Streaming]","[Agent] Session already completed"),e.setSessionProcessing(M,!1);return}throw console.error("[Agent] Execute failed:",S.status),e.setSessionProcessing(M,!1),new Error(`Execute failed: ${S.status}`)}},[x,e,w]),C=m.useCallback(async(M,T,P,S,L)=>{var I,W;if(!p)throw new Error(n("chat.model.noModelSelected"));const $=new AbortController;o.current=$;try{const A=w_(g).trim(),O=(g??"").trim().toLowerCase()==="copilot"&&ki(),H=(((I=y==null?void 0:y.config)==null?void 0:I.workspacePath)||"").trim().replace(/\/+$/,"").replace(/\\+$/,""),B=await l.current.sendMessage({message:M,session_id:T,enhance_prompt:A||void 0,copilot_conclusion_with_options_enhancement_enabled:O,workspace_path:H||void 0,selected_skill_ids:L&&L.length>0?L:void 0,images:(W=P.images)==null?void 0:W.filter(z=>!!z.base64).map(z=>({base64:z.base64,name:z.name,size:z.size,type:z.type})),model:p,...f?{model_ref:f,provider:f.provider}:{}}),{session_id:K}=B;K!==T&&console.warn(`[useMessageStreaming] Backend returned unexpected session_id=${K} for sessionId=${T}`),await N.getState().loadChatHistory(T,{mode:"replace"}),e.setSessionProcessing(T,!0),await new Promise(z=>setTimeout(z,0));const F=S?await l.current.execute(T,void 0,S,b(T),f??void 0):await l.current.execute(T,void 0,void 0,b(T),f??void 0);st("[Streaming]","[Agent] Execute status:",F.status),await k(T,F,S)}catch(A){throw A}},[p,f,b,y,g,e,k,n]),E=m.useCallback(async(M,T,P,S)=>{if(!y){t.info({title:n("chat.streaming.noActiveChatTitle"),content:n("chat.streaming.noActiveChatSendContent")});return}if(!e.sessionId){t.info({title:n("chat.streaming.noChatIdTitle"),content:n("chat.streaming.noChatIdSendContent")});return}if(!p){t.error({title:n("chat.model.noModelSelected"),content:n("chat.model.selectModelBeforeSend")});return}let L=c;if(L===null&&(L=await u()),!L){s.error(n("chat.streaming.agentUnavailable"));return}if(!p){s.error(n("chat.streaming.modelConfigNotLoaded"));return}const $=e.sessionId,I=(T==null?void 0:T.map(A=>({id:A.id,base64:A.base64,name:A.name,size:A.size,type:A.type})))||[],W={role:"user",content:M,id:crypto.randomUUID(),createdAt:new Date().toISOString(),images:I};await e.addMessage($,W);try{st("[Streaming]","[useChatStreaming] Using Agent Server"),await C(M,$,W,P,S)}catch(A){if(a.current&&ze.clear($,a.current),a.current=null,i.current="",A instanceof Error&&A.name==="AbortError")s.info(n("chat.streaming.requestCancelled"));else{console.error("[useChatStreaming] Failed to send message:",A);const O=A instanceof Error?A.message:String(A??"");Ec(O)?s.error(Rc(O)):(s.error(n("chat.streaming.sendFailed")),d(!1))}e.setSessionProcessing($,!1)}finally{o.current=null,a.current&&ze.clear($,a.current),a.current=null,i.current=""}},[c,s,u,y,e,t,C,d,p,n]),j=m.useCallback(async(M,T="regenerate")=>{if(!y){t.info({title:n("chat.streaming.noActiveChatTitle"),content:n("chat.streaming.noActiveChatRetryContent")});return}if(!e.sessionId){t.info({title:n("chat.streaming.noChatIdTitle"),content:n("chat.streaming.noChatIdRetryContent")});return}if(!p){t.error({title:n("chat.model.noModelSelected"),content:n("chat.model.selectModelBeforeRetry")});return}let P=c;if(P===null&&(P=await u()),!P){s.error(n("chat.streaming.agentUnavailable"));return}const S=e.sessionId;a.current&&ze.clear(S,a.current),a.current=null,i.current="";try{const L=T==="error_retry"?"error_retry":"after_last_user",$=await l.current.truncateSessionMessages(S,{mode:L});(T==="regenerate"||($.messages_removed??0)>0)&&await N.getState().loadChatHistory(S,{mode:"replace"}),e.setSessionProcessing(S,!0);const I=M?await l.current.execute(S,void 0,M,b(S),f??void 0):await l.current.execute(S,void 0,void 0,b(S),f??void 0);await k(S,I,M)}catch(L){console.error("[useMessageStreaming] Retry failed:",L);const $=L instanceof Error?L.message:String(L??"");Ec($)?s.error(Rc($)):s.error(n("chat.streaming.retryFailed")),e.setSessionProcessing(S,!1)}finally{o.current=null}},[p,f,c,s,b,u,y,e,k,t,n]);return{sendMessage:E,retryLastTurn:j,cancel:v,agentAvailable:c}}function __(e,t){const s=m.useMemo(()=>e.baseMessages,[e.baseMessages]),n=m.useCallback(async()=>{var d;if(!e.currentSessionId||!e.currentChat)return;const o=[...e.baseMessages];if(o.length===0)return;const a=o[o.length-1];let i=o;if((a==null?void 0:a.role)==="assistant"){if(!(await e.deleteMessage(e.currentSessionId,a.id)).success)return;i=o.slice(0,-1)}const l=[...i].reverse().find(u=>u.role==="user");if(!l)return;const c="content"in l?l.content:l.displayText;typeof c=="string"&&await((d=t==null?void 0:t.onRetry)==null?void 0:d.call(t,c))},[e,t]);return{currentMessages:s,retryLastMessage:n}}const T_=()=>{const e=a_(),t=Ud(e),s=i_(e),n=Cy({sessionId:e.currentSessionId,addMessage:e.addMessage,setSessionProcessing:e.setSessionProcessing,updateSession:e.updateSession}),o=__(e,{onRetry:n.sendMessage});return{chats:e.chats,currentSessionId:e.currentSessionId,currentChat:e.currentChat,pinnedChats:e.pinnedChats,unpinnedChats:e.unpinnedChats,chatCount:e.chatCount,currentMessages:o.currentMessages,agentAvailable:n.agentAvailable,titleGenerationState:t.titleGenerationState,autoGenerateTitles:t.autoGenerateTitles,isUpdatingAutoTitlePreference:t.isUpdatingAutoTitlePreference,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,generateChatTitle:t.generateChatTitle,setAutoGenerateTitlesPreference:t.setAutoGenerateTitlesPreference,createNewChat:s.createNewChat,createChatWithSystemPrompt:s.createChatWithSystemPrompt,toggleChatPin:s.toggleChatPin,updateChatTitle:s.updateChatTitle,deleteEmptyChats:s.deleteEmptyChats,deleteAllUnpinnedChats:s.deleteAllUnpinnedChats,deleteAllChats:s.deleteAllChats,retryLastMessage:o.retryLastMessage,sendMessage:n.sendMessage,cancelMessage:n.cancel}},My="lotus_vdi_safe_mode",ji=()=>{try{return localStorage.getItem(My)==="true"}catch{return!1}},k_=e=>{try{localStorage.setItem(My,e.toString())}catch(t){console.error("[vdiSafeMode] Failed to persist setting:",t)}},{Text:Fa}=le,{useToken:j_}=he,C_=({httpProxy:e,httpsProxy:t,onHttpProxyChange:s,onHttpsProxyChange:n,onReload:o,onSave:a,isLoading:i})=>{const{t:l}=ne(),{token:c}=j_(),d=ms(w=>w.proxyAuthStatus),u=ms(w=>w.isLoadingProxyAuthStatus),h=ms(w=>w.loadProxyAuthStatus),p=ms(w=>w.applyProxyAuth),g=ms(w=>w.clearProxyAuth),[y,f]=m.useState({username:"",password:""}),[v,b]=m.useState(!1);m.useEffect(()=>{h()},[h]);const x=async()=>{const w=y.username.trim();if(w){b(!0);try{await p({username:w,password:y.password}),f({username:"",password:""})}catch(k){console.error("Failed to apply proxy auth:",k)}finally{b(!1)}}},_=async()=>{b(!0);try{await g()}catch(w){console.error("Failed to clear proxy auth:",w)}finally{b(!1)}};return r.jsx(ee,{size:"small",title:r.jsx(Fa,{strong:!0,children:l("settings.networkCard.title")}),className:"lotus-settings-card",children:r.jsxs(X,{direction:"vertical",size:c.marginSM,style:{width:"100%"},children:[r.jsx(Xe,{message:l("settings.networkCard.guideTip"),type:"info",showIcon:!0}),r.jsxs(X,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[r.jsx(Fa,{type:"secondary",children:l("settings.networkCard.httpProxy")}),r.jsx(me,{"data-testid":"proxy-url",style:{width:"100%"},value:e,onChange:w=>s(w.target.value),placeholder:l("settings.networkCard.proxyPlaceholder"),disabled:i})]}),r.jsxs(X,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[r.jsx(Fa,{type:"secondary",children:l("settings.networkCard.httpsProxy")}),r.jsx(me,{style:{width:"100%"},value:t,onChange:w=>n(w.target.value),placeholder:l("settings.networkCard.proxyPlaceholder"),disabled:i})]}),r.jsx(ee,{size:"small",title:l("settings.networkCard.proxyAuthTitle"),className:"lotus-settings-card",style:{marginTop:c.marginSM},children:d!=null&&d.configured?r.jsxs(X,{direction:"vertical",style:{width:"100%"},children:[r.jsx(Xe,{type:"success",message:l("settings.networkCard.proxyConfiguredForUser",{username:d.username??""}),showIcon:!0}),r.jsx(Y,{onClick:_,loading:v||u,danger:!0,children:l("settings.networkCard.clearCredentials")})]}):r.jsxs(X,{direction:"vertical",size:c.marginXS,style:{width:"100%"},children:[r.jsx(me,{placeholder:l("settings.networkCard.username"),value:y.username,onChange:w=>f(k=>({...k,username:w.target.value}))}),r.jsx(me.Password,{placeholder:l("settings.networkCard.password"),value:y.password,onChange:w=>f(k=>({...k,password:w.target.value}))}),r.jsx(Y,{type:"primary",onClick:x,loading:v||u,disabled:!y.username.trim(),children:l("settings.networkCard.apply")})]})}),r.jsx(Fa,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l("settings.networkCard.credentialsStorageNote")}),r.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:c.marginSM},children:[r.jsx(Y,{onClick:()=>Promise.resolve(o()).finally(()=>h({force:!0})),disabled:i,children:l("settings.networkCard.reload")}),r.jsx(Y,{"data-testid":"save-proxy-settings",type:"primary",onClick:()=>Promise.resolve(a()).finally(()=>h({force:!0})),disabled:i,children:l("settings.networkCard.save")})]})]})})},{Text:M_}=le,{useToken:P_}=he,E_=({msgApi:e})=>{const{t}=ne(),{token:s}=P_(),[n]=Z.useForm(),[o,a]=m.useState(!1),[i,l]=m.useState(!1),[c,d]=m.useState(!1),[u,h]=m.useState(!1),[p,g]=m.useState(null),y=c&&!u,f=m.useMemo(()=>c?u?t("settings.configTab.accessPassword.helperLocalBypass","当前是本地访问,可直接修改访问密码,无需输入当前密码。"):t("settings.configTab.accessPassword.helperRemote","当前是远程访问。修改访问密码前,必须先输入当前密码。"):t("settings.configTab.accessPassword.helperNotEnabled","未设置访问密码。设置后,远程访问需要先输入密码,本地 loopback 访问可直接绕过。"),[u,c,t]),v=m.useCallback(async()=>{a(!0),g(null);try{const x=await et.getAccessStatus();d(x.password_enabled),h(x.local_bypass)}catch(x){const _=x instanceof Error?x.message:t("settings.configTab.accessPassword.loadStatusFailed","Failed to load access status");g(_)}finally{a(!1)}},[t]);m.useEffect(()=>{v()},[v]);const b=async()=>{var x;try{const _=await n.validateFields();l(!0),await et.updateAccessPassword({current_password:((x=_.currentPassword)==null?void 0:x.trim())||void 0,new_password:_.newPassword.trim()}),e.success(c?t("settings.configTab.accessPassword.updated","访问密码已更新"):t("settings.configTab.accessPassword.enabled","访问密码已设置")),n.resetFields(),await v()}catch(_){if(_.errorFields)return;const w=_ instanceof Error?_.message:t("settings.configTab.accessPassword.updateFailed","Failed to update access password");e.error(w)}finally{l(!1)}};return r.jsx(ee,{size:"small",className:"lotus-settings-card",title:r.jsx(M_,{strong:!0,children:t("settings.configTab.accessPasswordTitle","访问密码")}),children:r.jsxs(X,{direction:"vertical",size:s.marginMD,style:{width:"100%"},children:[r.jsx(Xe,{type:c?"info":"warning",showIcon:!0,message:c?t("settings.configTab.accessPassword.statusEnabled","访问密码已启用"):t("settings.configTab.accessPassword.statusDisabled","访问密码未启用"),description:f}),p?r.jsx(Xe,{type:"error",showIcon:!0,message:p}):null,r.jsxs(Z,{form:n,layout:"vertical",disabled:o||i,children:[y?r.jsx(Z.Item,{label:t("settings.configTab.accessPassword.currentPasswordLabel","当前密码"),name:"currentPassword",rules:[{required:!0,message:t("settings.configTab.accessPassword.validation.currentPasswordRequired","请输入当前密码")}],children:r.jsx(me.Password,{autoComplete:"current-password"})}):null,r.jsx(Z.Item,{label:c?t("settings.configTab.accessPassword.newPasswordLabel","新密码"):t("settings.configTab.accessPassword.setPasswordLabel","设置密码"),name:"newPassword",rules:[{required:!0,message:t("settings.configTab.accessPassword.validation.newPasswordRequired","请输入新密码")},{min:4,message:t("settings.configTab.accessPassword.validation.minLength","密码长度至少 4 位")}],children:r.jsx(me.Password,{autoComplete:"new-password"})}),r.jsx(Z.Item,{label:t("settings.configTab.accessPassword.confirmPasswordLabel","确认密码"),name:"confirmPassword",dependencies:["newPassword"],rules:[{required:!0,message:t("settings.configTab.accessPassword.validation.confirmPasswordRequired","请再次输入新密码")},({getFieldValue:x})=>({validator(_,w){return!w||x("newPassword")===w?Promise.resolve():Promise.reject(new Error(t("settings.configTab.accessPassword.validation.passwordMismatch","两次输入的密码不一致")))}})],children:r.jsx(me.Password,{autoComplete:"new-password"})}),r.jsx(Y,{type:"primary",loading:i,onClick:()=>void b(),children:c?t("settings.configTab.accessPassword.updateAction","更新访问密码"):t("settings.configTab.accessPassword.enableAction","启用访问密码")})]})]})})},{Text:qt}=le,{useToken:R_}=he,ym="http://127.0.0.1:9562/v1",Xo=e=>[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort(),A_=e=>{var s;const t=(s=e.tools)==null?void 0:s.disabled;return Array.isArray(t)?Xo(t.filter(n=>typeof n=="string")):[]},I_=({msgApi:e,locale:t,onLocaleChange:s})=>{const{t:n}=ne(),{token:o}=R_(),[a,i]=m.useState({http_proxy:"",https_proxy:"",memory:{auto_dream_enabled:!1,background_model:""}}),[l,c]=m.useState(ym),[d,u]=m.useState([]),[h,p]=m.useState([]),[g,y]=m.useState([]),[f,v]=m.useState(!1),[b,x]=m.useState(!1),_=m.useCallback(async()=>{var I,W;v(!0);try{const[A,O]=await Promise.all([et.getBambooConfig(),et.getBambooTools()]);i({http_proxy:A.http_proxy||"",https_proxy:A.https_proxy||"",memory:{auto_dream_enabled:((I=A.memory)==null?void 0:I.auto_dream_enabled)??!1,background_model:((W=A.memory)==null?void 0:W.background_model)||""}});const D=A_(A);p(D),y(D),u(Xo(O.tools||[]))}catch(A){console.error("Failed to load config:",A),e.error(n("settings.configTab.loadConfigFailed"))}finally{v(!1)}},[e,n]);m.useEffect(()=>{_()},[_]);const w=I=>{i(W=>({...W,http_proxy:I}))},k=I=>{i(W=>({...W,https_proxy:I}))},C=I=>{i(W=>({...W,memory:{...W.memory,auto_dream_enabled:I}}))},E=I=>{i(W=>({...W,memory:{...W.memory,background_model:I}}))},j=async()=>{var I,W;v(!0);try{const A=await et.validateBambooConfigPatch(a);if(!A.valid){const D=((W=(I=A.errors)==null?void 0:I.proxy)==null?void 0:W[0])??Object.values(A.errors||{}).flat().filter(Boolean)[0];e.error((D==null?void 0:D.message)||n("settings.configTab.invalidConfig"));return}await et.setBambooConfig(a),e.success(n("settings.configTab.saveConfigSuccess"))}catch(A){console.error("Failed to save config:",A);const O=A instanceof Error&&A.message.trim()?A.message:n("settings.configTab.saveConfigFailed");e.error(O)}finally{v(!1)}},R=async()=>{e.success(n("settings.configTab.backendSaved"))},M=()=>{c(ym),e.success(n("settings.configTab.backendResetDefault"))},T=(I,W)=>{p(A=>{const O=new Set(A);return W?O.delete(I):O.add(I),Xo([...O])})},P=async()=>{x(!0);try{const I=await et.getBambooTools();u(Xo(I.tools||[])),e.success(n("settings.configTab.toolsReloadSuccess"))}catch(I){console.error("Failed to reload tools:",I),e.error(n("settings.configTab.toolsLoadFailed"))}finally{x(!1)}},S=async()=>{x(!0);try{const I=Xo(h);await et.setBambooConfig({tools:{disabled:I}}),p(I),y(I),e.success(n("settings.configTab.toolsSaveSuccess"))}catch(I){console.error("Failed to save tool settings:",I),e.error(n("settings.configTab.toolsSaveFailed"))}finally{x(!1)}},L=JSON.stringify(h)!==JSON.stringify(g),$=new Set(h);return r.jsx(ps,{spinning:f,tip:n("settings.common.loading"),children:r.jsx(ui,{items:[{key:"general",label:n("settings.configTab.tabs.general"),children:r.jsxs(X,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[r.jsx(Xe,{message:n("settings.configTab.providerMovedTitle"),description:n("settings.configTab.providerMovedDescription"),type:"info",showIcon:!0,closable:!0}),r.jsx(C_,{httpProxy:a.http_proxy,httpsProxy:a.https_proxy,onHttpProxyChange:w,onHttpsProxyChange:k,onReload:_,onSave:j,isLoading:f}),r.jsx(ee,{size:"small",className:"lotus-settings-card",title:r.jsx(qt,{strong:!0,children:n("settings.configTab.language")}),children:r.jsx(Pe,{value:t,style:{width:260},options:[{label:n("settings.configTab.languageEnglish"),value:"en-US"},{label:n("settings.configTab.languageChinese"),value:"zh-CN"},{label:n("settings.configTab.languageTraditionalChinese"),value:"zh-TW"},{label:n("settings.configTab.languageFrench"),value:"fr-FR"},{label:n("settings.configTab.languageJapanese"),value:"ja-JP"},{label:n("settings.configTab.languageHindi"),value:"hi-IN"}],onChange:I=>s(I)})}),r.jsx(ee,{size:"small",className:"lotus-settings-card",title:r.jsx(qt,{strong:!0,children:n("settings.configTab.memoryTitle")}),children:r.jsxs(X,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[r.jsx(qt,{type:"secondary",children:n("settings.configTab.memoryDescription")}),r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:o.marginMD,flexWrap:"wrap"},children:[r.jsxs("div",{children:[r.jsx(qt,{strong:!0,children:n("settings.configTab.autoDreamEnabled")}),r.jsx("div",{children:r.jsx(qt,{type:"secondary",style:{fontSize:o.fontSizeSM},children:n("settings.configTab.autoDreamEnabledHint")})})]}),r.jsx(it,{"data-testid":"auto-dream-toggle",checked:a.memory.auto_dream_enabled,onChange:C})]}),r.jsxs(X,{direction:"vertical",size:o.marginXXS,style:{width:"100%"},children:[r.jsx(qt,{strong:!0,children:n("settings.configTab.backgroundModel")}),r.jsx(me,{"data-testid":"auto-dream-background-model-input",value:a.memory.background_model,onChange:I=>E(I.target.value),placeholder:n("settings.configTab.backgroundModelPlaceholder")}),r.jsx(qt,{type:"secondary",style:{fontSize:o.fontSizeSM},children:n("settings.configTab.backgroundModelHint")})]}),r.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:r.jsx(Y,{"data-testid":"save-memory-settings",type:"primary",onClick:j,loading:f,children:n("settings.configTab.save")})})]})}),r.jsx(ee,{size:"small",title:r.jsx(qt,{strong:!0,children:n("settings.configTab.backendApiBaseUrlTitle")}),children:r.jsxs(X,{direction:"vertical",size:o.marginSM,style:{width:"100%"},children:[r.jsx(X,{direction:"vertical",size:o.marginXXS,style:{width:"100%"},children:r.jsx(me,{style:{width:"100%"},value:l,onChange:I=>c(I.target.value),placeholder:n("settings.configTab.backendApiPlaceholder")})}),r.jsx(qt,{type:"secondary",style:{fontSize:o.fontSizeSM},children:n("settings.configTab.backendApiHint")}),r.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:o.marginSM},children:[r.jsx(Y,{"data-testid":"reset-to-defaults",onClick:M,children:n("settings.configTab.resetToDefault")}),r.jsx(Y,{"data-testid":"save-api-settings",type:"primary",onClick:R,children:n("settings.configTab.save")})]})]})}),r.jsx(E_,{msgApi:e})]})},{key:"tools",label:n("settings.configTab.tabs.tools"),children:r.jsx(ee,{size:"small",title:r.jsx(qt,{strong:!0,children:n("settings.configTab.toolsTitle")}),children:r.jsxs(X,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[r.jsx(qt,{type:"secondary",children:n("settings.configTab.toolsDescription")}),d.length===0?r.jsx(Xe,{type:"info",showIcon:!0,message:n("settings.configTab.toolsEmpty")}):r.jsx(nt,{bordered:!0,dataSource:d,renderItem:I=>r.jsx(nt.Item,{actions:[r.jsx(it,{checked:!$.has(I),onChange:W=>T(I,W)},`${I}-switch`)],children:r.jsx(qt,{code:!0,children:I})})}),r.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:o.marginSM},children:[r.jsx(Y,{onClick:P,loading:b,children:n("settings.configTab.reloadTools")}),r.jsx(Y,{type:"primary",onClick:S,loading:b,disabled:!L,children:n("settings.configTab.save")})]})]})})}]})})},bm={theme:"default",themeVariables:{},fontSize:16,defaultScale:1,useMaxWidth:!0,flowchartNodeSpacing:50,flowchartRankSpacing:50,flowchartCurve:"basis",sequenceActorMargin:50,sequenceMessageMargin:35,sequenceWidth:150,sequenceHeight:65,ganttBarHeight:20,ganttTopPadding:50},Hd=un()(hv(e=>({settings:bm,updateSettings:t=>e(s=>({settings:{...s.settings,...t}})),resetSettings:()=>e({settings:bm})}),{name:"mermaid-settings"})),Xi=()=>Hd(t=>t.settings),$_=()=>Hd(e=>e.updateSettings),D_=()=>Hd(e=>e.resetSettings),{Title:L_,Text:vl}=le,{useToken:O_}=he,F_=()=>{const{t:e}=ne(),{token:t}=O_(),s=Xi(),n=$_(),o=D_(),[a]=Z.useForm();ut.useEffect(()=>{a.setFieldsValue(s)},[s,a]);const i=c=>{n(c)},l=()=>{o(),a.resetFields()};return r.jsxs("div",{style:{padding:"24px",maxWidth:"1200px",margin:"0 auto"},children:[r.jsx(L_,{level:3,style:{marginBottom:"8px"},children:e("settings.mermaidTab.title")}),r.jsx(vl,{type:"secondary",style:{display:"block",marginBottom:"24px"},children:e("settings.mermaidTab.description")}),r.jsxs(Z,{form:a,layout:"vertical",initialValues:s,onValuesChange:i,children:[r.jsxs(ee,{title:e("settings.mermaidTab.themeCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:[r.jsx(Gt,{gutter:16,children:r.jsx(Oe,{span:24,children:r.jsx(Z.Item,{name:"theme",label:r.jsxs(X,{children:[e("settings.mermaidTab.themeLabel"),r.jsx(ke,{title:e("settings.mermaidTab.themeTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsxs(Pe,{children:[r.jsx(Pe.Option,{value:"default",children:e("settings.mermaidTab.themeOptions.default")}),r.jsx(Pe.Option,{value:"neutral",children:e("settings.mermaidTab.themeOptions.neutral")}),r.jsx(Pe.Option,{value:"dark",children:e("settings.mermaidTab.themeOptions.dark")}),r.jsx(Pe.Option,{value:"forest",children:e("settings.mermaidTab.themeOptions.forest")}),r.jsx(Pe.Option,{value:"base",children:e("settings.mermaidTab.themeOptions.base")})]})})})}),r.jsxs(vl,{type:"secondary",style:{display:"block",marginTop:"8px"},children:[r.jsx("strong",{children:e("settings.mermaidTab.themeDescriptionsTitle")}),r.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.default"),r.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.neutral"),r.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.dark"),r.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.forest"),r.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.base")]})]}),r.jsxs(ee,{title:e("settings.mermaidTab.globalCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:[r.jsxs(Gt,{gutter:16,children:[r.jsx(Oe,{span:12,children:r.jsx(Z.Item,{name:"fontSize",label:r.jsxs(X,{children:[e("settings.mermaidTab.fontSizeLabel"),r.jsx(ke,{title:e("settings.mermaidTab.fontSizeTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:10,max:32,step:1,style:{width:"100%"},addonAfter:"px"})})}),r.jsx(Oe,{span:12,children:r.jsx(Z.Item,{name:"defaultScale",label:r.jsxs(X,{children:[e("settings.mermaidTab.defaultZoomLabel"),r.jsx(ke,{title:e("settings.mermaidTab.defaultZoomTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:.1,max:3,step:.1,style:{width:"100%"}})})})]}),r.jsx(Z.Item,{name:"useMaxWidth",label:r.jsxs(X,{children:[e("settings.mermaidTab.responsiveWidthLabel"),r.jsx(ke,{title:e("settings.mermaidTab.responsiveWidthTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),valuePropName:"checked",children:r.jsx(it,{})})]}),r.jsx(ee,{title:e("settings.mermaidTab.flowchartCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsxs(Gt,{gutter:16,children:[r.jsx(Oe,{span:8,children:r.jsx(Z.Item,{name:"flowchartNodeSpacing",label:r.jsxs(X,{children:[e("settings.mermaidTab.flowchartNodeSpacingLabel"),r.jsx(ke,{title:e("settings.mermaidTab.flowchartNodeSpacingTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:20,max:200,step:10,style:{width:"100%"}})})}),r.jsx(Oe,{span:8,children:r.jsx(Z.Item,{name:"flowchartRankSpacing",label:r.jsxs(X,{children:[e("settings.mermaidTab.flowchartRankSpacingLabel"),r.jsx(ke,{title:e("settings.mermaidTab.flowchartRankSpacingTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:20,max:200,step:10,style:{width:"100%"}})})}),r.jsx(Oe,{span:8,children:r.jsx(Z.Item,{name:"flowchartCurve",label:r.jsxs(X,{children:[e("settings.mermaidTab.flowchartCurveTypeLabel"),r.jsx(ke,{title:e("settings.mermaidTab.flowchartCurveTypeTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsxs(Pe,{children:[r.jsx(Pe.Option,{value:"basis",children:e("settings.mermaidTab.flowchartCurveOptions.basis")}),r.jsx(Pe.Option,{value:"linear",children:e("settings.mermaidTab.flowchartCurveOptions.linear")}),r.jsx(Pe.Option,{value:"cardinal",children:e("settings.mermaidTab.flowchartCurveOptions.cardinal")})]})})})]})}),r.jsx(ee,{title:e("settings.mermaidTab.sequenceCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsxs(Gt,{gutter:16,children:[r.jsx(Oe,{span:6,children:r.jsx(Z.Item,{name:"sequenceActorMargin",label:r.jsxs(X,{children:[e("settings.mermaidTab.sequenceActorMarginLabel"),r.jsx(ke,{title:e("settings.mermaidTab.sequenceActorMarginTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:20,max:200,step:10,style:{width:"100%"}})})}),r.jsx(Oe,{span:6,children:r.jsx(Z.Item,{name:"sequenceMessageMargin",label:r.jsxs(X,{children:[e("settings.mermaidTab.sequenceMessageMarginLabel"),r.jsx(ke,{title:e("settings.mermaidTab.sequenceMessageMarginTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:10,max:100,step:5,style:{width:"100%"}})})}),r.jsx(Oe,{span:6,children:r.jsx(Z.Item,{name:"sequenceWidth",label:r.jsxs(X,{children:[e("settings.mermaidTab.sequenceActorWidthLabel"),r.jsx(ke,{title:e("settings.mermaidTab.sequenceActorWidthTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:100,max:300,step:10,style:{width:"100%"}})})}),r.jsx(Oe,{span:6,children:r.jsx(Z.Item,{name:"sequenceHeight",label:r.jsxs(X,{children:[e("settings.mermaidTab.sequenceActorHeightLabel"),r.jsx(ke,{title:e("settings.mermaidTab.sequenceActorHeightTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:40,max:150,step:5,style:{width:"100%"}})})})]})}),r.jsx(ee,{title:e("settings.mermaidTab.ganttCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsxs(Gt,{gutter:16,children:[r.jsx(Oe,{span:12,children:r.jsx(Z.Item,{name:"ganttBarHeight",label:r.jsxs(X,{children:[e("settings.mermaidTab.ganttBarHeightLabel"),r.jsx(ke,{title:e("settings.mermaidTab.ganttBarHeightTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:10,max:50,step:5,style:{width:"100%"},addonAfter:"px"})})}),r.jsx(Oe,{span:12,children:r.jsx(Z.Item,{name:"ganttTopPadding",label:r.jsxs(X,{children:[e("settings.mermaidTab.ganttTopPaddingLabel"),r.jsx(ke,{title:e("settings.mermaidTab.ganttTopPaddingTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:20,max:100,step:10,style:{width:"100%"}})})})]})}),r.jsx(X,{children:r.jsx(Y,{icon:r.jsx(dx,{}),onClick:l,children:e("settings.mermaidTab.resetToDefaults")})}),r.jsx(Rt,{}),r.jsx(ee,{title:e("settings.mermaidTab.previewTitle"),styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsx(vl,{type:"secondary",children:e("settings.mermaidTab.previewDescription")})})]})]})},z_=m.lazy(()=>Dt(()=>import("./index-gw2m3pxJ.js"),__vite__mapDeps([0,1,2,3,4,5,6,7]),import.meta.url)),{Text:bn}=le,{useToken:N_}=he,B_=({promptEnhancement:e,onPromptEnhancementChange:t,mermaidEnhancementEnabled:s,taskEnhancementEnabled:n,showCopilotConclusionWithOptionsEnhancement:o,copilotConclusionWithOptionsEnhancementEnabled:a,onMermaidToggle:i,onTaskToggle:l,onCopilotConclusionWithOptionsToggle:c,onSaveEnhancement:d})=>{const{t:u}=ne(),{token:h}=N_(),p=h.marginLG;return r.jsxs(G,{vertical:!0,gap:p,children:[r.jsx(ee,{size:"small",className:"lotus-settings-card",children:r.jsx(m.Suspense,{fallback:r.jsx(ps,{size:"small"}),children:r.jsx(z_,{})})}),r.jsx(ee,{size:"small",className:"lotus-settings-card",children:r.jsxs(X,{direction:"vertical",size:h.marginXS,style:{width:"100%"},children:[r.jsx(bn,{strong:!0,children:u("settings.promptsTab.title")}),r.jsxs(G,{align:"center",gap:h.marginSM,children:[r.jsx(bn,{strong:!0,children:u("settings.promptsTab.mermaidEnhancement")}),r.jsx(it,{checked:s,onChange:i})]}),r.jsxs(G,{align:"center",gap:h.marginSM,children:[r.jsx(bn,{strong:!0,children:u("settings.promptsTab.taskListRules")}),r.jsx(it,{checked:n,onChange:l})]}),o&&r.jsxs(X,{direction:"vertical",size:h.marginXXS,style:{width:"100%"},children:[r.jsxs(G,{align:"center",gap:h.marginSM,children:[r.jsx(bn,{strong:!0,children:u("settings.promptsTab.copilotConclusionWithOptionsBeforeFinish")}),r.jsx(it,{checked:a,onChange:c})]}),r.jsx(bn,{type:"secondary",style:{fontSize:h.fontSizeSM},children:u("settings.promptsTab.copilotConclusionWithOptionsBeforeFinishDescription",{defaultValue:y_()})})]}),r.jsx(me.TextArea,{rows:6,placeholder:u("settings.promptsTab.enhancementPlaceholder"),value:e,onChange:g=>t(g.target.value)}),r.jsx(G,{justify:"flex-end",children:r.jsx(Y,{type:"primary",onClick:d,children:u("settings.promptsTab.saveEnhancement")})}),r.jsx(bn,{type:"secondary",style:{fontSize:h.fontSizeSM},children:u("settings.promptsTab.description")})]})}),s&&r.jsx(ns,{size:"small",items:[{key:"mermaid",label:r.jsx(bn,{strong:!0,children:u("settings.mermaidTab.title")}),children:r.jsx(F_,{})}]})]})},Yd="bodhi_onboarding_complete",W_=()=>localStorage.getItem(Yd)==="true",U_=()=>localStorage.setItem(Yd,"true"),q_=()=>localStorage.removeItem(Yd),H_=["new-session","task-templates","model-picker","sidebar","open-settings"],Y_=()=>{const e={};for(const t of H_)e[t]=document.querySelector(`[data-tour-id="${t}"]`);return e},X_=({disabled:e=!1})=>{const{t}=ne(),[s,n]=m.useState(!1),[o,a]=m.useState(null);m.useEffect(()=>{if(e||W_())return;const c=setTimeout(()=>{const d=Y_();a(d),n(!0)},800);return()=>clearTimeout(c)},[e]);const i=m.useMemo(()=>[{title:t("onboarding.welcome.title"),description:t("onboarding.welcome.description"),target:null},{title:t("onboarding.newSession.title"),description:t("onboarding.newSession.description"),target:(o==null?void 0:o["new-session"])??void 0},{title:t("onboarding.taskTemplates.title"),description:t("onboarding.taskTemplates.description"),target:(o==null?void 0:o["task-templates"])??void 0},{title:t("onboarding.modelPicker.title"),description:t("onboarding.modelPicker.description"),target:(o==null?void 0:o["model-picker"])??void 0},{title:t("onboarding.sidebar.title"),description:t("onboarding.sidebar.description"),target:(o==null?void 0:o.sidebar)??void 0},{title:t("onboarding.settings.title"),description:t("onboarding.settings.description"),target:(o==null?void 0:o["open-settings"])??void 0}],[t,o]),l=()=>{U_(),n(!1)};return r.jsx(ux,{open:s,onClose:l,steps:i})},{Text:vs}=le,{useToken:V_}=he,K_=({autoGenerateTitles:e,isUpdatingAutoTitlePreference:t,onAutoTitleToggle:s,themeMode:n,onThemeModeChange:o,vdiSafeMode:a,onVdiSafeModeToggle:i,onClearLocalStorage:l,onResetApp:c,isResetting:d,darkModeKey:u})=>{const{t:h}=ne(),{token:p}=V_();return r.jsx(ee,{size:"small",className:"lotus-settings-card",children:r.jsxs(X,{direction:"vertical",size:p.marginSM,style:{width:"100%"},children:[r.jsxs(G,{align:"center",gap:p.marginSM,children:[r.jsx(vs,{strong:!0,children:h("settings.appTab.autoGenerateTitle")}),r.jsx(it,{checked:e,loading:t,onChange:s})]}),r.jsx(vs,{type:"secondary",style:{fontSize:p.fontSizeSM},children:h("settings.appTab.autoGenerateTitleDesc")}),r.jsxs(G,{align:"center",justify:"space-between",gap:p.marginSM,children:[r.jsx(vs,{strong:!0,children:h("settings.appTab.runningVersion","Running version")}),r.jsxs(vs,{code:!0,"data-testid":"settings-app-version",children:["v",xd]})]}),r.jsx(vs,{type:"secondary",style:{fontSize:p.fontSizeSM},children:h("settings.appTab.runningVersionDesc","This is the currently running Lotus frontend version.")}),r.jsxs(G,{align:"center",gap:p.marginSM,children:[r.jsx(vs,{strong:!0,children:h("settings.appTab.darkMode")}),r.jsx(it,{"data-testid":"dark-mode-toggle",checked:n==="dark",onChange:g=>{const y=g?"dark":"light";o(y),localStorage.setItem(u,y)}})]}),r.jsxs(G,{align:"center",gap:p.marginSM,children:[r.jsx(vs,{strong:!0,children:h("settings.appTab.vdiSafeMode","Graphics compatibility mode")}),r.jsx(it,{"data-testid":"vdi-safe-mode-toggle",checked:a,onChange:i})]}),r.jsx(vs,{type:"secondary",style:{fontSize:p.fontSizeSM},children:h("settings.appTab.vdiSafeModeDesc","Disables blur and glass effects that can break dropdowns and hover overlays in some virtual desktop, remote, or graphics-constrained environments.")}),r.jsx(Y,{block:!0,icon:r.jsx(nd,{}),onClick:()=>{q_(),window.location.reload()},children:h("settings.appTab.resetStepReplayGuide")}),r.jsx(mi,{title:h("settings.appTab.clearLocalStorageTitle"),description:h("settings.appTab.clearLocalStorageDescription"),onConfirm:l,okText:h("settings.appTab.confirmClear"),cancelText:h("settings.appTab.cancel"),placement:"top",children:r.jsx(Y,{danger:!0,block:!0,icon:r.jsx(dn,{}),children:h("settings.appTab.clearLocalStorageButton")})}),r.jsx(Rt,{style:{margin:`${p.marginSM}px 0`}}),r.jsxs(G,{align:"center",gap:p.marginSM,children:[r.jsx(ua,{style:{color:p.colorError}}),r.jsx(vs,{strong:!0,style:{color:p.colorError},children:h("settings.appTab.dangerZone")})]}),r.jsx(vs,{type:"secondary",style:{fontSize:p.fontSizeSM},children:h("settings.appTab.dangerDescription")}),r.jsx(mi,{title:h("settings.appTab.resetApplicationTitle"),description:r.jsxs("div",{children:[r.jsx("p",{children:h("settings.appTab.resetApplicationIntro")}),r.jsxs("ul",{style:{margin:0,paddingLeft:16},children:[r.jsx("li",{children:h("settings.appTab.resetStepDeleteAllSessions")}),r.jsx("li",{children:h("settings.appTab.resetStepClearStorage")}),r.jsx("li",{children:h("settings.appTab.resetStepResetConfig")}),r.jsx("li",{children:h("settings.appTab.resetStepSetupFlow")}),r.jsx("li",{children:h("settings.appTab.resetStepReload")})]})]}),onConfirm:c,okText:h("settings.appTab.resetConfirm"),cancelText:h("settings.appTab.cancel"),placement:"top",okButtonProps:{danger:!0},children:r.jsx(Y,{"data-testid":"reset-to-defaults",danger:!0,block:!0,type:"primary",icon:r.jsx(yf,{}),loading:d,children:h("settings.appTab.resetButton")})})]})})},{Text:xn}=le,{useToken:G_}=he,xm=[{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,}"}],J_=(e,t,s)=>{if(!t)return{masked:e};if(s==="exact")return{masked:e.split(t).join("[MASKED]")};try{const n=new RegExp(t,"g");return{masked:e.replace(n,"[MASKED]")}}catch(n){return{masked:e,error:n instanceof Error?n.message:es.t("settings.keywordMaskingTab.invalidRegexPattern")}}},Q_=()=>{const{t:e}=ne(),{token:t}=G_(),[s,n]=m.useState([]),[o,a]=m.useState(!1),[i,l]=m.useState(null),[c,d]=m.useState(""),[u,h]=m.useState("exact"),[p,g]=m.useState(!0),[y,f]=m.useState(),[v,b]=m.useState("My token is sk-123"),x=m.useCallback(async()=>{try{a(!0);const P=await fs.getInstance().getKeywordMaskingConfig();n(P.entries)}catch(T){fe.error(e("settings.keywordMaskingTab.loadFailed")),console.error(T)}finally{a(!1)}},[e]);m.useEffect(()=>{x()},[x]);const _=async T=>{try{const P=fs.getInstance(),S=await P.validateKeywordEntries(T);if(!S.valid&&S.errors){const $=S.errors.map(I=>`Entry ${I.index+1}: ${I.message}`).join("; ");return fe.error(`${e("settings.keywordMaskingTab.validationFailedPrefix")}: ${$}`),!1}const L=await P.updateKeywordMaskingConfig(T);return n(L.entries),fe.success(e("settings.keywordMaskingTab.saveSuccess")),!0}catch(P){return fe.error(P instanceof Error?P.message:e("settings.keywordMaskingTab.saveFailed")),!1}},w=async()=>{const T={pattern:"",match_type:"exact",enabled:!0},P=[...s,T];n(P),l(P.length-1),d(""),h("exact"),g(!0),f(void 0)},k=T=>{const P=s[T];l(T),d(P.pattern),h(P.match_type),g(P.enabled),f(void 0)},C=async()=>{if(i===null)return;if(!c.trim()){fe.error(e("settings.keywordMaskingTab.patternRequired"));return}const T=[...s];T[i]={pattern:c.trim(),match_type:u,enabled:p},await _(T)&&l(null)},E=()=>{var T;i!==null&&!((T=s[i])!=null&&T.pattern)&&n(s.filter((P,S)=>S!==i)),l(null)},j=async T=>{const P=s.filter((S,L)=>L!==T);await _(P)},R=async(T,P)=>{const S=[...s];S[T]={...S[T],enabled:P},await _(S)},M=J_(v,c,u);return r.jsx(ee,{className:"lotus-settings-card",title:e("settings.keywordMaskingTab.title"),extra:r.jsx(Y,{"data-testid":"add-keyword",type:"primary",icon:r.jsx(Us,{}),onClick:w,loading:o,children:e("settings.keywordMaskingTab.addKeyword")}),children:r.jsxs(X,{direction:"vertical",style:{width:"100%"},size:"large",children:[r.jsx(xn,{type:"secondary",children:e("settings.keywordMaskingTab.description")}),r.jsx(nt,{loading:o,dataSource:s,locale:{emptyText:e("settings.keywordMaskingTab.empty")},renderItem:(T,P)=>r.jsx(nt.Item,{style:{backgroundColor:t.colorFillAlter,marginBottom:8,borderRadius:t.borderRadius,padding:12},actions:i===P?[r.jsx(Y,{"data-testid":"save-keyword",type:"primary",icon:r.jsx(Di,{}),onClick:C,"aria-label":e("settings.keywordMaskingTab.save")},"save"),r.jsx(Y,{onClick:E,children:e("settings.keywordMaskingTab.cancel")},"cancel")]:[r.jsx(Y,{icon:r.jsx(ca,{}),onClick:()=>k(P),"aria-label":e("settings.keywordMaskingTab.edit")},"edit"),r.jsx(Y,{"data-testid":`delete-keyword-${P}`,danger:!0,icon:r.jsx(dn,{}),onClick:()=>j(P),"aria-label":e("settings.keywordMaskingTab.delete")},"delete")],children:r.jsx(G,{vertical:!0,style:{width:"100%"},gap:8,children:i===P?r.jsxs(r.Fragment,{children:[r.jsx(me,{"data-testid":"keyword-pattern-input",placeholder:e("settings.keywordMaskingTab.patternPlaceholder"),value:c,onChange:S=>d(S.target.value),autoFocus:!0}),r.jsxs(G,{gap:8,align:"center",wrap:"wrap",children:[r.jsx(Pe,{"data-testid":"keyword-examples-select","aria-label":e("settings.keywordMaskingTab.examples"),placeholder:e("settings.keywordMaskingTab.examples"),value:y,onChange:S=>{f(S);const L=xm.find($=>$.value===S);L&&(d(L.pattern),h(L.match_type))},options:xm.map(S=>({value:S.value,label:e(S.labelKey)})),style:{minWidth:220}}),r.jsx(Pe,{value:u,onChange:h,options:[{value:"exact",label:e("settings.keywordMaskingTab.exactMatch")},{value:"regex",label:e("settings.keywordMaskingTab.regexPattern")}],style:{width:150}}),r.jsx(it,{checked:p,onChange:g})]}),r.jsxs(G,{vertical:!0,gap:6,children:[r.jsx(xn,{type:"secondary",children:e("settings.keywordMaskingTab.sampleText")}),r.jsx(me,{placeholder:e("settings.keywordMaskingTab.sampleTextPlaceholder"),value:v,onChange:S=>b(S.target.value)}),r.jsx(xn,{type:"secondary",children:e("settings.keywordMaskingTab.maskedPreview")}),r.jsx(me,{readOnly:!0,value:M.masked,status:M.error?"error":void 0}),M.error&&r.jsx(xn,{type:"danger",children:M.error})]})]}):r.jsxs(G,{justify:"space-between",align:"center",children:[r.jsxs(G,{vertical:!0,gap:4,children:[r.jsx(xn,{strong:!0,children:T.pattern||e("settings.keywordMaskingTab.emptyPattern")}),r.jsxs(G,{gap:8,children:[r.jsx(xn,{type:"secondary",style:{fontSize:12},children:T.match_type==="regex"?e("settings.keywordMaskingTab.regexPattern"):e("settings.keywordMaskingTab.exactMatch")}),!T.enabled&&r.jsx(xn,{type:"warning",style:{fontSize:12},children:e("settings.keywordMaskingTab.disabled")})]})]}),r.jsx(it,{checked:T.enabled,onChange:S=>R(P,S),size:"small"})]})})})})]})})},{Text:tr,Paragraph:Z_}=le,e0=/^[A-Za-z_][A-Za-z0-9_]*$/,t0=()=>{const{t:e}=ne(),[t,s]=m.useState([]),[n,o]=m.useState(!1),[a,i]=m.useState(!1),[l,c]=m.useState(null),[d]=Z.useForm(),u=m.useCallback(async()=>{o(!0);try{const b=await It.getEnvVars();s(b.entries)}catch{fe.error(e("settings.envVars.fetchError","Failed to load environment variables"))}finally{o(!1)}},[e]);m.useEffect(()=>{u()},[u]);const h=async b=>{var _;const x={name:b.name.trim(),value:b.value,secret:b.secret??!1,description:((_=b.description)==null?void 0:_.trim())||void 0};try{const w=await It.upsertEnvVar(x);s(w.entries),fe.success(l?e("settings.envVars.updated","Variable updated"):e("settings.envVars.created","Variable created")),f()}catch(w){fe.error((w instanceof Error?w.message:void 0)||e("settings.envVars.saveError","Failed to save variable"))}},p=async b=>{try{const x=await It.deleteEnvVar(b);s(x.entries),fe.success(e("settings.envVars.deleted","Variable deleted"))}catch(x){fe.error((x instanceof Error?x.message:void 0)||e("settings.envVars.deleteError","Failed to delete variable"))}},g=()=>{c(null),d.resetFields(),d.setFieldsValue({secret:!1}),i(!0)},y=b=>{c(b.name),d.setFieldsValue({name:b.name,value:"",secret:b.secret,description:b.description??""}),i(!0)},f=()=>{i(!1),c(null),d.resetFields()},v=[{title:e("settings.envVars.name","Name"),dataIndex:"name",key:"name",render:b=>r.jsx(tr,{code:!0,children:b})},{title:e("settings.envVars.value","Value"),dataIndex:"value",key:"value",render:(b,x)=>x.secret?r.jsxs(tr,{type:"secondary",children:[r.jsx(lu,{style:{marginRight:4}}),x.has_value?"••••••••":e("settings.envVars.notSet","(not set)")]}):r.jsx(tr,{children:b||r.jsx(tr,{type:"secondary",children:e("settings.envVars.empty","(empty)")})})},{title:e("settings.envVars.type","Type"),key:"secret",width:100,render:(b,x)=>x.secret?r.jsx(oe,{color:"warning",icon:r.jsx(lu,{}),children:e("settings.envVars.secret","Secret")}):r.jsx(oe,{color:"processing",children:e("settings.envVars.plain","Plain")})},{title:e("settings.envVars.descriptionCol","Description"),dataIndex:"description",key:"description",ellipsis:!0,render:b=>b?r.jsx(tr,{type:"secondary",children:b}):r.jsx(tr,{type:"secondary",italic:!0,children:"—"})},{title:e("settings.envVars.actions","Actions"),key:"actions",width:120,render:(b,x)=>r.jsxs(X,{size:"small",children:[r.jsx(Y,{type:"text",size:"small",icon:r.jsx(ca,{}),onClick:()=>y(x),"aria-label":e("settings.envVars.edit","Edit")}),r.jsx(mi,{title:e("settings.envVars.deleteConfirm","Delete this variable?"),onConfirm:()=>p(x.name),okText:e("settings.envVars.yes","Yes"),cancelText:e("settings.envVars.no","No"),children:r.jsx(Y,{type:"text",size:"small",danger:!0,icon:r.jsx(dn,{}),"aria-label":e("settings.envVars.delete","Delete")})})]})}];return r.jsxs("div",{style:{maxWidth:900},children:[r.jsxs(ee,{className:"lotus-settings-card",title:e("settings.envVars.title","Environment Variables"),extra:r.jsx(Y,{type:"primary",icon:r.jsx(Us,{}),onClick:g,children:e("settings.envVars.addButton","Add Variable")}),children:[r.jsx(Z_,{type:"secondary",style:{marginBottom:16},children:e("settings.envVars.description","Variables are injected into Bash tool processes. Secret variables are encrypted at rest.")}),r.jsx(qs,{dataSource:t,columns:v,rowKey:"name",size:"small",pagination:!1,loading:n,locale:{emptyText:e("settings.envVars.noVars","No environment variables configured")}})]}),r.jsx(Lt,{title:l?e("settings.envVars.editTitle","Edit Variable"):e("settings.envVars.addTitle","Add Environment Variable"),open:a,onCancel:f,onOk:()=>d.submit(),okText:e("settings.envVars.save","Save"),cancelText:e("settings.envVars.cancel","Cancel"),destroyOnClose:!0,children:r.jsxs(Z,{form:d,layout:"vertical",onFinish:h,initialValues:{secret:!1},children:[r.jsx(Z.Item,{name:"name",label:e("settings.envVars.name","Name"),rules:[{required:!0,message:e("settings.envVars.nameRequired","Variable name is required")},{pattern:e0,message:e("settings.envVars.nameInvalid","Must start with a letter or underscore, followed by letters, digits, or underscores")}],children:r.jsx(me,{placeholder:"GITHUB_TOKEN",disabled:l!==null,autoFocus:l===null})}),r.jsx(Z.Item,{name:"value",label:e("settings.envVars.value","Value"),rules:[{required:l===null,message:e("settings.envVars.valueRequired","Value is required for new variables")}],extra:l?e("settings.envVars.valueEditHint","Leave empty to keep the existing value"):void 0,children:r.jsx(me.Password,{placeholder:l?e("settings.envVars.valuePlaceholderEdit","Enter new value or leave empty"):e("settings.envVars.valuePlaceholder","Enter value"),visibilityToggle:!0})}),r.jsx(Z.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:r.jsx(it,{})}),r.jsx(Z.Item,{name:"description",label:e("settings.envVars.descriptionField","Description"),children:r.jsx(me,{placeholder:e("settings.envVars.descriptionPlaceholder","Optional description")})})]})})]})},An=class An{constructor(){}static getInstance(){return An.instance||(An.instance=new An),An.instance}async listWorkflows(){try{st("[WorkflowManager]","[WorkflowManagerService] Listing workflows");const t=await xe.get("bamboo/workflows"),s=Array.isArray(t)?t:[];return st("[WorkflowManager]","[WorkflowManagerService] Listed workflows:",s),s.map(n=>({name:String(n.name||""),filename:String(n.filename||(n.name||"workflow")+".md"),size:Number(n.size||0),modified_at:typeof n.modified_at=="string"?n.modified_at:void 0,source:"global"}))}catch(t){throw console.error("[WorkflowManagerService] Failed to list workflows:",t),t}}async getWorkflow(t){try{st("[WorkflowManager]","[WorkflowManagerService] Getting workflow: "+t);const s=await xe.get("bamboo/workflows/"+encodeURIComponent(t)),n=s!=null&&s.name?String(s.name):t,o={name:n,filename:String((s==null?void 0:s.filename)||n+".md"),size:Number((s==null?void 0:s.size)||0),modified_at:s==null?void 0:s.modified_at,source:"global"};return st("[WorkflowManager]","[WorkflowManagerService] Got workflow:",s),{name:n,content:String((s==null?void 0:s.content)||""),metadata:o}}catch(s){throw console.error("[WorkflowManagerService] Failed to get workflow "+t+":",s),kv(s)&&s.status===404?new Error("Workflow '"+t+"' not found"):s instanceof Error&&s.message.includes("404")?new Error("Workflow '"+t+"' not found"):s}}};He(An,"instance");let Ac=An;const{Text:Sl}=le,{TextArea:s0}=me,{useToken:n0}=he,r0=e=>!(!e||e.includes("/")||e.includes("\\")||e.includes("..")),o0=()=>{const{t:e}=ne(),{token:t}=n0(),[s,n]=fe.useMessage(),[o,a]=m.useState([]),[i,l]=m.useState(!1),[c,d]=m.useState(!1),[u,h]=m.useState(!1),[p,g]=m.useState(null),[y,f]=m.useState(""),[v,b]=m.useState(""),[x,_]=m.useState(!1),w=m.useMemo(()=>Ac.getInstance(),[]),k=m.useCallback(async()=>{l(!0);try{const M=await w.listWorkflows();return a(M),M}catch{return s.error(e("settings.workflowsTab.loadFailed")),[]}finally{l(!1)}},[s,e,w]);m.useEffect(()=>{k()},[k]);const C=m.useCallback(async M=>{g(M),f(M.name),_(!1),d(!0);try{const T=await w.getWorkflow(M.name);b(T.content??"")}catch{s.error(e("settings.workflowsTab.loadContentFailed")),b("")}finally{d(!1)}},[s,e,w]),E=()=>{g(null),f(""),b(""),_(!1)},j=m.useCallback(async()=>{if(!r0(y)){s.error(e("settings.workflowsTab.invalidName"));return}const M=o.some(T=>T.name===y);if(!p&&M){s.error(e("settings.workflowsTab.nameAlreadyExists"));return}h(!0);try{await fs.getInstance().saveWorkflow(y,v),s.success(e("settings.workflowsTab.saved")),_(!1);const S=(await k()).find(L=>L.name===y);S&&g(S)}catch(T){s.error(T instanceof Error?T.message:e("settings.workflowsTab.saveFailed"))}finally{h(!1)}},[v,y,k,s,p,e,o]),R=m.useCallback(async M=>{try{await fs.getInstance().deleteWorkflow(M.name),s.success(e("settings.workflowsTab.deleted")),(p==null?void 0:p.name)===M.name&&E(),await k()}catch(T){s.error(T instanceof Error?T.message:e("settings.workflowsTab.deleteFailed"))}},[k,s,p,e]);return r.jsxs("div",{style:{padding:"24px"},children:[n,r.jsxs(ee,{title:e("settings.workflowsTab.title"),extra:r.jsxs(X,{children:[r.jsx(Y,{icon:r.jsx(Ms,{}),onClick:k,loading:i,children:e("settings.workflowsTab.refresh")}),r.jsx(Y,{"data-testid":"create-workflow",icon:r.jsx(Us,{}),onClick:E,children:e("settings.workflowsTab.newWorkflow")}),r.jsx(Y,{"data-testid":"save-workflow",type:"primary",icon:r.jsx(Di,{}),onClick:j,loading:u,disabled:!x,children:e("settings.workflowsTab.save")})]}),children:[r.jsx(Sl,{type:"secondary",children:e("settings.workflowsTab.description")}),r.jsxs(G,{gap:t.marginLG,style:{marginTop:t.marginLG},children:[r.jsx("div",{style:{width:320,flexShrink:0},children:r.jsx(nt,{loading:i,dataSource:o,locale:{emptyText:e("settings.workflowsTab.empty")},renderItem:M=>r.jsx(nt.Item,{style:{cursor:"pointer",backgroundColor:(p==null?void 0:p.name)===M.name?t.colorFillSecondary:"transparent",borderRadius:t.borderRadius,padding:t.paddingSM},onClick:()=>C(M),actions:[r.jsx(Y,{"data-testid":`delete-workflow-${M.name}`,type:"text",danger:!0,size:"small",icon:r.jsx(dn,{}),onClick:T=>{T.stopPropagation(),R(M)},"aria-label":e("settings.workflowsTab.delete")},"delete")],children:r.jsxs(X,{direction:"vertical",size:0,children:[r.jsxs(Sl,{strong:!0,children:["/",M.name]}),r.jsx(Sl,{type:"secondary",style:{fontSize:12},children:M.filename})]})})})}),r.jsx("div",{style:{flex:1},children:r.jsxs(X,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx(me,{"data-testid":"workflow-name",placeholder:e("settings.workflowsTab.namePlaceholder"),value:y,onChange:M=>{f(M.target.value),_(!0)},disabled:!!p,prefix:r.jsx(ca,{})}),r.jsx(s0,{"data-testid":"workflow-content",placeholder:e("settings.workflowsTab.contentPlaceholder"),value:v,onChange:M=>{b(M.target.value),_(!0)},autoSize:{minRows:12},disabled:c})]})})]})]})]})};var ue=(e=>(e.Connecting="connecting",e.Ready="ready",e.Degraded="degraded",e.Stopped="stopped",e.Error="error",e))(ue||{});const va=6e4,Sa=3e4,aa=2e4,Ci=1e4,Vi=e=>({id:e,enabled:!0,transport:{type:"stdio",command:"",args:[],env:{},startup_timeout_ms:aa},request_timeout_ms:va,healthcheck_interval_ms:Sa,allowed_tools:[],denied_tools:[]}),a0=()=>({status:"stopped",tool_count:0,restart_count:0}),i0=e=>{switch(typeof e=="string"?e.trim().toLowerCase():""){case ue.Connecting:return ue.Connecting;case ue.Ready:return ue.Ready;case ue.Degraded:return ue.Degraded;case ue.Error:return ue.Error;case ue.Stopped:default:return ue.Stopped}},Ns=(e,t)=>{if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Number(e);if(Number.isFinite(s))return s}return t},l0=(e,t)=>{if(!e||typeof e!="object")return t;const s=e;if(s.type==="sse"){const a=Array.isArray(s.headers)?s.headers.map(i=>{if(!i||typeof i!="object")return null;const l=i;return typeof l.name!="string"||typeof l.value!="string"?null:{name:l.name,value:l.value}}).filter(i=>!!i):[];return{type:"sse",url:typeof s.url=="string"?s.url:"",headers:a,connect_timeout_ms:Ns(s.connect_timeout_ms,Ci)}}const n=Array.isArray(s.args)?s.args.filter(a=>typeof a=="string"):[],o=s.env&&typeof s.env=="object"?Object.entries(s.env):[];return{type:"stdio",command:typeof s.command=="string"?s.command:"",args:n,cwd:typeof s.cwd=="string"?s.cwd:void 0,env:o.reduce((a,[i,l])=>(typeof l=="string"&&(a[i]=l),a),{}),startup_timeout_ms:Ns(s.startup_timeout_ms,aa)}},c0=(e,t)=>{const s=Vi(e.id),n=t??{};return{...s,...n,id:e.id,name:typeof n.name=="string"?n.name:typeof e.name=="string"?e.name:void 0,enabled:typeof e.enabled=="boolean"?e.enabled:typeof n.enabled=="boolean"?n.enabled:!0,request_timeout_ms:Ns(n.request_timeout_ms,va),healthcheck_interval_ms:Ns(n.healthcheck_interval_ms,Sa),allowed_tools:Array.isArray(n.allowed_tools)?n.allowed_tools.filter(a=>typeof a=="string"):[],denied_tools:Array.isArray(n.denied_tools)?n.denied_tools.filter(a=>typeof a=="string"):[],reconnect:n.reconnect&&typeof n.reconnect=="object"?{enabled:typeof n.reconnect.enabled=="boolean"?n.reconnect.enabled:!0,initial_backoff_ms:Ns(n.reconnect.initial_backoff_ms,1e3),max_backoff_ms:Ns(n.reconnect.max_backoff_ms,3e4),max_attempts:Ns(n.reconnect.max_attempts,0)}:void 0,transport:l0(n.transport,s.transport)}},d0=e=>{const t=a0(),n=e.runtime??{},o=n.status??e.status;return{status:i0(o),last_error:typeof n.last_error=="string"?n.last_error:typeof e.last_error=="string"?e.last_error:void 0,connected_at:typeof n.connected_at=="string"?n.connected_at:void 0,disconnected_at:typeof n.disconnected_at=="string"?n.disconnected_at:void 0,tool_count:Ns(n.tool_count??e.tool_count,t.tool_count),restart_count:Ns(n.restart_count??e.restart_count,t.restart_count),last_ping_at:typeof n.last_ping_at=="string"?n.last_ping_at:void 0}},u0=e=>{const t=c0(e,e.config);return{id:e.id,name:typeof e.name=="string"?e.name:typeof t.name=="string"?t.name:e.id,enabled:typeof e.enabled=="boolean"?e.enabled:t.enabled,config:t,runtime:d0(e)}},m0=(e,t)=>`mcp__${e}__${t}`,h0=e=>{if(!e.startsWith("mcp__"))return null;const t=e.slice(5),s=t.indexOf("__");if(s<=0)return null;const n=t.slice(0,s),o=t.slice(s+2);return!n||!o?null:{server_id:n,original_name:o}},p0=(e,t,s=0)=>{if(!e||typeof e!="object")return null;const n=e,o=typeof n.alias=="string"?n.alias:typeof n.name=="string"&&n.name.startsWith("mcp__")?n.name:void 0,a=o&&typeof o=="string"?h0(o):null,i=(typeof n.server_id=="string"?n.server_id:void 0)??(typeof n.serverId=="string"?n.serverId:void 0)??(a==null?void 0:a.server_id)??t??"",l=(typeof n.original_name=="string"?n.original_name:void 0)??(typeof n.originalName=="string"?n.originalName:void 0)??(a==null?void 0:a.original_name)??(typeof n.name=="string"?n.name:void 0)??"",c=o??(i&&l?m0(i,l):""),d=typeof n.description=="string"?n.description:"",u=n,h="parameters"in u?u.parameters:"inputSchema"in u?u.inputSchema:"input_schema"in u?u.input_schema:void 0,p=c||l||`mcp_tool_${s}`;return{alias:p,server_id:i||"unknown",original_name:l||p,description:d,parameters:h}};class f0{async getServers(){const t=await pe.get("mcp/servers");return Array.isArray(t.servers)?t.servers.map(u0):[]}async addServer(t){return pe.post("mcp/servers",t)}async updateServer(t,s){const n={...s,id:t};return pe.put(`mcp/servers/${t}`,n)}async deleteServer(t){return pe.delete(`mcp/servers/${t}`)}async connectServer(t){return pe.post(`mcp/servers/${t}/connect`)}async disconnectServer(t){return pe.post(`mcp/servers/${t}/disconnect`)}async refreshTools(t){return pe.post(`mcp/servers/${t}/refresh`)}async getTools(t){const s=t?`mcp/servers/${t}/tools`:"mcp/tools",n=await pe.get(s);return(Array.isArray(n.tools)?n.tools:[]).map((a,i)=>p0(a,t,i)).filter(a=>!!a)}async importServers(t){return pe.post("mcp/servers/import",t)}}const Py=new f0,g0=5e3,Ls=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,vm=(e,t)=>`${e}:${t}`,y0=(e={})=>{const{service:t=Py,autoRefreshMs:s=g0,autoRefreshEnabled:n=!0}=e,[o,a]=m.useState([]),[i,l]=m.useState(null),[c,d]=m.useState({}),[u,h]=m.useState({}),[p,g]=m.useState({}),[y,f]=m.useState(!1),[v,b]=m.useState(!1),[x,_]=m.useState(!1),[w,k]=m.useState(null),C=m.useRef({}),E=m.useCallback(B=>{const K=new Set(B.map(z=>z.id)),F=B.map(z=>{const Te=C.current[z.id]??z.config,$e={...Te,id:z.id,name:Te.name??z.name};return C.current[z.id]=$e,{...z,name:z.name||$e.name||z.id,enabled:z.enabled??$e.enabled,config:$e}});return Object.keys(C.current).forEach(z=>{K.has(z)||delete C.current[z]}),F},[]),j=m.useCallback(async({silent:B=!1}={})=>{B||f(!0);try{const K=await t.getServers(),F=E(K);a(F),l(z=>{var de;return z&&F.some(Te=>Te.id===z)?z:((de=F[0])==null?void 0:de.id)??null}),k(null)}catch(K){throw k(Ls(K,"Failed to load MCP servers")),K}finally{B||f(!1)}},[E,t]),R=m.useCallback(async(B,K=!1)=>{if(!B)return[];if(!K&&c[B])return c[B];h(F=>({...F,[B]:!0}));try{const F=await t.getTools(B);return d(z=>({...z,[B]:F})),k(null),F}catch(F){throw k(Ls(F,"Failed to load MCP tools")),F}finally{h(F=>({...F,[B]:!1}))}},[t,c]),M=m.useCallback((B,K,F)=>{const z=vm(B,K);g(de=>({...de,[z]:F}))},[]),T=m.useCallback(async B=>{b(!0);try{await t.addServer(B),C.current[B.id]=B,await j()}catch(K){throw k(Ls(K,"Failed to add MCP server")),K}finally{b(!1)}},[j,t]),P=m.useCallback(async(B,K)=>{b(!0);try{const F={...K,id:B};await t.updateServer(B,F),C.current[B]=F,await j()}catch(F){throw k(Ls(F,"Failed to update MCP server")),F}finally{b(!1)}},[j,t]),S=m.useCallback(async B=>{M(B,"delete",!0);try{await t.deleteServer(B),d(K=>{const F={...K};return delete F[B],F}),delete C.current[B],await j()}catch(K){throw k(Ls(K,"Failed to delete MCP server")),K}finally{M(B,"delete",!1)}},[j,t,M]),L=m.useCallback(async B=>{M(B,"connect",!0);try{await t.connectServer(B),await j({silent:!0})}catch(K){throw k(Ls(K,"Failed to connect MCP server")),K}finally{M(B,"connect",!1)}},[j,t,M]),$=m.useCallback(async B=>{M(B,"disconnect",!0);try{await t.disconnectServer(B),await j({silent:!0})}catch(K){throw k(Ls(K,"Failed to disconnect MCP server")),K}finally{M(B,"disconnect",!1)}},[j,t,M]),I=m.useCallback(async B=>{M(B,"refresh",!0);try{await t.refreshTools(B),await R(B,!0),await j({silent:!0})}catch(K){throw k(Ls(K,"Failed to refresh MCP tools")),K}finally{M(B,"refresh",!1)}},[R,j,t,M]),W=m.useCallback(async()=>{_(!0);try{const B=o.map(K=>K.id);await Promise.all(B.map(async K=>{try{await t.refreshTools(K)}catch{}})),await j(),i&&await R(i,!0)}catch(B){throw k(Ls(B,"Failed to refresh MCP status")),B}finally{_(!1)}},[R,j,i,o,t]),A=m.useCallback(B=>{l(B)},[]),O=m.useCallback((B,K)=>!!p[vm(B,K)],[p]),D=m.useMemo(()=>i?c[i]??[]:[],[i,c]),H=m.useMemo(()=>i?!!u[i]:!1,[i,u]);return m.useEffect(()=>{j().catch(()=>{})},[j]),m.useEffect(()=>{if(!n||s<=0)return;const B=window.setInterval(()=>{j({silent:!0}).catch(()=>{})},s);return()=>{window.clearInterval(B)}},[n,s,j]),m.useEffect(()=>{i&&R(i).catch(()=>{})},[R,i]),{servers:o,selectedServerId:i,selectedServerTools:D,isLoadingServers:y,isMutatingConfig:v,isRefreshingAll:x,isSelectedServerToolsLoading:H,error:w,setSelectedServerId:A,refreshServers:j,addServer:T,updateServer:P,deleteServer:S,connectServer:L,disconnectServer:$,refreshServerTools:I,refreshAll:W,isServerActionLoading:O}},b0={[ue.Connecting]:"blue",[ue.Ready]:"green",[ue.Degraded]:"orange",[ue.Stopped]:"default",[ue.Error]:"red"},x0=e=>e===ue.Connecting||e===ue.Ready||e===ue.Degraded,v0=e=>{if(!e)return;const t=e.replace(/\s+/g," ").trim();if(t)return t.length>180?`${t.slice(0,180)}...`:t},S0=({servers:e,loading:t=!1,selectedServerId:s,onSelectServer:n,onEditServer:o,onDeleteServer:a,onConnectServer:i,onDisconnectServer:l,onRefreshTools:c,isServerActionLoading:d})=>{const{t:u}=ne(),{token:h}=he.useToken(),p=m.useMemo(()=>({[ue.Connecting]:u("settings.mcpTab.statusHelp.connecting"),[ue.Ready]:u("settings.mcpTab.statusHelp.ready"),[ue.Degraded]:u("settings.mcpTab.statusHelp.degraded"),[ue.Stopped]:u("settings.mcpTab.statusHelp.stopped"),[ue.Error]:u("settings.mcpTab.statusHelp.error")}),[u]),g=m.useMemo(()=>[{key:"name",title:u("settings.mcpServerTable.columns.name"),render:(y,f)=>f.name||f.id},{key:"transport",title:u("settings.mcpServerTable.columns.transportType"),render:(y,f)=>f.config.transport.type==="sse"?u("settings.mcpServerTable.transportOptions.sse"):u("settings.mcpServerTable.transportOptions.stdio"),width:140},{key:"status",title:u("settings.mcpServerTable.columns.status"),render:(y,f)=>{var w,k;const v=((w=f.runtime)==null?void 0:w.status)??ue.Stopped,b=v0((k=f.runtime)==null?void 0:k.last_error),x=p[v],_={[ue.Connecting]:u("settings.mcpTab.status.connecting"),[ue.Ready]:u("settings.mcpTab.status.ready"),[ue.Degraded]:u("settings.mcpTab.status.degraded"),[ue.Stopped]:u("settings.mcpTab.status.stopped"),[ue.Error]:u("settings.mcpTab.status.error")};return r.jsx(ke,{title:b?`${x} ${u("settings.mcpTab.statusLastError",{error:b})}`:x,children:r.jsx(oe,{color:v===ue.Stopped?void 0:b0[v],style:{marginInlineEnd:0,cursor:"help",...v===ue.Stopped?{background:h.colorFillSecondary,borderColor:h.colorBorderSecondary,color:h.colorTextSecondary}:void 0},children:_[v]})})},width:120},{key:"toolCount",title:u("settings.mcpServerTable.columns.toolCount"),render:(y,f)=>{var v;return((v=f.runtime)==null?void 0:v.tool_count)??0},width:100},{key:"actions",title:u("settings.mcpServerTable.columns.actions"),width:360,render:(y,f)=>{var x;const v=((x=f.runtime)==null?void 0:x.status)??ue.Stopped,b=x0(v);return r.jsxs(X,{size:h.marginXS,children:[r.jsx(Y,{size:"small",onClick:_=>{_.stopPropagation(),o==null||o(f)},children:u("settings.mcpServerTable.actions.edit")}),r.jsx(mi,{title:u("settings.mcpServerTable.deleteTitle"),description:u("settings.mcpServerTable.deleteDescription",{name:f.name||f.id}),onConfirm:()=>a==null?void 0:a(f),okText:u("settings.mcpServerTable.actions.delete"),okButtonProps:{danger:!0,loading:d==null?void 0:d(f.id,"delete")},children:r.jsx(Y,{size:"small",danger:!0,loading:d==null?void 0:d(f.id,"delete"),onClick:_=>_.stopPropagation(),children:u("settings.mcpServerTable.actions.delete")})}),b?r.jsx(Y,{size:"small",onClick:_=>{_.stopPropagation(),l==null||l(f)},loading:d==null?void 0:d(f.id,"disconnect"),children:u("settings.mcpServerTable.actions.disconnect")}):r.jsx(Y,{size:"small",type:"primary",ghost:!0,onClick:_=>{_.stopPropagation(),i==null||i(f)},loading:d==null?void 0:d(f.id,"connect"),children:u("settings.mcpServerTable.actions.connect")}),r.jsx(Y,{size:"small",onClick:_=>{_.stopPropagation(),c==null||c(f)},loading:d==null?void 0:d(f.id,"refresh"),children:u("settings.mcpServerTable.actions.refreshTools")})]})}}],[d,i,a,l,o,c,p,u,h.colorBorderSecondary,h.colorFillSecondary,h.colorTextSecondary,h.marginXS]);return r.jsx(qs,{rowKey:"id",columns:g,dataSource:e,loading:t,pagination:!1,locale:{emptyText:u("settings.mcpServerTable.empty")},onRow:y=>({onClick:()=>n==null?void 0:n(y.id),style:{cursor:n?"pointer":"default",backgroundColor:s===y.id?h.colorFillSecondary:void 0}})})},{Text:Sm}=le,{TextArea:w0}=me,wm=e=>{const t=e??Vi(""),s=t.transport,n=s.type==="stdio"?Object.entries(s.env??{}).map(([a,i])=>({key:a,value:i})):[],o=s.type==="sse"?s.headers.map(a=>({name:a.name,value:a.value})):[];return{id:t.id,name:t.name,enabled:t.enabled,transportType:s.type,command:s.type==="stdio"?s.command:void 0,args:s.type==="stdio"?s.args:[],envEntries:n,url:s.type==="sse"?s.url:void 0,headerEntries:o,requestTimeoutMs:t.request_timeout_ms||va,healthcheckIntervalMs:t.healthcheck_interval_ms||Sa,allowedTools:t.allowed_tools||[],deniedTools:t.denied_tools||[]}},_0=e=>e.reduce((t,s)=>{var o;const n=(o=s.key)==null?void 0:o.trim();return n&&(t[n]=s.value??""),t},{}),T0=e=>e.filter(t=>{var s;return(s=t.name)==null?void 0:s.trim()}).map(t=>{var s;return{name:((s=t.name)==null?void 0:s.trim())||"",value:t.value??""}}),_m=(e,t,s)=>{var u,h,p;const n=t==="edit"&&(s==null?void 0:s.id)||e.id,o=(u=e.name)==null?void 0:u.trim(),a=typeof e.requestTimeoutMs=="number"?e.requestTimeoutMs:(s==null?void 0:s.request_timeout_ms)??va,i=typeof e.healthcheckIntervalMs=="number"?e.healthcheckIntervalMs:(s==null?void 0:s.healthcheck_interval_ms)??Sa,l=Array.isArray(e.allowedTools)?e.allowedTools:(s==null?void 0:s.allowed_tools)??[],c=Array.isArray(e.deniedTools)?e.deniedTools:(s==null?void 0:s.denied_tools)??[],d=e.transportType==="sse"?{type:"sse",url:((h=e.url)==null?void 0:h.trim())||"",headers:T0(e.headerEntries||[]),connect_timeout_ms:(s==null?void 0:s.transport.type)==="sse"?s.transport.connect_timeout_ms??Ci:Ci}:{type:"stdio",command:((p=e.command)==null?void 0:p.trim())||"",args:e.args||[],env:_0(e.envEntries||[]),cwd:(s==null?void 0:s.transport.type)==="stdio"?s.transport.cwd:void 0,startup_timeout_ms:(s==null?void 0:s.transport.type)==="stdio"?s.transport.startup_timeout_ms??aa:aa};return{id:n,name:o||void 0,enabled:e.enabled,transport:d,request_timeout_ms:a,healthcheck_interval_ms:i,allowed_tools:l,denied_tools:c,reconnect:s==null?void 0:s.reconnect}},Tm=e=>JSON.stringify(e||Vi(""),null,2),wl=(e,t)=>{try{const s=JSON.parse(e);if(!s||typeof s!="object")return{valid:!1,error:t("settings.mcpServerForm.jsonMustBeObject")};const n=s;if(n.mcpServers&&typeof n.mcpServers=="object")return{valid:!1,error:t("settings.mcpServerForm.detectedBulkConfig")};const o=typeof n.id=="string"?n.id:"";if(!o.trim())return{valid:!1,error:t("settings.mcpServerForm.missingIdField")};if(n.transport&&typeof n.transport=="object"){const h=n;return!h.transport||typeof h.transport!="object"?{valid:!1,error:t("settings.mcpServerForm.missingTransportField")}:{valid:!0,config:h}}const a=typeof n.enabled=="boolean"?n.enabled:typeof n.disabled=="boolean"?!n.disabled:!0,i=typeof n.request_timeout_ms=="number"?n.request_timeout_ms:va,l=typeof n.healthcheck_interval_ms=="number"?n.healthcheck_interval_ms:Sa,c=Array.isArray(n.allowed_tools)?n.allowed_tools.filter(h=>typeof h=="string"):[],d=Array.isArray(n.denied_tools)?n.denied_tools.filter(h=>typeof h=="string"):[],u=typeof n.name=="string"?n.name:void 0;if(typeof n.url=="string"){const h=n.headers,p=Array.isArray(h)?h.map(y=>{if(!y||typeof y!="object")return null;const f=y,v=typeof f.name=="string"?f.name:"",b=typeof f.value=="string"?f.value:"";return v.trim()?{name:v,value:b}:null}).filter(y=>!!y):h&&typeof h=="object"?Object.entries(h).filter(([y])=>y.trim()).map(([y,f])=>({name:y,value:typeof f=="string"?f:""})):[],g=typeof n.connect_timeout_ms=="number"?n.connect_timeout_ms:Ci;return{valid:!0,config:{id:o,name:u,enabled:a,transport:{type:"sse",url:n.url,headers:p,connect_timeout_ms:g},request_timeout_ms:i,healthcheck_interval_ms:l,allowed_tools:c,denied_tools:d,reconnect:void 0}}}if(typeof n.command=="string"){const h=Array.isArray(n.args)?n.args.filter(f=>typeof f=="string"):[],p=n.env,g=p&&typeof p=="object"?Object.entries(p).reduce((f,[v,b])=>(typeof b=="string"&&(f[v]=b),f),{}):{},y=typeof n.startup_timeout_ms=="number"?n.startup_timeout_ms:aa;return{valid:!0,config:{id:o,name:u,enabled:a,transport:{type:"stdio",command:n.command,args:h,cwd:typeof n.cwd=="string"?n.cwd:void 0,env:g,startup_timeout_ms:y},request_timeout_ms:i,healthcheck_interval_ms:l,allowed_tools:c,denied_tools:d,reconnect:void 0}}}return{valid:!1,error:t("settings.mcpServerForm.missingTransportInfo")}}catch(s){return{valid:!1,error:t("settings.mcpServerForm.invalidJson",{message:s instanceof Error?s.message:t("settings.mcpServerForm.unknownError")})}}},k0=({open:e,mode:t,initialConfig:s,confirmLoading:n=!1,onCancel:o,onSubmit:a})=>{const{t:i}=ne(),[l]=Z.useForm(),[c,d]=m.useState("form"),[u,h]=m.useState(""),[p,g]=m.useState(null),y=m.useMemo(()=>wm(s),[s]),f=Z.useWatch("transportType",l)??"stdio";m.useEffect(()=>{e&&(l.setFieldsValue(y),h(Tm(s)),g(null),d("form"))},[l,y,s,e]);const v=()=>{l.resetFields(),h(""),g(null),o()},b=async()=>{if(c==="json"){const w=wl(u,i);if(!w.valid){g(w.error);return}g(null);try{await a(w.config),h("")}catch(k){console.error("MCP server JSON submission error:",k)}return}try{const w=await l.validateFields(),k=_m(w,t,s);await a(k),l.resetFields()}catch(w){console.error("MCP server form submission error:",w)}},x=w=>{h(w),p&&wl(w,i).valid&&g(null)},_=w=>{if(w==="json")try{const k=l.getFieldsValue(),C=_m(k,t,s);h(JSON.stringify(C,null,2))}catch{h(Tm(s))}else{const k=wl(u,i);k.valid&&l.setFieldsValue(wm(k.config))}d(w),g(null)};return r.jsxs(Lt,{title:i(t==="edit"?"settings.mcpServerForm.editTitle":"settings.mcpServerForm.addTitle"),open:e,onCancel:v,onOk:()=>{b()},okText:i("settings.mcpServerForm.save"),destroyOnClose:!0,confirmLoading:n,width:720,children:[r.jsx("div",{style:{marginBottom:16},children:r.jsxs(ts.Group,{value:c,onChange:w=>_(w.target.value),optionType:"button",buttonStyle:"solid",children:[r.jsxs(ts.Button,{value:"form",children:[r.jsx(mx,{})," ",i("settings.mcpServerForm.modeForm")]}),r.jsxs(ts.Button,{value:"json",children:[r.jsx(Li,{})," ",i("settings.mcpServerForm.modeJson")]})]})}),c==="json"&&p&&r.jsx(Xe,{type:"error",message:i("settings.mcpServerForm.jsonError"),description:p,showIcon:!0,style:{marginBottom:16},closable:!0,onClose:()=>g(null)}),c==="json"?r.jsx(w0,{value:u,onChange:w=>x(w.target.value),rows:20,style:{fontFamily:"monospace",fontSize:13},placeholder:JSON.stringify(Vi("example-server"),null,2)}):r.jsxs(Z,{layout:"vertical",form:l,preserve:!0,initialValues:y,children:[r.jsx(Z.Item,{name:"id",label:i("settings.mcpServerForm.serverId"),rules:[{required:!0,message:i("settings.mcpServerForm.serverIdRequired")},{pattern:/^[a-zA-Z0-9_-]+$/,message:i("settings.mcpServerForm.serverIdPatternError")}],children:r.jsx(me,{placeholder:"filesystem",disabled:t==="edit",autoComplete:"off"})}),r.jsx(Z.Item,{name:"name",label:i("settings.mcpServerForm.displayName"),children:r.jsx(me,{placeholder:"Filesystem MCP",autoComplete:"off"})}),r.jsx(Z.Item,{name:"enabled",label:i("settings.mcpServerForm.enabled"),valuePropName:"checked",extra:i("settings.mcpServerForm.enabledHelp"),children:r.jsx(it,{})}),r.jsx(Z.Item,{name:"transportType",label:i("settings.mcpServerForm.transportType"),rules:[{required:!0,message:i("settings.mcpServerForm.transportTypeRequired")}],children:r.jsx(Pe,{options:[{label:i("settings.mcpServerForm.transportOptions.stdio"),value:"stdio"},{label:i("settings.mcpServerForm.transportOptions.sse"),value:"sse"}]})}),f==="stdio"?r.jsxs(r.Fragment,{children:[r.jsx(Z.Item,{name:"command",label:i("settings.mcpServerForm.command"),rules:[{required:!0,message:i("settings.mcpServerForm.commandRequired")}],children:r.jsx(me,{placeholder:"npx",autoComplete:"off"})}),r.jsx(Z.Item,{name:"args",label:i("settings.mcpServerForm.arguments"),children:r.jsx(Pe,{mode:"tags",tokenSeparators:[","],placeholder:i("settings.mcpServerForm.argumentsPlaceholder"),open:!1})}),r.jsx(Z.List,{name:"envEntries",children:(w,{add:k,remove:C})=>r.jsxs(X,{direction:"vertical",style:{width:"100%"},children:[r.jsxs(X,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[r.jsx(Sm,{strong:!0,children:i("settings.mcpServerForm.envVars")}),r.jsx(Y,{icon:r.jsx(Us,{}),onClick:()=>k({key:"",value:""}),type:"dashed",children:i("settings.mcpServerForm.addEnv")})]}),w.map(E=>r.jsxs(X,{align:"baseline",style:{display:"flex"},children:[r.jsx(Z.Item,{...E,name:[E.name,"key"],rules:[{required:!0,message:i("settings.mcpServerForm.keyRequired")}],children:r.jsx(me,{placeholder:"MCP_ROOT",autoComplete:"off"})}),r.jsx(Z.Item,{...E,name:[E.name,"value"],children:r.jsx(me,{placeholder:"/Users/me/workspace",autoComplete:"off"})}),r.jsx(Y,{danger:!0,type:"text",icon:r.jsx(nc,{}),onClick:()=>C(E.name),"aria-label":i("settings.mcpServerForm.removeEnv","Remove environment variable")})]},E.key))]})})]}):r.jsxs(r.Fragment,{children:[r.jsx(Z.Item,{name:"url",label:i("settings.mcpServerForm.sseUrl"),rules:[{required:!0,message:i("settings.mcpServerForm.sseUrlRequired")},{validator:async(w,k)=>{if(k)try{new URL(k)}catch{throw new Error(i("settings.mcpServerForm.validUrlRequired"))}}}],children:r.jsx(me,{placeholder:"http://localhost:4000/sse",autoComplete:"off"})}),r.jsx(Z.List,{name:"headerEntries",children:(w,{add:k,remove:C})=>r.jsxs(X,{direction:"vertical",style:{width:"100%"},children:[r.jsxs(X,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[r.jsx(Sm,{strong:!0,children:i("settings.mcpServerForm.headers")}),r.jsx(Y,{icon:r.jsx(Us,{}),onClick:()=>k({name:"",value:""}),type:"dashed",children:i("settings.mcpServerForm.addHeader")})]}),w.map(E=>r.jsxs(X,{align:"baseline",style:{display:"flex"},children:[r.jsx(Z.Item,{...E,name:[E.name,"name"],rules:[{required:!0,message:i("settings.mcpServerForm.headerNameRequired")}],children:r.jsx(me,{placeholder:"Authorization",autoComplete:"off"})}),r.jsx(Z.Item,{...E,name:[E.name,"value"],children:r.jsx(me,{placeholder:"Bearer token",autoComplete:"off"})}),r.jsx(Y,{danger:!0,type:"text",icon:r.jsx(nc,{}),onClick:()=>C(E.name),"aria-label":i("settings.mcpServerForm.removeHeader","Remove header")})]},E.key))]})})]})]})]})},j0={maxLines:8,maxCharacters:500},on=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Zs=e=>typeof e=="string"?e:void 0,Mn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,km=e=>typeof e=="boolean"?e:void 0,Xd=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const s=JSON.parse(t);return on(s)?s:null}catch{return null}},Ey=e=>/\\u[0-9a-fA-F]{4}|\\n|\\t|\\r/.test(e)?e.replace(/\\u([0-9a-fA-F]{4})/g,(t,s)=>String.fromCharCode(parseInt(s,16))).replace(/\\n/g,`
|
|
112
|
+
Raw error: ${t}`:"";return["Bamboo stopped this completion because Copilot conclusion_with_options confirmation is enabled for this session.","The assistant tried to finish with plain text instead of calling conclusion_with_options.","Next steps: retry the request, shorten or clarify the prompt, or temporarily disable the Copilot conclusion_with_options enhancement for this session if you do not want enforced confirmation."].join(" ")+s};function Cy(e){var R;const{modal:t,message:s}=Ot.useApp(),{t:n}=ne(),o=m.useRef(null),a=m.useRef(null),i=m.useRef(""),l=m.useRef(new rs),c=N(M=>M.agentAvailability),d=N(M=>M.setAgentAvailability),u=N(M=>M.checkAgentAvailability),h=N(M=>M.startAgentHealthCheck),p=Hi(e.sessionId),g=Ee(M=>M.currentProvider),y=N(M=>e.sessionId&&M.chats.find(T=>T.id===e.sessionId)||null),f=Bd((R=y==null?void 0:y.config)==null?void 0:R.model_ref);m.useEffect(()=>{h()},[h]);const v=m.useCallback(()=>{var T;(T=o.current)==null||T.abort();const M=y==null?void 0:y.id;M&&l.current.stopGeneration(M).catch(P=>{console.error("[useMessageStreaming] Failed to stop generation:",P)})},[y==null?void 0:y.id]),b=m.useCallback(M=>{var O;const T=N.getState(),S=(Array.isArray(T.chats)?T.chats:[]).find(D=>D.id===M),L=T.pendingQuestionRespond,$=(L==null?void 0:L.sessionId)===M?L:null,I=(O=S==null?void 0:S.config)==null?void 0:O.syncCursor,W=!!$||!!(I!=null&&I.hasPendingQuestion),A=($==null?void 0:$.toolCallId)??(I==null?void 0:I.pendingQuestionToolCallId)??null;return{client_message_count:(I==null?void 0:I.messageCount)??(S==null?void 0:S.messageCount)??0,client_last_message_id:(I==null?void 0:I.lastMessageId)??null,client_has_pending_question:W,client_pending_question_tool_call_id:A}},[]),x=m.useCallback((M,T)=>{const P=T.sync;if(!P)return;const S=N.getState(),$=(Array.isArray(S.chats)?S.chats:[]).find(I=>I.id===M);$&&e.updateSession(M,{messageCount:P.server_message_count,config:{...$.config||{},syncCursor:{messageCount:P.server_message_count,lastMessageId:P.server_last_message_id??null,hasPendingQuestion:P.has_pending_question,pendingQuestionToolCallId:P.pending_question_tool_call_id??null}}})},[e]),_=m.useCallback(async M=>{try{return await pe.get(`respond/${M}/pending`)}catch(T){return console.warn(`[useMessageStreaming] Failed to fetch pending question for ${M}:`,T),{has_pending_question:!1}}},[]),w=m.useCallback(async(M,T,P)=>{var A,O;e.setSessionProcessing(M,!1),await N.getState().loadChatHistory(M,{mode:"replace"});const S=await _(M),L=N.getState().setPendingQuestionRespond,$=N.getState().clearPendingQuestionRespondForSession;if(S.has_pending_question){L({sessionId:M,question:S.question||"",options:S.options||[],allowCustom:S.allow_custom??!0,toolCallId:S.tool_call_id??null});const D=N.getState().chats.find(H=>H.id===M);return D&&e.updateSession(M,{config:{...D.config||{},syncCursor:{messageCount:D.messageCount??D.messages.length,lastMessageId:((O=(A=D.config)==null?void 0:A.syncCursor)==null?void 0:O.lastMessageId)??null,hasPendingQuestion:!0,pendingQuestionToolCallId:S.tool_call_id??null}}}),null}if($(M),!((T==null?void 0:T.has_pending_user_message)??!1))return null;e.setSessionProcessing(M,!0),await new Promise(D=>setTimeout(D,0));const W=P?await l.current.execute(M,void 0,P,b(M),f??void 0):await l.current.execute(M,void 0,void 0,b(M),f??void 0);return x(M,W),W},[f,x,b,e,_]),k=m.useCallback(async(M,T,P)=>{var I,W;let S=T;x(M,S);const L=2;let $=0;for(;(I=S.sync)!=null&&I.need_sync&&$<L;){const A=await w(M,S.sync,P);if($+=1,!A){e.setSessionProcessing(M,!1);return}S=A,x(M,S)}if((W=S.sync)!=null&&W.need_sync){console.warn(`[useMessageStreaming] Execute remains out-of-sync after ${L} recovery attempt(s) for session ${M}.`,S.sync),e.setSessionProcessing(M,!1);return}if(!["started","already_running"].includes(S.status)){if(S.status==="completed"){st("[Streaming]","[Agent] Session already completed"),e.setSessionProcessing(M,!1);return}throw console.error("[Agent] Execute failed:",S.status),e.setSessionProcessing(M,!1),new Error(`Execute failed: ${S.status}`)}},[x,e,w]),C=m.useCallback(async(M,T,P,S,L)=>{var I,W;if(!p)throw new Error(n("chat.model.noModelSelected"));const $=new AbortController;o.current=$;try{const A=w_(g).trim(),O=(g??"").trim().toLowerCase()==="copilot"&&ki(),H=(((I=y==null?void 0:y.config)==null?void 0:I.workspacePath)||"").trim().replace(/\/+$/,"").replace(/\\+$/,""),B=await l.current.sendMessage({message:M,session_id:T,enhance_prompt:A||void 0,copilot_conclusion_with_options_enhancement_enabled:O,workspace_path:H||void 0,selected_skill_ids:L&&L.length>0?L:void 0,images:(W=P.images)==null?void 0:W.filter(z=>!!z.base64).map(z=>({base64:z.base64,name:z.name,size:z.size,type:z.type})),model:p,...f?{model_ref:f,provider:f.provider}:{}}),{session_id:K}=B;K!==T&&console.warn(`[useMessageStreaming] Backend returned unexpected session_id=${K} for sessionId=${T}`),await N.getState().loadChatHistory(T,{mode:"replace"}),e.setSessionProcessing(T,!0),await new Promise(z=>setTimeout(z,0));const F=S?await l.current.execute(T,void 0,S,b(T),f??void 0):await l.current.execute(T,void 0,void 0,b(T),f??void 0);st("[Streaming]","[Agent] Execute status:",F.status),await k(T,F,S)}catch(A){throw A}},[p,f,b,y,g,e,k,n]),E=m.useCallback(async(M,T,P,S)=>{if(!y){t.info({title:n("chat.streaming.noActiveChatTitle"),content:n("chat.streaming.noActiveChatSendContent")});return}if(!e.sessionId){t.info({title:n("chat.streaming.noChatIdTitle"),content:n("chat.streaming.noChatIdSendContent")});return}if(!p){t.error({title:n("chat.model.noModelSelected"),content:n("chat.model.selectModelBeforeSend")});return}let L=c;if(L===null&&(L=await u()),!L){s.error(n("chat.streaming.agentUnavailable"));return}if(!p){s.error(n("chat.streaming.modelConfigNotLoaded"));return}const $=e.sessionId,I=(T==null?void 0:T.map(A=>({id:A.id,base64:A.base64,name:A.name,size:A.size,type:A.type})))||[],W={role:"user",content:M,id:crypto.randomUUID(),createdAt:new Date().toISOString(),images:I};await e.addMessage($,W);try{st("[Streaming]","[useChatStreaming] Using Agent Server"),await C(M,$,W,P,S)}catch(A){if(a.current&&ze.clear($,a.current),a.current=null,i.current="",A instanceof Error&&A.name==="AbortError")s.info(n("chat.streaming.requestCancelled"));else{console.error("[useChatStreaming] Failed to send message:",A);const O=A instanceof Error?A.message:String(A??"");Ec(O)?s.error(Rc(O)):(s.error(n("chat.streaming.sendFailed")),d(!1))}e.setSessionProcessing($,!1)}finally{o.current=null,a.current&&ze.clear($,a.current),a.current=null,i.current=""}},[c,s,u,y,e,t,C,d,p,n]),j=m.useCallback(async(M,T="regenerate")=>{if(!y){t.info({title:n("chat.streaming.noActiveChatTitle"),content:n("chat.streaming.noActiveChatRetryContent")});return}if(!e.sessionId){t.info({title:n("chat.streaming.noChatIdTitle"),content:n("chat.streaming.noChatIdRetryContent")});return}if(!p){t.error({title:n("chat.model.noModelSelected"),content:n("chat.model.selectModelBeforeRetry")});return}let P=c;if(P===null&&(P=await u()),!P){s.error(n("chat.streaming.agentUnavailable"));return}const S=e.sessionId;a.current&&ze.clear(S,a.current),a.current=null,i.current="";try{const L=T==="error_retry"?"error_retry":"after_last_user",$=await l.current.truncateSessionMessages(S,{mode:L});(T==="regenerate"||($.messages_removed??0)>0)&&await N.getState().loadChatHistory(S,{mode:"replace"}),e.setSessionProcessing(S,!0);const I=M?await l.current.execute(S,void 0,M,b(S),f??void 0):await l.current.execute(S,void 0,void 0,b(S),f??void 0);await k(S,I,M)}catch(L){console.error("[useMessageStreaming] Retry failed:",L);const $=L instanceof Error?L.message:String(L??"");Ec($)?s.error(Rc($)):s.error(n("chat.streaming.retryFailed")),e.setSessionProcessing(S,!1)}finally{o.current=null}},[p,f,c,s,b,u,y,e,k,t,n]);return{sendMessage:E,retryLastTurn:j,cancel:v,agentAvailable:c}}function __(e,t){const s=m.useMemo(()=>e.baseMessages,[e.baseMessages]),n=m.useCallback(async()=>{var d;if(!e.currentSessionId||!e.currentChat)return;const o=[...e.baseMessages];if(o.length===0)return;const a=o[o.length-1];let i=o;if((a==null?void 0:a.role)==="assistant"){if(!(await e.deleteMessage(e.currentSessionId,a.id)).success)return;i=o.slice(0,-1)}const l=[...i].reverse().find(u=>u.role==="user");if(!l)return;const c="content"in l?l.content:l.displayText;typeof c=="string"&&await((d=t==null?void 0:t.onRetry)==null?void 0:d.call(t,c))},[e,t]);return{currentMessages:s,retryLastMessage:n}}const T_=()=>{const e=a_(),t=Ud(e),s=i_(e),n=Cy({sessionId:e.currentSessionId,addMessage:e.addMessage,setSessionProcessing:e.setSessionProcessing,updateSession:e.updateSession}),o=__(e,{onRetry:n.sendMessage});return{chats:e.chats,currentSessionId:e.currentSessionId,currentChat:e.currentChat,pinnedChats:e.pinnedChats,unpinnedChats:e.unpinnedChats,chatCount:e.chatCount,currentMessages:o.currentMessages,agentAvailable:n.agentAvailable,titleGenerationState:t.titleGenerationState,autoGenerateTitles:t.autoGenerateTitles,isUpdatingAutoTitlePreference:t.isUpdatingAutoTitlePreference,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,generateChatTitle:t.generateChatTitle,setAutoGenerateTitlesPreference:t.setAutoGenerateTitlesPreference,createNewChat:s.createNewChat,createChatWithSystemPrompt:s.createChatWithSystemPrompt,toggleChatPin:s.toggleChatPin,updateChatTitle:s.updateChatTitle,deleteEmptyChats:s.deleteEmptyChats,deleteAllUnpinnedChats:s.deleteAllUnpinnedChats,deleteAllChats:s.deleteAllChats,retryLastMessage:o.retryLastMessage,sendMessage:n.sendMessage,cancelMessage:n.cancel}},My="lotus_vdi_safe_mode",ji=()=>{try{return localStorage.getItem(My)==="true"}catch{return!1}},k_=e=>{try{localStorage.setItem(My,e.toString())}catch(t){console.error("[vdiSafeMode] Failed to persist setting:",t)}},{Text:Fa}=le,{useToken:j_}=he,C_=({httpProxy:e,httpsProxy:t,onHttpProxyChange:s,onHttpsProxyChange:n,onReload:o,onSave:a,isLoading:i})=>{const{t:l}=ne(),{token:c}=j_(),d=ms(w=>w.proxyAuthStatus),u=ms(w=>w.isLoadingProxyAuthStatus),h=ms(w=>w.loadProxyAuthStatus),p=ms(w=>w.applyProxyAuth),g=ms(w=>w.clearProxyAuth),[y,f]=m.useState({username:"",password:""}),[v,b]=m.useState(!1);m.useEffect(()=>{h()},[h]);const x=async()=>{const w=y.username.trim();if(w){b(!0);try{await p({username:w,password:y.password}),f({username:"",password:""})}catch(k){console.error("Failed to apply proxy auth:",k)}finally{b(!1)}}},_=async()=>{b(!0);try{await g()}catch(w){console.error("Failed to clear proxy auth:",w)}finally{b(!1)}};return r.jsx(ee,{size:"small",title:r.jsx(Fa,{strong:!0,children:l("settings.networkCard.title")}),className:"lotus-settings-card",children:r.jsxs(X,{direction:"vertical",size:c.marginSM,style:{width:"100%"},children:[r.jsx(Xe,{message:l("settings.networkCard.guideTip"),type:"info",showIcon:!0}),r.jsxs(X,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[r.jsx(Fa,{type:"secondary",children:l("settings.networkCard.httpProxy")}),r.jsx(me,{"data-testid":"proxy-url",style:{width:"100%"},value:e,onChange:w=>s(w.target.value),placeholder:l("settings.networkCard.proxyPlaceholder"),disabled:i})]}),r.jsxs(X,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[r.jsx(Fa,{type:"secondary",children:l("settings.networkCard.httpsProxy")}),r.jsx(me,{style:{width:"100%"},value:t,onChange:w=>n(w.target.value),placeholder:l("settings.networkCard.proxyPlaceholder"),disabled:i})]}),r.jsx(ee,{size:"small",title:l("settings.networkCard.proxyAuthTitle"),className:"lotus-settings-card",style:{marginTop:c.marginSM},children:d!=null&&d.configured?r.jsxs(X,{direction:"vertical",style:{width:"100%"},children:[r.jsx(Xe,{type:"success",message:l("settings.networkCard.proxyConfiguredForUser",{username:d.username??""}),showIcon:!0}),r.jsx(Y,{onClick:_,loading:v||u,danger:!0,children:l("settings.networkCard.clearCredentials")})]}):r.jsxs(X,{direction:"vertical",size:c.marginXS,style:{width:"100%"},children:[r.jsx(me,{placeholder:l("settings.networkCard.username"),value:y.username,onChange:w=>f(k=>({...k,username:w.target.value}))}),r.jsx(me.Password,{placeholder:l("settings.networkCard.password"),value:y.password,onChange:w=>f(k=>({...k,password:w.target.value}))}),r.jsx(Y,{type:"primary",onClick:x,loading:v||u,disabled:!y.username.trim(),children:l("settings.networkCard.apply")})]})}),r.jsx(Fa,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l("settings.networkCard.credentialsStorageNote")}),r.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:c.marginSM},children:[r.jsx(Y,{onClick:()=>Promise.resolve(o()).finally(()=>h({force:!0})),disabled:i,children:l("settings.networkCard.reload")}),r.jsx(Y,{"data-testid":"save-proxy-settings",type:"primary",onClick:()=>Promise.resolve(a()).finally(()=>h({force:!0})),disabled:i,children:l("settings.networkCard.save")})]})]})})},{Text:M_}=le,{useToken:P_}=he,E_=({msgApi:e})=>{const{t}=ne(),{token:s}=P_(),[n]=Z.useForm(),[o,a]=m.useState(!1),[i,l]=m.useState(!1),[c,d]=m.useState(!1),[u,h]=m.useState(!1),[p,g]=m.useState(null),y=c&&!u,f=m.useMemo(()=>c?u?t("settings.configTab.accessPassword.helperLocalBypass","当前是本地访问,可直接修改访问密码,无需输入当前密码。"):t("settings.configTab.accessPassword.helperRemote","当前是远程访问。修改访问密码前,必须先输入当前密码。"):t("settings.configTab.accessPassword.helperNotEnabled","未设置访问密码。设置后,远程访问需要先输入密码,本地 loopback 访问可直接绕过。"),[u,c,t]),v=m.useCallback(async()=>{a(!0),g(null);try{const x=await et.getAccessStatus();d(x.password_enabled),h(x.local_bypass)}catch(x){const _=x instanceof Error?x.message:t("settings.configTab.accessPassword.loadStatusFailed","Failed to load access status");g(_)}finally{a(!1)}},[t]);m.useEffect(()=>{v()},[v]);const b=async()=>{var x;try{const _=await n.validateFields();l(!0),await et.updateAccessPassword({current_password:((x=_.currentPassword)==null?void 0:x.trim())||void 0,new_password:_.newPassword.trim()}),e.success(c?t("settings.configTab.accessPassword.updated","访问密码已更新"):t("settings.configTab.accessPassword.enabled","访问密码已设置")),n.resetFields(),await v()}catch(_){if(_.errorFields)return;const w=_ instanceof Error?_.message:t("settings.configTab.accessPassword.updateFailed","Failed to update access password");e.error(w)}finally{l(!1)}};return r.jsx(ee,{size:"small",className:"lotus-settings-card",title:r.jsx(M_,{strong:!0,children:t("settings.configTab.accessPasswordTitle","访问密码")}),children:r.jsxs(X,{direction:"vertical",size:s.marginMD,style:{width:"100%"},children:[r.jsx(Xe,{type:c?"info":"warning",showIcon:!0,message:c?t("settings.configTab.accessPassword.statusEnabled","访问密码已启用"):t("settings.configTab.accessPassword.statusDisabled","访问密码未启用"),description:f}),p?r.jsx(Xe,{type:"error",showIcon:!0,message:p}):null,r.jsxs(Z,{form:n,layout:"vertical",disabled:o||i,children:[y?r.jsx(Z.Item,{label:t("settings.configTab.accessPassword.currentPasswordLabel","当前密码"),name:"currentPassword",rules:[{required:!0,message:t("settings.configTab.accessPassword.validation.currentPasswordRequired","请输入当前密码")}],children:r.jsx(me.Password,{autoComplete:"current-password"})}):null,r.jsx(Z.Item,{label:c?t("settings.configTab.accessPassword.newPasswordLabel","新密码"):t("settings.configTab.accessPassword.setPasswordLabel","设置密码"),name:"newPassword",rules:[{required:!0,message:t("settings.configTab.accessPassword.validation.newPasswordRequired","请输入新密码")},{min:4,message:t("settings.configTab.accessPassword.validation.minLength","密码长度至少 4 位")}],children:r.jsx(me.Password,{autoComplete:"new-password"})}),r.jsx(Z.Item,{label:t("settings.configTab.accessPassword.confirmPasswordLabel","确认密码"),name:"confirmPassword",dependencies:["newPassword"],rules:[{required:!0,message:t("settings.configTab.accessPassword.validation.confirmPasswordRequired","请再次输入新密码")},({getFieldValue:x})=>({validator(_,w){return!w||x("newPassword")===w?Promise.resolve():Promise.reject(new Error(t("settings.configTab.accessPassword.validation.passwordMismatch","两次输入的密码不一致")))}})],children:r.jsx(me.Password,{autoComplete:"new-password"})}),r.jsx(Y,{type:"primary",loading:i,onClick:()=>void b(),children:c?t("settings.configTab.accessPassword.updateAction","更新访问密码"):t("settings.configTab.accessPassword.enableAction","启用访问密码")})]})]})})},{Text:qt}=le,{useToken:R_}=he,ym="http://127.0.0.1:9562/v1",Xo=e=>[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort(),A_=e=>{var s;const t=(s=e.tools)==null?void 0:s.disabled;return Array.isArray(t)?Xo(t.filter(n=>typeof n=="string")):[]},I_=({msgApi:e,locale:t,onLocaleChange:s})=>{const{t:n}=ne(),{token:o}=R_(),[a,i]=m.useState({http_proxy:"",https_proxy:"",memory:{auto_dream_enabled:!1,background_model:""}}),[l,c]=m.useState(ym),[d,u]=m.useState([]),[h,p]=m.useState([]),[g,y]=m.useState([]),[f,v]=m.useState(!1),[b,x]=m.useState(!1),_=m.useCallback(async()=>{var I,W;v(!0);try{const[A,O]=await Promise.all([et.getBambooConfig(),et.getBambooTools()]);i({http_proxy:A.http_proxy||"",https_proxy:A.https_proxy||"",memory:{auto_dream_enabled:((I=A.memory)==null?void 0:I.auto_dream_enabled)??!1,background_model:((W=A.memory)==null?void 0:W.background_model)||""}});const D=A_(A);p(D),y(D),u(Xo(O.tools||[]))}catch(A){console.error("Failed to load config:",A),e.error(n("settings.configTab.loadConfigFailed"))}finally{v(!1)}},[e,n]);m.useEffect(()=>{_()},[_]);const w=I=>{i(W=>({...W,http_proxy:I}))},k=I=>{i(W=>({...W,https_proxy:I}))},C=I=>{i(W=>({...W,memory:{...W.memory,auto_dream_enabled:I}}))},E=I=>{i(W=>({...W,memory:{...W.memory,background_model:I}}))},j=async()=>{var I,W;v(!0);try{const A=await et.validateBambooConfigPatch(a);if(!A.valid){const D=((W=(I=A.errors)==null?void 0:I.proxy)==null?void 0:W[0])??Object.values(A.errors||{}).flat().filter(Boolean)[0];e.error((D==null?void 0:D.message)||n("settings.configTab.invalidConfig"));return}await et.setBambooConfig(a),e.success(n("settings.configTab.saveConfigSuccess"))}catch(A){console.error("Failed to save config:",A);const O=A instanceof Error&&A.message.trim()?A.message:n("settings.configTab.saveConfigFailed");e.error(O)}finally{v(!1)}},R=async()=>{e.success(n("settings.configTab.backendSaved"))},M=()=>{c(ym),e.success(n("settings.configTab.backendResetDefault"))},T=(I,W)=>{p(A=>{const O=new Set(A);return W?O.delete(I):O.add(I),Xo([...O])})},P=async()=>{x(!0);try{const I=await et.getBambooTools();u(Xo(I.tools||[])),e.success(n("settings.configTab.toolsReloadSuccess"))}catch(I){console.error("Failed to reload tools:",I),e.error(n("settings.configTab.toolsLoadFailed"))}finally{x(!1)}},S=async()=>{x(!0);try{const I=Xo(h);await et.setBambooConfig({tools:{disabled:I}}),p(I),y(I),e.success(n("settings.configTab.toolsSaveSuccess"))}catch(I){console.error("Failed to save tool settings:",I),e.error(n("settings.configTab.toolsSaveFailed"))}finally{x(!1)}},L=JSON.stringify(h)!==JSON.stringify(g),$=new Set(h);return r.jsx(ps,{spinning:f,tip:n("settings.common.loading"),children:r.jsx(ui,{items:[{key:"general",label:n("settings.configTab.tabs.general"),children:r.jsxs(X,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[r.jsx(Xe,{message:n("settings.configTab.providerMovedTitle"),description:n("settings.configTab.providerMovedDescription"),type:"info",showIcon:!0,closable:!0}),r.jsx(C_,{httpProxy:a.http_proxy,httpsProxy:a.https_proxy,onHttpProxyChange:w,onHttpsProxyChange:k,onReload:_,onSave:j,isLoading:f}),r.jsx(ee,{size:"small",className:"lotus-settings-card",title:r.jsx(qt,{strong:!0,children:n("settings.configTab.language")}),children:r.jsx(Pe,{value:t,style:{width:260},options:[{label:n("settings.configTab.languageEnglish"),value:"en-US"},{label:n("settings.configTab.languageChinese"),value:"zh-CN"},{label:n("settings.configTab.languageTraditionalChinese"),value:"zh-TW"},{label:n("settings.configTab.languageFrench"),value:"fr-FR"},{label:n("settings.configTab.languageJapanese"),value:"ja-JP"},{label:n("settings.configTab.languageHindi"),value:"hi-IN"}],onChange:I=>s(I)})}),r.jsx(ee,{size:"small",className:"lotus-settings-card",title:r.jsx(qt,{strong:!0,children:n("settings.configTab.memoryTitle")}),children:r.jsxs(X,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[r.jsx(qt,{type:"secondary",children:n("settings.configTab.memoryDescription")}),r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:o.marginMD,flexWrap:"wrap"},children:[r.jsxs("div",{children:[r.jsx(qt,{strong:!0,children:n("settings.configTab.autoDreamEnabled")}),r.jsx("div",{children:r.jsx(qt,{type:"secondary",style:{fontSize:o.fontSizeSM},children:n("settings.configTab.autoDreamEnabledHint")})})]}),r.jsx(it,{"data-testid":"auto-dream-toggle",checked:a.memory.auto_dream_enabled,onChange:C})]}),r.jsxs(X,{direction:"vertical",size:o.marginXXS,style:{width:"100%"},children:[r.jsx(qt,{strong:!0,children:n("settings.configTab.backgroundModel")}),r.jsx(me,{"data-testid":"auto-dream-background-model-input",value:a.memory.background_model,onChange:I=>E(I.target.value),placeholder:n("settings.configTab.backgroundModelPlaceholder")}),r.jsx(qt,{type:"secondary",style:{fontSize:o.fontSizeSM},children:n("settings.configTab.backgroundModelHint")})]}),r.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:r.jsx(Y,{"data-testid":"save-memory-settings",type:"primary",onClick:j,loading:f,children:n("settings.configTab.save")})})]})}),r.jsx(ee,{size:"small",title:r.jsx(qt,{strong:!0,children:n("settings.configTab.backendApiBaseUrlTitle")}),children:r.jsxs(X,{direction:"vertical",size:o.marginSM,style:{width:"100%"},children:[r.jsx(X,{direction:"vertical",size:o.marginXXS,style:{width:"100%"},children:r.jsx(me,{style:{width:"100%"},value:l,onChange:I=>c(I.target.value),placeholder:n("settings.configTab.backendApiPlaceholder")})}),r.jsx(qt,{type:"secondary",style:{fontSize:o.fontSizeSM},children:n("settings.configTab.backendApiHint")}),r.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:o.marginSM},children:[r.jsx(Y,{"data-testid":"reset-to-defaults",onClick:M,children:n("settings.configTab.resetToDefault")}),r.jsx(Y,{"data-testid":"save-api-settings",type:"primary",onClick:R,children:n("settings.configTab.save")})]})]})}),r.jsx(E_,{msgApi:e})]})},{key:"tools",label:n("settings.configTab.tabs.tools"),children:r.jsx(ee,{size:"small",title:r.jsx(qt,{strong:!0,children:n("settings.configTab.toolsTitle")}),children:r.jsxs(X,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[r.jsx(qt,{type:"secondary",children:n("settings.configTab.toolsDescription")}),d.length===0?r.jsx(Xe,{type:"info",showIcon:!0,message:n("settings.configTab.toolsEmpty")}):r.jsx(nt,{bordered:!0,dataSource:d,renderItem:I=>r.jsx(nt.Item,{actions:[r.jsx(it,{checked:!$.has(I),onChange:W=>T(I,W)},`${I}-switch`)],children:r.jsx(qt,{code:!0,children:I})})}),r.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:o.marginSM},children:[r.jsx(Y,{onClick:P,loading:b,children:n("settings.configTab.reloadTools")}),r.jsx(Y,{type:"primary",onClick:S,loading:b,disabled:!L,children:n("settings.configTab.save")})]})]})})}]})})},bm={theme:"default",themeVariables:{},fontSize:16,defaultScale:1,useMaxWidth:!0,flowchartNodeSpacing:50,flowchartRankSpacing:50,flowchartCurve:"basis",sequenceActorMargin:50,sequenceMessageMargin:35,sequenceWidth:150,sequenceHeight:65,ganttBarHeight:20,ganttTopPadding:50},Hd=un()(hv(e=>({settings:bm,updateSettings:t=>e(s=>({settings:{...s.settings,...t}})),resetSettings:()=>e({settings:bm})}),{name:"mermaid-settings"})),Xi=()=>Hd(t=>t.settings),$_=()=>Hd(e=>e.updateSettings),D_=()=>Hd(e=>e.resetSettings),{Title:L_,Text:vl}=le,{useToken:O_}=he,F_=()=>{const{t:e}=ne(),{token:t}=O_(),s=Xi(),n=$_(),o=D_(),[a]=Z.useForm();ut.useEffect(()=>{a.setFieldsValue(s)},[s,a]);const i=c=>{n(c)},l=()=>{o(),a.resetFields()};return r.jsxs("div",{style:{padding:"24px",maxWidth:"1200px",margin:"0 auto"},children:[r.jsx(L_,{level:3,style:{marginBottom:"8px"},children:e("settings.mermaidTab.title")}),r.jsx(vl,{type:"secondary",style:{display:"block",marginBottom:"24px"},children:e("settings.mermaidTab.description")}),r.jsxs(Z,{form:a,layout:"vertical",initialValues:s,onValuesChange:i,children:[r.jsxs(ee,{title:e("settings.mermaidTab.themeCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:[r.jsx(Gt,{gutter:16,children:r.jsx(Oe,{span:24,children:r.jsx(Z.Item,{name:"theme",label:r.jsxs(X,{children:[e("settings.mermaidTab.themeLabel"),r.jsx(ke,{title:e("settings.mermaidTab.themeTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsxs(Pe,{children:[r.jsx(Pe.Option,{value:"default",children:e("settings.mermaidTab.themeOptions.default")}),r.jsx(Pe.Option,{value:"neutral",children:e("settings.mermaidTab.themeOptions.neutral")}),r.jsx(Pe.Option,{value:"dark",children:e("settings.mermaidTab.themeOptions.dark")}),r.jsx(Pe.Option,{value:"forest",children:e("settings.mermaidTab.themeOptions.forest")}),r.jsx(Pe.Option,{value:"base",children:e("settings.mermaidTab.themeOptions.base")})]})})})}),r.jsxs(vl,{type:"secondary",style:{display:"block",marginTop:"8px"},children:[r.jsx("strong",{children:e("settings.mermaidTab.themeDescriptionsTitle")}),r.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.default"),r.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.neutral"),r.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.dark"),r.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.forest"),r.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.base")]})]}),r.jsxs(ee,{title:e("settings.mermaidTab.globalCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:[r.jsxs(Gt,{gutter:16,children:[r.jsx(Oe,{span:12,children:r.jsx(Z.Item,{name:"fontSize",label:r.jsxs(X,{children:[e("settings.mermaidTab.fontSizeLabel"),r.jsx(ke,{title:e("settings.mermaidTab.fontSizeTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:10,max:32,step:1,style:{width:"100%"},addonAfter:"px"})})}),r.jsx(Oe,{span:12,children:r.jsx(Z.Item,{name:"defaultScale",label:r.jsxs(X,{children:[e("settings.mermaidTab.defaultZoomLabel"),r.jsx(ke,{title:e("settings.mermaidTab.defaultZoomTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:.1,max:3,step:.1,style:{width:"100%"}})})})]}),r.jsx(Z.Item,{name:"useMaxWidth",label:r.jsxs(X,{children:[e("settings.mermaidTab.responsiveWidthLabel"),r.jsx(ke,{title:e("settings.mermaidTab.responsiveWidthTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),valuePropName:"checked",children:r.jsx(it,{})})]}),r.jsx(ee,{title:e("settings.mermaidTab.flowchartCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsxs(Gt,{gutter:16,children:[r.jsx(Oe,{span:8,children:r.jsx(Z.Item,{name:"flowchartNodeSpacing",label:r.jsxs(X,{children:[e("settings.mermaidTab.flowchartNodeSpacingLabel"),r.jsx(ke,{title:e("settings.mermaidTab.flowchartNodeSpacingTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:20,max:200,step:10,style:{width:"100%"}})})}),r.jsx(Oe,{span:8,children:r.jsx(Z.Item,{name:"flowchartRankSpacing",label:r.jsxs(X,{children:[e("settings.mermaidTab.flowchartRankSpacingLabel"),r.jsx(ke,{title:e("settings.mermaidTab.flowchartRankSpacingTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:20,max:200,step:10,style:{width:"100%"}})})}),r.jsx(Oe,{span:8,children:r.jsx(Z.Item,{name:"flowchartCurve",label:r.jsxs(X,{children:[e("settings.mermaidTab.flowchartCurveTypeLabel"),r.jsx(ke,{title:e("settings.mermaidTab.flowchartCurveTypeTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsxs(Pe,{children:[r.jsx(Pe.Option,{value:"basis",children:e("settings.mermaidTab.flowchartCurveOptions.basis")}),r.jsx(Pe.Option,{value:"linear",children:e("settings.mermaidTab.flowchartCurveOptions.linear")}),r.jsx(Pe.Option,{value:"cardinal",children:e("settings.mermaidTab.flowchartCurveOptions.cardinal")})]})})})]})}),r.jsx(ee,{title:e("settings.mermaidTab.sequenceCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsxs(Gt,{gutter:16,children:[r.jsx(Oe,{span:6,children:r.jsx(Z.Item,{name:"sequenceActorMargin",label:r.jsxs(X,{children:[e("settings.mermaidTab.sequenceActorMarginLabel"),r.jsx(ke,{title:e("settings.mermaidTab.sequenceActorMarginTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:20,max:200,step:10,style:{width:"100%"}})})}),r.jsx(Oe,{span:6,children:r.jsx(Z.Item,{name:"sequenceMessageMargin",label:r.jsxs(X,{children:[e("settings.mermaidTab.sequenceMessageMarginLabel"),r.jsx(ke,{title:e("settings.mermaidTab.sequenceMessageMarginTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:10,max:100,step:5,style:{width:"100%"}})})}),r.jsx(Oe,{span:6,children:r.jsx(Z.Item,{name:"sequenceWidth",label:r.jsxs(X,{children:[e("settings.mermaidTab.sequenceActorWidthLabel"),r.jsx(ke,{title:e("settings.mermaidTab.sequenceActorWidthTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:100,max:300,step:10,style:{width:"100%"}})})}),r.jsx(Oe,{span:6,children:r.jsx(Z.Item,{name:"sequenceHeight",label:r.jsxs(X,{children:[e("settings.mermaidTab.sequenceActorHeightLabel"),r.jsx(ke,{title:e("settings.mermaidTab.sequenceActorHeightTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:40,max:150,step:5,style:{width:"100%"}})})})]})}),r.jsx(ee,{title:e("settings.mermaidTab.ganttCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsxs(Gt,{gutter:16,children:[r.jsx(Oe,{span:12,children:r.jsx(Z.Item,{name:"ganttBarHeight",label:r.jsxs(X,{children:[e("settings.mermaidTab.ganttBarHeightLabel"),r.jsx(ke,{title:e("settings.mermaidTab.ganttBarHeightTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:10,max:50,step:5,style:{width:"100%"},addonAfter:"px"})})}),r.jsx(Oe,{span:12,children:r.jsx(Z.Item,{name:"ganttTopPadding",label:r.jsxs(X,{children:[e("settings.mermaidTab.ganttTopPaddingLabel"),r.jsx(ke,{title:e("settings.mermaidTab.ganttTopPaddingTooltip"),children:r.jsx(At,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(rt,{min:20,max:100,step:10,style:{width:"100%"}})})})]})}),r.jsx(X,{children:r.jsx(Y,{icon:r.jsx(dx,{}),onClick:l,children:e("settings.mermaidTab.resetToDefaults")})}),r.jsx(Rt,{}),r.jsx(ee,{title:e("settings.mermaidTab.previewTitle"),styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsx(vl,{type:"secondary",children:e("settings.mermaidTab.previewDescription")})})]})]})},z_=m.lazy(()=>Dt(()=>import("./index-BvEtlBh_.js"),__vite__mapDeps([0,1,2,3,4,5,6,7]),import.meta.url)),{Text:bn}=le,{useToken:N_}=he,B_=({promptEnhancement:e,onPromptEnhancementChange:t,mermaidEnhancementEnabled:s,taskEnhancementEnabled:n,showCopilotConclusionWithOptionsEnhancement:o,copilotConclusionWithOptionsEnhancementEnabled:a,onMermaidToggle:i,onTaskToggle:l,onCopilotConclusionWithOptionsToggle:c,onSaveEnhancement:d})=>{const{t:u}=ne(),{token:h}=N_(),p=h.marginLG;return r.jsxs(G,{vertical:!0,gap:p,children:[r.jsx(ee,{size:"small",className:"lotus-settings-card",children:r.jsx(m.Suspense,{fallback:r.jsx(ps,{size:"small"}),children:r.jsx(z_,{})})}),r.jsx(ee,{size:"small",className:"lotus-settings-card",children:r.jsxs(X,{direction:"vertical",size:h.marginXS,style:{width:"100%"},children:[r.jsx(bn,{strong:!0,children:u("settings.promptsTab.title")}),r.jsxs(G,{align:"center",gap:h.marginSM,children:[r.jsx(bn,{strong:!0,children:u("settings.promptsTab.mermaidEnhancement")}),r.jsx(it,{checked:s,onChange:i})]}),r.jsxs(G,{align:"center",gap:h.marginSM,children:[r.jsx(bn,{strong:!0,children:u("settings.promptsTab.taskListRules")}),r.jsx(it,{checked:n,onChange:l})]}),o&&r.jsxs(X,{direction:"vertical",size:h.marginXXS,style:{width:"100%"},children:[r.jsxs(G,{align:"center",gap:h.marginSM,children:[r.jsx(bn,{strong:!0,children:u("settings.promptsTab.copilotConclusionWithOptionsBeforeFinish")}),r.jsx(it,{checked:a,onChange:c})]}),r.jsx(bn,{type:"secondary",style:{fontSize:h.fontSizeSM},children:u("settings.promptsTab.copilotConclusionWithOptionsBeforeFinishDescription",{defaultValue:y_()})})]}),r.jsx(me.TextArea,{rows:6,placeholder:u("settings.promptsTab.enhancementPlaceholder"),value:e,onChange:g=>t(g.target.value)}),r.jsx(G,{justify:"flex-end",children:r.jsx(Y,{type:"primary",onClick:d,children:u("settings.promptsTab.saveEnhancement")})}),r.jsx(bn,{type:"secondary",style:{fontSize:h.fontSizeSM},children:u("settings.promptsTab.description")})]})}),s&&r.jsx(ns,{size:"small",items:[{key:"mermaid",label:r.jsx(bn,{strong:!0,children:u("settings.mermaidTab.title")}),children:r.jsx(F_,{})}]})]})},Yd="bodhi_onboarding_complete",W_=()=>localStorage.getItem(Yd)==="true",U_=()=>localStorage.setItem(Yd,"true"),q_=()=>localStorage.removeItem(Yd),H_=["new-session","task-templates","model-picker","sidebar","open-settings"],Y_=()=>{const e={};for(const t of H_)e[t]=document.querySelector(`[data-tour-id="${t}"]`);return e},X_=({disabled:e=!1})=>{const{t}=ne(),[s,n]=m.useState(!1),[o,a]=m.useState(null);m.useEffect(()=>{if(e||W_())return;const c=setTimeout(()=>{const d=Y_();a(d),n(!0)},800);return()=>clearTimeout(c)},[e]);const i=m.useMemo(()=>[{title:t("onboarding.welcome.title"),description:t("onboarding.welcome.description"),target:null},{title:t("onboarding.newSession.title"),description:t("onboarding.newSession.description"),target:(o==null?void 0:o["new-session"])??void 0},{title:t("onboarding.taskTemplates.title"),description:t("onboarding.taskTemplates.description"),target:(o==null?void 0:o["task-templates"])??void 0},{title:t("onboarding.modelPicker.title"),description:t("onboarding.modelPicker.description"),target:(o==null?void 0:o["model-picker"])??void 0},{title:t("onboarding.sidebar.title"),description:t("onboarding.sidebar.description"),target:(o==null?void 0:o.sidebar)??void 0},{title:t("onboarding.settings.title"),description:t("onboarding.settings.description"),target:(o==null?void 0:o["open-settings"])??void 0}],[t,o]),l=()=>{U_(),n(!1)};return r.jsx(ux,{open:s,onClose:l,steps:i})},{Text:vs}=le,{useToken:V_}=he,K_=({autoGenerateTitles:e,isUpdatingAutoTitlePreference:t,onAutoTitleToggle:s,themeMode:n,onThemeModeChange:o,vdiSafeMode:a,onVdiSafeModeToggle:i,onClearLocalStorage:l,onResetApp:c,isResetting:d,darkModeKey:u})=>{const{t:h}=ne(),{token:p}=V_();return r.jsx(ee,{size:"small",className:"lotus-settings-card",children:r.jsxs(X,{direction:"vertical",size:p.marginSM,style:{width:"100%"},children:[r.jsxs(G,{align:"center",gap:p.marginSM,children:[r.jsx(vs,{strong:!0,children:h("settings.appTab.autoGenerateTitle")}),r.jsx(it,{checked:e,loading:t,onChange:s})]}),r.jsx(vs,{type:"secondary",style:{fontSize:p.fontSizeSM},children:h("settings.appTab.autoGenerateTitleDesc")}),r.jsxs(G,{align:"center",justify:"space-between",gap:p.marginSM,children:[r.jsx(vs,{strong:!0,children:h("settings.appTab.runningVersion","Running version")}),r.jsxs(vs,{code:!0,"data-testid":"settings-app-version",children:["v",xd]})]}),r.jsx(vs,{type:"secondary",style:{fontSize:p.fontSizeSM},children:h("settings.appTab.runningVersionDesc","This is the currently running Lotus frontend version.")}),r.jsxs(G,{align:"center",gap:p.marginSM,children:[r.jsx(vs,{strong:!0,children:h("settings.appTab.darkMode")}),r.jsx(it,{"data-testid":"dark-mode-toggle",checked:n==="dark",onChange:g=>{const y=g?"dark":"light";o(y),localStorage.setItem(u,y)}})]}),r.jsxs(G,{align:"center",gap:p.marginSM,children:[r.jsx(vs,{strong:!0,children:h("settings.appTab.vdiSafeMode","Graphics compatibility mode")}),r.jsx(it,{"data-testid":"vdi-safe-mode-toggle",checked:a,onChange:i})]}),r.jsx(vs,{type:"secondary",style:{fontSize:p.fontSizeSM},children:h("settings.appTab.vdiSafeModeDesc","Disables blur and glass effects that can break dropdowns and hover overlays in some virtual desktop, remote, or graphics-constrained environments.")}),r.jsx(Y,{block:!0,icon:r.jsx(nd,{}),onClick:()=>{q_(),window.location.reload()},children:h("settings.appTab.resetStepReplayGuide")}),r.jsx(mi,{title:h("settings.appTab.clearLocalStorageTitle"),description:h("settings.appTab.clearLocalStorageDescription"),onConfirm:l,okText:h("settings.appTab.confirmClear"),cancelText:h("settings.appTab.cancel"),placement:"top",children:r.jsx(Y,{danger:!0,block:!0,icon:r.jsx(dn,{}),children:h("settings.appTab.clearLocalStorageButton")})}),r.jsx(Rt,{style:{margin:`${p.marginSM}px 0`}}),r.jsxs(G,{align:"center",gap:p.marginSM,children:[r.jsx(ua,{style:{color:p.colorError}}),r.jsx(vs,{strong:!0,style:{color:p.colorError},children:h("settings.appTab.dangerZone")})]}),r.jsx(vs,{type:"secondary",style:{fontSize:p.fontSizeSM},children:h("settings.appTab.dangerDescription")}),r.jsx(mi,{title:h("settings.appTab.resetApplicationTitle"),description:r.jsxs("div",{children:[r.jsx("p",{children:h("settings.appTab.resetApplicationIntro")}),r.jsxs("ul",{style:{margin:0,paddingLeft:16},children:[r.jsx("li",{children:h("settings.appTab.resetStepDeleteAllSessions")}),r.jsx("li",{children:h("settings.appTab.resetStepClearStorage")}),r.jsx("li",{children:h("settings.appTab.resetStepResetConfig")}),r.jsx("li",{children:h("settings.appTab.resetStepSetupFlow")}),r.jsx("li",{children:h("settings.appTab.resetStepReload")})]})]}),onConfirm:c,okText:h("settings.appTab.resetConfirm"),cancelText:h("settings.appTab.cancel"),placement:"top",okButtonProps:{danger:!0},children:r.jsx(Y,{"data-testid":"reset-to-defaults",danger:!0,block:!0,type:"primary",icon:r.jsx(yf,{}),loading:d,children:h("settings.appTab.resetButton")})})]})})},{Text:xn}=le,{useToken:G_}=he,xm=[{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,}"}],J_=(e,t,s)=>{if(!t)return{masked:e};if(s==="exact")return{masked:e.split(t).join("[MASKED]")};try{const n=new RegExp(t,"g");return{masked:e.replace(n,"[MASKED]")}}catch(n){return{masked:e,error:n instanceof Error?n.message:es.t("settings.keywordMaskingTab.invalidRegexPattern")}}},Q_=()=>{const{t:e}=ne(),{token:t}=G_(),[s,n]=m.useState([]),[o,a]=m.useState(!1),[i,l]=m.useState(null),[c,d]=m.useState(""),[u,h]=m.useState("exact"),[p,g]=m.useState(!0),[y,f]=m.useState(),[v,b]=m.useState("My token is sk-123"),x=m.useCallback(async()=>{try{a(!0);const P=await fs.getInstance().getKeywordMaskingConfig();n(P.entries)}catch(T){fe.error(e("settings.keywordMaskingTab.loadFailed")),console.error(T)}finally{a(!1)}},[e]);m.useEffect(()=>{x()},[x]);const _=async T=>{try{const P=fs.getInstance(),S=await P.validateKeywordEntries(T);if(!S.valid&&S.errors){const $=S.errors.map(I=>`Entry ${I.index+1}: ${I.message}`).join("; ");return fe.error(`${e("settings.keywordMaskingTab.validationFailedPrefix")}: ${$}`),!1}const L=await P.updateKeywordMaskingConfig(T);return n(L.entries),fe.success(e("settings.keywordMaskingTab.saveSuccess")),!0}catch(P){return fe.error(P instanceof Error?P.message:e("settings.keywordMaskingTab.saveFailed")),!1}},w=async()=>{const T={pattern:"",match_type:"exact",enabled:!0},P=[...s,T];n(P),l(P.length-1),d(""),h("exact"),g(!0),f(void 0)},k=T=>{const P=s[T];l(T),d(P.pattern),h(P.match_type),g(P.enabled),f(void 0)},C=async()=>{if(i===null)return;if(!c.trim()){fe.error(e("settings.keywordMaskingTab.patternRequired"));return}const T=[...s];T[i]={pattern:c.trim(),match_type:u,enabled:p},await _(T)&&l(null)},E=()=>{var T;i!==null&&!((T=s[i])!=null&&T.pattern)&&n(s.filter((P,S)=>S!==i)),l(null)},j=async T=>{const P=s.filter((S,L)=>L!==T);await _(P)},R=async(T,P)=>{const S=[...s];S[T]={...S[T],enabled:P},await _(S)},M=J_(v,c,u);return r.jsx(ee,{className:"lotus-settings-card",title:e("settings.keywordMaskingTab.title"),extra:r.jsx(Y,{"data-testid":"add-keyword",type:"primary",icon:r.jsx(Us,{}),onClick:w,loading:o,children:e("settings.keywordMaskingTab.addKeyword")}),children:r.jsxs(X,{direction:"vertical",style:{width:"100%"},size:"large",children:[r.jsx(xn,{type:"secondary",children:e("settings.keywordMaskingTab.description")}),r.jsx(nt,{loading:o,dataSource:s,locale:{emptyText:e("settings.keywordMaskingTab.empty")},renderItem:(T,P)=>r.jsx(nt.Item,{style:{backgroundColor:t.colorFillAlter,marginBottom:8,borderRadius:t.borderRadius,padding:12},actions:i===P?[r.jsx(Y,{"data-testid":"save-keyword",type:"primary",icon:r.jsx(Di,{}),onClick:C,"aria-label":e("settings.keywordMaskingTab.save")},"save"),r.jsx(Y,{onClick:E,children:e("settings.keywordMaskingTab.cancel")},"cancel")]:[r.jsx(Y,{icon:r.jsx(ca,{}),onClick:()=>k(P),"aria-label":e("settings.keywordMaskingTab.edit")},"edit"),r.jsx(Y,{"data-testid":`delete-keyword-${P}`,danger:!0,icon:r.jsx(dn,{}),onClick:()=>j(P),"aria-label":e("settings.keywordMaskingTab.delete")},"delete")],children:r.jsx(G,{vertical:!0,style:{width:"100%"},gap:8,children:i===P?r.jsxs(r.Fragment,{children:[r.jsx(me,{"data-testid":"keyword-pattern-input",placeholder:e("settings.keywordMaskingTab.patternPlaceholder"),value:c,onChange:S=>d(S.target.value),autoFocus:!0}),r.jsxs(G,{gap:8,align:"center",wrap:"wrap",children:[r.jsx(Pe,{"data-testid":"keyword-examples-select","aria-label":e("settings.keywordMaskingTab.examples"),placeholder:e("settings.keywordMaskingTab.examples"),value:y,onChange:S=>{f(S);const L=xm.find($=>$.value===S);L&&(d(L.pattern),h(L.match_type))},options:xm.map(S=>({value:S.value,label:e(S.labelKey)})),style:{minWidth:220}}),r.jsx(Pe,{value:u,onChange:h,options:[{value:"exact",label:e("settings.keywordMaskingTab.exactMatch")},{value:"regex",label:e("settings.keywordMaskingTab.regexPattern")}],style:{width:150}}),r.jsx(it,{checked:p,onChange:g})]}),r.jsxs(G,{vertical:!0,gap:6,children:[r.jsx(xn,{type:"secondary",children:e("settings.keywordMaskingTab.sampleText")}),r.jsx(me,{placeholder:e("settings.keywordMaskingTab.sampleTextPlaceholder"),value:v,onChange:S=>b(S.target.value)}),r.jsx(xn,{type:"secondary",children:e("settings.keywordMaskingTab.maskedPreview")}),r.jsx(me,{readOnly:!0,value:M.masked,status:M.error?"error":void 0}),M.error&&r.jsx(xn,{type:"danger",children:M.error})]})]}):r.jsxs(G,{justify:"space-between",align:"center",children:[r.jsxs(G,{vertical:!0,gap:4,children:[r.jsx(xn,{strong:!0,children:T.pattern||e("settings.keywordMaskingTab.emptyPattern")}),r.jsxs(G,{gap:8,children:[r.jsx(xn,{type:"secondary",style:{fontSize:12},children:T.match_type==="regex"?e("settings.keywordMaskingTab.regexPattern"):e("settings.keywordMaskingTab.exactMatch")}),!T.enabled&&r.jsx(xn,{type:"warning",style:{fontSize:12},children:e("settings.keywordMaskingTab.disabled")})]})]}),r.jsx(it,{checked:T.enabled,onChange:S=>R(P,S),size:"small"})]})})})})]})})},{Text:tr,Paragraph:Z_}=le,e0=/^[A-Za-z_][A-Za-z0-9_]*$/,t0=()=>{const{t:e}=ne(),[t,s]=m.useState([]),[n,o]=m.useState(!1),[a,i]=m.useState(!1),[l,c]=m.useState(null),[d]=Z.useForm(),u=m.useCallback(async()=>{o(!0);try{const b=await It.getEnvVars();s(b.entries)}catch{fe.error(e("settings.envVars.fetchError","Failed to load environment variables"))}finally{o(!1)}},[e]);m.useEffect(()=>{u()},[u]);const h=async b=>{var _;const x={name:b.name.trim(),value:b.value,secret:b.secret??!1,description:((_=b.description)==null?void 0:_.trim())||void 0};try{const w=await It.upsertEnvVar(x);s(w.entries),fe.success(l?e("settings.envVars.updated","Variable updated"):e("settings.envVars.created","Variable created")),f()}catch(w){fe.error((w instanceof Error?w.message:void 0)||e("settings.envVars.saveError","Failed to save variable"))}},p=async b=>{try{const x=await It.deleteEnvVar(b);s(x.entries),fe.success(e("settings.envVars.deleted","Variable deleted"))}catch(x){fe.error((x instanceof Error?x.message:void 0)||e("settings.envVars.deleteError","Failed to delete variable"))}},g=()=>{c(null),d.resetFields(),d.setFieldsValue({secret:!1}),i(!0)},y=b=>{c(b.name),d.setFieldsValue({name:b.name,value:"",secret:b.secret,description:b.description??""}),i(!0)},f=()=>{i(!1),c(null),d.resetFields()},v=[{title:e("settings.envVars.name","Name"),dataIndex:"name",key:"name",render:b=>r.jsx(tr,{code:!0,children:b})},{title:e("settings.envVars.value","Value"),dataIndex:"value",key:"value",render:(b,x)=>x.secret?r.jsxs(tr,{type:"secondary",children:[r.jsx(lu,{style:{marginRight:4}}),x.has_value?"••••••••":e("settings.envVars.notSet","(not set)")]}):r.jsx(tr,{children:b||r.jsx(tr,{type:"secondary",children:e("settings.envVars.empty","(empty)")})})},{title:e("settings.envVars.type","Type"),key:"secret",width:100,render:(b,x)=>x.secret?r.jsx(oe,{color:"warning",icon:r.jsx(lu,{}),children:e("settings.envVars.secret","Secret")}):r.jsx(oe,{color:"processing",children:e("settings.envVars.plain","Plain")})},{title:e("settings.envVars.descriptionCol","Description"),dataIndex:"description",key:"description",ellipsis:!0,render:b=>b?r.jsx(tr,{type:"secondary",children:b}):r.jsx(tr,{type:"secondary",italic:!0,children:"—"})},{title:e("settings.envVars.actions","Actions"),key:"actions",width:120,render:(b,x)=>r.jsxs(X,{size:"small",children:[r.jsx(Y,{type:"text",size:"small",icon:r.jsx(ca,{}),onClick:()=>y(x),"aria-label":e("settings.envVars.edit","Edit")}),r.jsx(mi,{title:e("settings.envVars.deleteConfirm","Delete this variable?"),onConfirm:()=>p(x.name),okText:e("settings.envVars.yes","Yes"),cancelText:e("settings.envVars.no","No"),children:r.jsx(Y,{type:"text",size:"small",danger:!0,icon:r.jsx(dn,{}),"aria-label":e("settings.envVars.delete","Delete")})})]})}];return r.jsxs("div",{style:{maxWidth:900},children:[r.jsxs(ee,{className:"lotus-settings-card",title:e("settings.envVars.title","Environment Variables"),extra:r.jsx(Y,{type:"primary",icon:r.jsx(Us,{}),onClick:g,children:e("settings.envVars.addButton","Add Variable")}),children:[r.jsx(Z_,{type:"secondary",style:{marginBottom:16},children:e("settings.envVars.description","Variables are injected into Bash tool processes. Secret variables are encrypted at rest.")}),r.jsx(qs,{dataSource:t,columns:v,rowKey:"name",size:"small",pagination:!1,loading:n,locale:{emptyText:e("settings.envVars.noVars","No environment variables configured")}})]}),r.jsx(Lt,{title:l?e("settings.envVars.editTitle","Edit Variable"):e("settings.envVars.addTitle","Add Environment Variable"),open:a,onCancel:f,onOk:()=>d.submit(),okText:e("settings.envVars.save","Save"),cancelText:e("settings.envVars.cancel","Cancel"),destroyOnClose:!0,children:r.jsxs(Z,{form:d,layout:"vertical",onFinish:h,initialValues:{secret:!1},children:[r.jsx(Z.Item,{name:"name",label:e("settings.envVars.name","Name"),rules:[{required:!0,message:e("settings.envVars.nameRequired","Variable name is required")},{pattern:e0,message:e("settings.envVars.nameInvalid","Must start with a letter or underscore, followed by letters, digits, or underscores")}],children:r.jsx(me,{placeholder:"GITHUB_TOKEN",disabled:l!==null,autoFocus:l===null})}),r.jsx(Z.Item,{name:"value",label:e("settings.envVars.value","Value"),rules:[{required:l===null,message:e("settings.envVars.valueRequired","Value is required for new variables")}],extra:l?e("settings.envVars.valueEditHint","Leave empty to keep the existing value"):void 0,children:r.jsx(me.Password,{placeholder:l?e("settings.envVars.valuePlaceholderEdit","Enter new value or leave empty"):e("settings.envVars.valuePlaceholder","Enter value"),visibilityToggle:!0})}),r.jsx(Z.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:r.jsx(it,{})}),r.jsx(Z.Item,{name:"description",label:e("settings.envVars.descriptionField","Description"),children:r.jsx(me,{placeholder:e("settings.envVars.descriptionPlaceholder","Optional description")})})]})})]})},An=class An{constructor(){}static getInstance(){return An.instance||(An.instance=new An),An.instance}async listWorkflows(){try{st("[WorkflowManager]","[WorkflowManagerService] Listing workflows");const t=await xe.get("bamboo/workflows"),s=Array.isArray(t)?t:[];return st("[WorkflowManager]","[WorkflowManagerService] Listed workflows:",s),s.map(n=>({name:String(n.name||""),filename:String(n.filename||(n.name||"workflow")+".md"),size:Number(n.size||0),modified_at:typeof n.modified_at=="string"?n.modified_at:void 0,source:"global"}))}catch(t){throw console.error("[WorkflowManagerService] Failed to list workflows:",t),t}}async getWorkflow(t){try{st("[WorkflowManager]","[WorkflowManagerService] Getting workflow: "+t);const s=await xe.get("bamboo/workflows/"+encodeURIComponent(t)),n=s!=null&&s.name?String(s.name):t,o={name:n,filename:String((s==null?void 0:s.filename)||n+".md"),size:Number((s==null?void 0:s.size)||0),modified_at:s==null?void 0:s.modified_at,source:"global"};return st("[WorkflowManager]","[WorkflowManagerService] Got workflow:",s),{name:n,content:String((s==null?void 0:s.content)||""),metadata:o}}catch(s){throw console.error("[WorkflowManagerService] Failed to get workflow "+t+":",s),kv(s)&&s.status===404?new Error("Workflow '"+t+"' not found"):s instanceof Error&&s.message.includes("404")?new Error("Workflow '"+t+"' not found"):s}}};He(An,"instance");let Ac=An;const{Text:Sl}=le,{TextArea:s0}=me,{useToken:n0}=he,r0=e=>!(!e||e.includes("/")||e.includes("\\")||e.includes("..")),o0=()=>{const{t:e}=ne(),{token:t}=n0(),[s,n]=fe.useMessage(),[o,a]=m.useState([]),[i,l]=m.useState(!1),[c,d]=m.useState(!1),[u,h]=m.useState(!1),[p,g]=m.useState(null),[y,f]=m.useState(""),[v,b]=m.useState(""),[x,_]=m.useState(!1),w=m.useMemo(()=>Ac.getInstance(),[]),k=m.useCallback(async()=>{l(!0);try{const M=await w.listWorkflows();return a(M),M}catch{return s.error(e("settings.workflowsTab.loadFailed")),[]}finally{l(!1)}},[s,e,w]);m.useEffect(()=>{k()},[k]);const C=m.useCallback(async M=>{g(M),f(M.name),_(!1),d(!0);try{const T=await w.getWorkflow(M.name);b(T.content??"")}catch{s.error(e("settings.workflowsTab.loadContentFailed")),b("")}finally{d(!1)}},[s,e,w]),E=()=>{g(null),f(""),b(""),_(!1)},j=m.useCallback(async()=>{if(!r0(y)){s.error(e("settings.workflowsTab.invalidName"));return}const M=o.some(T=>T.name===y);if(!p&&M){s.error(e("settings.workflowsTab.nameAlreadyExists"));return}h(!0);try{await fs.getInstance().saveWorkflow(y,v),s.success(e("settings.workflowsTab.saved")),_(!1);const S=(await k()).find(L=>L.name===y);S&&g(S)}catch(T){s.error(T instanceof Error?T.message:e("settings.workflowsTab.saveFailed"))}finally{h(!1)}},[v,y,k,s,p,e,o]),R=m.useCallback(async M=>{try{await fs.getInstance().deleteWorkflow(M.name),s.success(e("settings.workflowsTab.deleted")),(p==null?void 0:p.name)===M.name&&E(),await k()}catch(T){s.error(T instanceof Error?T.message:e("settings.workflowsTab.deleteFailed"))}},[k,s,p,e]);return r.jsxs("div",{style:{padding:"24px"},children:[n,r.jsxs(ee,{title:e("settings.workflowsTab.title"),extra:r.jsxs(X,{children:[r.jsx(Y,{icon:r.jsx(Ms,{}),onClick:k,loading:i,children:e("settings.workflowsTab.refresh")}),r.jsx(Y,{"data-testid":"create-workflow",icon:r.jsx(Us,{}),onClick:E,children:e("settings.workflowsTab.newWorkflow")}),r.jsx(Y,{"data-testid":"save-workflow",type:"primary",icon:r.jsx(Di,{}),onClick:j,loading:u,disabled:!x,children:e("settings.workflowsTab.save")})]}),children:[r.jsx(Sl,{type:"secondary",children:e("settings.workflowsTab.description")}),r.jsxs(G,{gap:t.marginLG,style:{marginTop:t.marginLG},children:[r.jsx("div",{style:{width:320,flexShrink:0},children:r.jsx(nt,{loading:i,dataSource:o,locale:{emptyText:e("settings.workflowsTab.empty")},renderItem:M=>r.jsx(nt.Item,{style:{cursor:"pointer",backgroundColor:(p==null?void 0:p.name)===M.name?t.colorFillSecondary:"transparent",borderRadius:t.borderRadius,padding:t.paddingSM},onClick:()=>C(M),actions:[r.jsx(Y,{"data-testid":`delete-workflow-${M.name}`,type:"text",danger:!0,size:"small",icon:r.jsx(dn,{}),onClick:T=>{T.stopPropagation(),R(M)},"aria-label":e("settings.workflowsTab.delete")},"delete")],children:r.jsxs(X,{direction:"vertical",size:0,children:[r.jsxs(Sl,{strong:!0,children:["/",M.name]}),r.jsx(Sl,{type:"secondary",style:{fontSize:12},children:M.filename})]})})})}),r.jsx("div",{style:{flex:1},children:r.jsxs(X,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx(me,{"data-testid":"workflow-name",placeholder:e("settings.workflowsTab.namePlaceholder"),value:y,onChange:M=>{f(M.target.value),_(!0)},disabled:!!p,prefix:r.jsx(ca,{})}),r.jsx(s0,{"data-testid":"workflow-content",placeholder:e("settings.workflowsTab.contentPlaceholder"),value:v,onChange:M=>{b(M.target.value),_(!0)},autoSize:{minRows:12},disabled:c})]})})]})]})]})};var ue=(e=>(e.Connecting="connecting",e.Ready="ready",e.Degraded="degraded",e.Stopped="stopped",e.Error="error",e))(ue||{});const va=6e4,Sa=3e4,aa=2e4,Ci=1e4,Vi=e=>({id:e,enabled:!0,transport:{type:"stdio",command:"",args:[],env:{},startup_timeout_ms:aa},request_timeout_ms:va,healthcheck_interval_ms:Sa,allowed_tools:[],denied_tools:[]}),a0=()=>({status:"stopped",tool_count:0,restart_count:0}),i0=e=>{switch(typeof e=="string"?e.trim().toLowerCase():""){case ue.Connecting:return ue.Connecting;case ue.Ready:return ue.Ready;case ue.Degraded:return ue.Degraded;case ue.Error:return ue.Error;case ue.Stopped:default:return ue.Stopped}},Ns=(e,t)=>{if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Number(e);if(Number.isFinite(s))return s}return t},l0=(e,t)=>{if(!e||typeof e!="object")return t;const s=e;if(s.type==="sse"){const a=Array.isArray(s.headers)?s.headers.map(i=>{if(!i||typeof i!="object")return null;const l=i;return typeof l.name!="string"||typeof l.value!="string"?null:{name:l.name,value:l.value}}).filter(i=>!!i):[];return{type:"sse",url:typeof s.url=="string"?s.url:"",headers:a,connect_timeout_ms:Ns(s.connect_timeout_ms,Ci)}}const n=Array.isArray(s.args)?s.args.filter(a=>typeof a=="string"):[],o=s.env&&typeof s.env=="object"?Object.entries(s.env):[];return{type:"stdio",command:typeof s.command=="string"?s.command:"",args:n,cwd:typeof s.cwd=="string"?s.cwd:void 0,env:o.reduce((a,[i,l])=>(typeof l=="string"&&(a[i]=l),a),{}),startup_timeout_ms:Ns(s.startup_timeout_ms,aa)}},c0=(e,t)=>{const s=Vi(e.id),n=t??{};return{...s,...n,id:e.id,name:typeof n.name=="string"?n.name:typeof e.name=="string"?e.name:void 0,enabled:typeof e.enabled=="boolean"?e.enabled:typeof n.enabled=="boolean"?n.enabled:!0,request_timeout_ms:Ns(n.request_timeout_ms,va),healthcheck_interval_ms:Ns(n.healthcheck_interval_ms,Sa),allowed_tools:Array.isArray(n.allowed_tools)?n.allowed_tools.filter(a=>typeof a=="string"):[],denied_tools:Array.isArray(n.denied_tools)?n.denied_tools.filter(a=>typeof a=="string"):[],reconnect:n.reconnect&&typeof n.reconnect=="object"?{enabled:typeof n.reconnect.enabled=="boolean"?n.reconnect.enabled:!0,initial_backoff_ms:Ns(n.reconnect.initial_backoff_ms,1e3),max_backoff_ms:Ns(n.reconnect.max_backoff_ms,3e4),max_attempts:Ns(n.reconnect.max_attempts,0)}:void 0,transport:l0(n.transport,s.transport)}},d0=e=>{const t=a0(),n=e.runtime??{},o=n.status??e.status;return{status:i0(o),last_error:typeof n.last_error=="string"?n.last_error:typeof e.last_error=="string"?e.last_error:void 0,connected_at:typeof n.connected_at=="string"?n.connected_at:void 0,disconnected_at:typeof n.disconnected_at=="string"?n.disconnected_at:void 0,tool_count:Ns(n.tool_count??e.tool_count,t.tool_count),restart_count:Ns(n.restart_count??e.restart_count,t.restart_count),last_ping_at:typeof n.last_ping_at=="string"?n.last_ping_at:void 0}},u0=e=>{const t=c0(e,e.config);return{id:e.id,name:typeof e.name=="string"?e.name:typeof t.name=="string"?t.name:e.id,enabled:typeof e.enabled=="boolean"?e.enabled:t.enabled,config:t,runtime:d0(e)}},m0=(e,t)=>`mcp__${e}__${t}`,h0=e=>{if(!e.startsWith("mcp__"))return null;const t=e.slice(5),s=t.indexOf("__");if(s<=0)return null;const n=t.slice(0,s),o=t.slice(s+2);return!n||!o?null:{server_id:n,original_name:o}},p0=(e,t,s=0)=>{if(!e||typeof e!="object")return null;const n=e,o=typeof n.alias=="string"?n.alias:typeof n.name=="string"&&n.name.startsWith("mcp__")?n.name:void 0,a=o&&typeof o=="string"?h0(o):null,i=(typeof n.server_id=="string"?n.server_id:void 0)??(typeof n.serverId=="string"?n.serverId:void 0)??(a==null?void 0:a.server_id)??t??"",l=(typeof n.original_name=="string"?n.original_name:void 0)??(typeof n.originalName=="string"?n.originalName:void 0)??(a==null?void 0:a.original_name)??(typeof n.name=="string"?n.name:void 0)??"",c=o??(i&&l?m0(i,l):""),d=typeof n.description=="string"?n.description:"",u=n,h="parameters"in u?u.parameters:"inputSchema"in u?u.inputSchema:"input_schema"in u?u.input_schema:void 0,p=c||l||`mcp_tool_${s}`;return{alias:p,server_id:i||"unknown",original_name:l||p,description:d,parameters:h}};class f0{async getServers(){const t=await pe.get("mcp/servers");return Array.isArray(t.servers)?t.servers.map(u0):[]}async addServer(t){return pe.post("mcp/servers",t)}async updateServer(t,s){const n={...s,id:t};return pe.put(`mcp/servers/${t}`,n)}async deleteServer(t){return pe.delete(`mcp/servers/${t}`)}async connectServer(t){return pe.post(`mcp/servers/${t}/connect`)}async disconnectServer(t){return pe.post(`mcp/servers/${t}/disconnect`)}async refreshTools(t){return pe.post(`mcp/servers/${t}/refresh`)}async getTools(t){const s=t?`mcp/servers/${t}/tools`:"mcp/tools",n=await pe.get(s);return(Array.isArray(n.tools)?n.tools:[]).map((a,i)=>p0(a,t,i)).filter(a=>!!a)}async importServers(t){return pe.post("mcp/servers/import",t)}}const Py=new f0,g0=5e3,Ls=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,vm=(e,t)=>`${e}:${t}`,y0=(e={})=>{const{service:t=Py,autoRefreshMs:s=g0,autoRefreshEnabled:n=!0}=e,[o,a]=m.useState([]),[i,l]=m.useState(null),[c,d]=m.useState({}),[u,h]=m.useState({}),[p,g]=m.useState({}),[y,f]=m.useState(!1),[v,b]=m.useState(!1),[x,_]=m.useState(!1),[w,k]=m.useState(null),C=m.useRef({}),E=m.useCallback(B=>{const K=new Set(B.map(z=>z.id)),F=B.map(z=>{const Te=C.current[z.id]??z.config,$e={...Te,id:z.id,name:Te.name??z.name};return C.current[z.id]=$e,{...z,name:z.name||$e.name||z.id,enabled:z.enabled??$e.enabled,config:$e}});return Object.keys(C.current).forEach(z=>{K.has(z)||delete C.current[z]}),F},[]),j=m.useCallback(async({silent:B=!1}={})=>{B||f(!0);try{const K=await t.getServers(),F=E(K);a(F),l(z=>{var de;return z&&F.some(Te=>Te.id===z)?z:((de=F[0])==null?void 0:de.id)??null}),k(null)}catch(K){throw k(Ls(K,"Failed to load MCP servers")),K}finally{B||f(!1)}},[E,t]),R=m.useCallback(async(B,K=!1)=>{if(!B)return[];if(!K&&c[B])return c[B];h(F=>({...F,[B]:!0}));try{const F=await t.getTools(B);return d(z=>({...z,[B]:F})),k(null),F}catch(F){throw k(Ls(F,"Failed to load MCP tools")),F}finally{h(F=>({...F,[B]:!1}))}},[t,c]),M=m.useCallback((B,K,F)=>{const z=vm(B,K);g(de=>({...de,[z]:F}))},[]),T=m.useCallback(async B=>{b(!0);try{await t.addServer(B),C.current[B.id]=B,await j()}catch(K){throw k(Ls(K,"Failed to add MCP server")),K}finally{b(!1)}},[j,t]),P=m.useCallback(async(B,K)=>{b(!0);try{const F={...K,id:B};await t.updateServer(B,F),C.current[B]=F,await j()}catch(F){throw k(Ls(F,"Failed to update MCP server")),F}finally{b(!1)}},[j,t]),S=m.useCallback(async B=>{M(B,"delete",!0);try{await t.deleteServer(B),d(K=>{const F={...K};return delete F[B],F}),delete C.current[B],await j()}catch(K){throw k(Ls(K,"Failed to delete MCP server")),K}finally{M(B,"delete",!1)}},[j,t,M]),L=m.useCallback(async B=>{M(B,"connect",!0);try{await t.connectServer(B),await j({silent:!0})}catch(K){throw k(Ls(K,"Failed to connect MCP server")),K}finally{M(B,"connect",!1)}},[j,t,M]),$=m.useCallback(async B=>{M(B,"disconnect",!0);try{await t.disconnectServer(B),await j({silent:!0})}catch(K){throw k(Ls(K,"Failed to disconnect MCP server")),K}finally{M(B,"disconnect",!1)}},[j,t,M]),I=m.useCallback(async B=>{M(B,"refresh",!0);try{await t.refreshTools(B),await R(B,!0),await j({silent:!0})}catch(K){throw k(Ls(K,"Failed to refresh MCP tools")),K}finally{M(B,"refresh",!1)}},[R,j,t,M]),W=m.useCallback(async()=>{_(!0);try{const B=o.map(K=>K.id);await Promise.all(B.map(async K=>{try{await t.refreshTools(K)}catch{}})),await j(),i&&await R(i,!0)}catch(B){throw k(Ls(B,"Failed to refresh MCP status")),B}finally{_(!1)}},[R,j,i,o,t]),A=m.useCallback(B=>{l(B)},[]),O=m.useCallback((B,K)=>!!p[vm(B,K)],[p]),D=m.useMemo(()=>i?c[i]??[]:[],[i,c]),H=m.useMemo(()=>i?!!u[i]:!1,[i,u]);return m.useEffect(()=>{j().catch(()=>{})},[j]),m.useEffect(()=>{if(!n||s<=0)return;const B=window.setInterval(()=>{j({silent:!0}).catch(()=>{})},s);return()=>{window.clearInterval(B)}},[n,s,j]),m.useEffect(()=>{i&&R(i).catch(()=>{})},[R,i]),{servers:o,selectedServerId:i,selectedServerTools:D,isLoadingServers:y,isMutatingConfig:v,isRefreshingAll:x,isSelectedServerToolsLoading:H,error:w,setSelectedServerId:A,refreshServers:j,addServer:T,updateServer:P,deleteServer:S,connectServer:L,disconnectServer:$,refreshServerTools:I,refreshAll:W,isServerActionLoading:O}},b0={[ue.Connecting]:"blue",[ue.Ready]:"green",[ue.Degraded]:"orange",[ue.Stopped]:"default",[ue.Error]:"red"},x0=e=>e===ue.Connecting||e===ue.Ready||e===ue.Degraded,v0=e=>{if(!e)return;const t=e.replace(/\s+/g," ").trim();if(t)return t.length>180?`${t.slice(0,180)}...`:t},S0=({servers:e,loading:t=!1,selectedServerId:s,onSelectServer:n,onEditServer:o,onDeleteServer:a,onConnectServer:i,onDisconnectServer:l,onRefreshTools:c,isServerActionLoading:d})=>{const{t:u}=ne(),{token:h}=he.useToken(),p=m.useMemo(()=>({[ue.Connecting]:u("settings.mcpTab.statusHelp.connecting"),[ue.Ready]:u("settings.mcpTab.statusHelp.ready"),[ue.Degraded]:u("settings.mcpTab.statusHelp.degraded"),[ue.Stopped]:u("settings.mcpTab.statusHelp.stopped"),[ue.Error]:u("settings.mcpTab.statusHelp.error")}),[u]),g=m.useMemo(()=>[{key:"name",title:u("settings.mcpServerTable.columns.name"),render:(y,f)=>f.name||f.id},{key:"transport",title:u("settings.mcpServerTable.columns.transportType"),render:(y,f)=>f.config.transport.type==="sse"?u("settings.mcpServerTable.transportOptions.sse"):u("settings.mcpServerTable.transportOptions.stdio"),width:140},{key:"status",title:u("settings.mcpServerTable.columns.status"),render:(y,f)=>{var w,k;const v=((w=f.runtime)==null?void 0:w.status)??ue.Stopped,b=v0((k=f.runtime)==null?void 0:k.last_error),x=p[v],_={[ue.Connecting]:u("settings.mcpTab.status.connecting"),[ue.Ready]:u("settings.mcpTab.status.ready"),[ue.Degraded]:u("settings.mcpTab.status.degraded"),[ue.Stopped]:u("settings.mcpTab.status.stopped"),[ue.Error]:u("settings.mcpTab.status.error")};return r.jsx(ke,{title:b?`${x} ${u("settings.mcpTab.statusLastError",{error:b})}`:x,children:r.jsx(oe,{color:v===ue.Stopped?void 0:b0[v],style:{marginInlineEnd:0,cursor:"help",...v===ue.Stopped?{background:h.colorFillSecondary,borderColor:h.colorBorderSecondary,color:h.colorTextSecondary}:void 0},children:_[v]})})},width:120},{key:"toolCount",title:u("settings.mcpServerTable.columns.toolCount"),render:(y,f)=>{var v;return((v=f.runtime)==null?void 0:v.tool_count)??0},width:100},{key:"actions",title:u("settings.mcpServerTable.columns.actions"),width:360,render:(y,f)=>{var x;const v=((x=f.runtime)==null?void 0:x.status)??ue.Stopped,b=x0(v);return r.jsxs(X,{size:h.marginXS,children:[r.jsx(Y,{size:"small",onClick:_=>{_.stopPropagation(),o==null||o(f)},children:u("settings.mcpServerTable.actions.edit")}),r.jsx(mi,{title:u("settings.mcpServerTable.deleteTitle"),description:u("settings.mcpServerTable.deleteDescription",{name:f.name||f.id}),onConfirm:()=>a==null?void 0:a(f),okText:u("settings.mcpServerTable.actions.delete"),okButtonProps:{danger:!0,loading:d==null?void 0:d(f.id,"delete")},children:r.jsx(Y,{size:"small",danger:!0,loading:d==null?void 0:d(f.id,"delete"),onClick:_=>_.stopPropagation(),children:u("settings.mcpServerTable.actions.delete")})}),b?r.jsx(Y,{size:"small",onClick:_=>{_.stopPropagation(),l==null||l(f)},loading:d==null?void 0:d(f.id,"disconnect"),children:u("settings.mcpServerTable.actions.disconnect")}):r.jsx(Y,{size:"small",type:"primary",ghost:!0,onClick:_=>{_.stopPropagation(),i==null||i(f)},loading:d==null?void 0:d(f.id,"connect"),children:u("settings.mcpServerTable.actions.connect")}),r.jsx(Y,{size:"small",onClick:_=>{_.stopPropagation(),c==null||c(f)},loading:d==null?void 0:d(f.id,"refresh"),children:u("settings.mcpServerTable.actions.refreshTools")})]})}}],[d,i,a,l,o,c,p,u,h.colorBorderSecondary,h.colorFillSecondary,h.colorTextSecondary,h.marginXS]);return r.jsx(qs,{rowKey:"id",columns:g,dataSource:e,loading:t,pagination:!1,locale:{emptyText:u("settings.mcpServerTable.empty")},onRow:y=>({onClick:()=>n==null?void 0:n(y.id),style:{cursor:n?"pointer":"default",backgroundColor:s===y.id?h.colorFillSecondary:void 0}})})},{Text:Sm}=le,{TextArea:w0}=me,wm=e=>{const t=e??Vi(""),s=t.transport,n=s.type==="stdio"?Object.entries(s.env??{}).map(([a,i])=>({key:a,value:i})):[],o=s.type==="sse"?s.headers.map(a=>({name:a.name,value:a.value})):[];return{id:t.id,name:t.name,enabled:t.enabled,transportType:s.type,command:s.type==="stdio"?s.command:void 0,args:s.type==="stdio"?s.args:[],envEntries:n,url:s.type==="sse"?s.url:void 0,headerEntries:o,requestTimeoutMs:t.request_timeout_ms||va,healthcheckIntervalMs:t.healthcheck_interval_ms||Sa,allowedTools:t.allowed_tools||[],deniedTools:t.denied_tools||[]}},_0=e=>e.reduce((t,s)=>{var o;const n=(o=s.key)==null?void 0:o.trim();return n&&(t[n]=s.value??""),t},{}),T0=e=>e.filter(t=>{var s;return(s=t.name)==null?void 0:s.trim()}).map(t=>{var s;return{name:((s=t.name)==null?void 0:s.trim())||"",value:t.value??""}}),_m=(e,t,s)=>{var u,h,p;const n=t==="edit"&&(s==null?void 0:s.id)||e.id,o=(u=e.name)==null?void 0:u.trim(),a=typeof e.requestTimeoutMs=="number"?e.requestTimeoutMs:(s==null?void 0:s.request_timeout_ms)??va,i=typeof e.healthcheckIntervalMs=="number"?e.healthcheckIntervalMs:(s==null?void 0:s.healthcheck_interval_ms)??Sa,l=Array.isArray(e.allowedTools)?e.allowedTools:(s==null?void 0:s.allowed_tools)??[],c=Array.isArray(e.deniedTools)?e.deniedTools:(s==null?void 0:s.denied_tools)??[],d=e.transportType==="sse"?{type:"sse",url:((h=e.url)==null?void 0:h.trim())||"",headers:T0(e.headerEntries||[]),connect_timeout_ms:(s==null?void 0:s.transport.type)==="sse"?s.transport.connect_timeout_ms??Ci:Ci}:{type:"stdio",command:((p=e.command)==null?void 0:p.trim())||"",args:e.args||[],env:_0(e.envEntries||[]),cwd:(s==null?void 0:s.transport.type)==="stdio"?s.transport.cwd:void 0,startup_timeout_ms:(s==null?void 0:s.transport.type)==="stdio"?s.transport.startup_timeout_ms??aa:aa};return{id:n,name:o||void 0,enabled:e.enabled,transport:d,request_timeout_ms:a,healthcheck_interval_ms:i,allowed_tools:l,denied_tools:c,reconnect:s==null?void 0:s.reconnect}},Tm=e=>JSON.stringify(e||Vi(""),null,2),wl=(e,t)=>{try{const s=JSON.parse(e);if(!s||typeof s!="object")return{valid:!1,error:t("settings.mcpServerForm.jsonMustBeObject")};const n=s;if(n.mcpServers&&typeof n.mcpServers=="object")return{valid:!1,error:t("settings.mcpServerForm.detectedBulkConfig")};const o=typeof n.id=="string"?n.id:"";if(!o.trim())return{valid:!1,error:t("settings.mcpServerForm.missingIdField")};if(n.transport&&typeof n.transport=="object"){const h=n;return!h.transport||typeof h.transport!="object"?{valid:!1,error:t("settings.mcpServerForm.missingTransportField")}:{valid:!0,config:h}}const a=typeof n.enabled=="boolean"?n.enabled:typeof n.disabled=="boolean"?!n.disabled:!0,i=typeof n.request_timeout_ms=="number"?n.request_timeout_ms:va,l=typeof n.healthcheck_interval_ms=="number"?n.healthcheck_interval_ms:Sa,c=Array.isArray(n.allowed_tools)?n.allowed_tools.filter(h=>typeof h=="string"):[],d=Array.isArray(n.denied_tools)?n.denied_tools.filter(h=>typeof h=="string"):[],u=typeof n.name=="string"?n.name:void 0;if(typeof n.url=="string"){const h=n.headers,p=Array.isArray(h)?h.map(y=>{if(!y||typeof y!="object")return null;const f=y,v=typeof f.name=="string"?f.name:"",b=typeof f.value=="string"?f.value:"";return v.trim()?{name:v,value:b}:null}).filter(y=>!!y):h&&typeof h=="object"?Object.entries(h).filter(([y])=>y.trim()).map(([y,f])=>({name:y,value:typeof f=="string"?f:""})):[],g=typeof n.connect_timeout_ms=="number"?n.connect_timeout_ms:Ci;return{valid:!0,config:{id:o,name:u,enabled:a,transport:{type:"sse",url:n.url,headers:p,connect_timeout_ms:g},request_timeout_ms:i,healthcheck_interval_ms:l,allowed_tools:c,denied_tools:d,reconnect:void 0}}}if(typeof n.command=="string"){const h=Array.isArray(n.args)?n.args.filter(f=>typeof f=="string"):[],p=n.env,g=p&&typeof p=="object"?Object.entries(p).reduce((f,[v,b])=>(typeof b=="string"&&(f[v]=b),f),{}):{},y=typeof n.startup_timeout_ms=="number"?n.startup_timeout_ms:aa;return{valid:!0,config:{id:o,name:u,enabled:a,transport:{type:"stdio",command:n.command,args:h,cwd:typeof n.cwd=="string"?n.cwd:void 0,env:g,startup_timeout_ms:y},request_timeout_ms:i,healthcheck_interval_ms:l,allowed_tools:c,denied_tools:d,reconnect:void 0}}}return{valid:!1,error:t("settings.mcpServerForm.missingTransportInfo")}}catch(s){return{valid:!1,error:t("settings.mcpServerForm.invalidJson",{message:s instanceof Error?s.message:t("settings.mcpServerForm.unknownError")})}}},k0=({open:e,mode:t,initialConfig:s,confirmLoading:n=!1,onCancel:o,onSubmit:a})=>{const{t:i}=ne(),[l]=Z.useForm(),[c,d]=m.useState("form"),[u,h]=m.useState(""),[p,g]=m.useState(null),y=m.useMemo(()=>wm(s),[s]),f=Z.useWatch("transportType",l)??"stdio";m.useEffect(()=>{e&&(l.setFieldsValue(y),h(Tm(s)),g(null),d("form"))},[l,y,s,e]);const v=()=>{l.resetFields(),h(""),g(null),o()},b=async()=>{if(c==="json"){const w=wl(u,i);if(!w.valid){g(w.error);return}g(null);try{await a(w.config),h("")}catch(k){console.error("MCP server JSON submission error:",k)}return}try{const w=await l.validateFields(),k=_m(w,t,s);await a(k),l.resetFields()}catch(w){console.error("MCP server form submission error:",w)}},x=w=>{h(w),p&&wl(w,i).valid&&g(null)},_=w=>{if(w==="json")try{const k=l.getFieldsValue(),C=_m(k,t,s);h(JSON.stringify(C,null,2))}catch{h(Tm(s))}else{const k=wl(u,i);k.valid&&l.setFieldsValue(wm(k.config))}d(w),g(null)};return r.jsxs(Lt,{title:i(t==="edit"?"settings.mcpServerForm.editTitle":"settings.mcpServerForm.addTitle"),open:e,onCancel:v,onOk:()=>{b()},okText:i("settings.mcpServerForm.save"),destroyOnClose:!0,confirmLoading:n,width:720,children:[r.jsx("div",{style:{marginBottom:16},children:r.jsxs(ts.Group,{value:c,onChange:w=>_(w.target.value),optionType:"button",buttonStyle:"solid",children:[r.jsxs(ts.Button,{value:"form",children:[r.jsx(mx,{})," ",i("settings.mcpServerForm.modeForm")]}),r.jsxs(ts.Button,{value:"json",children:[r.jsx(Li,{})," ",i("settings.mcpServerForm.modeJson")]})]})}),c==="json"&&p&&r.jsx(Xe,{type:"error",message:i("settings.mcpServerForm.jsonError"),description:p,showIcon:!0,style:{marginBottom:16},closable:!0,onClose:()=>g(null)}),c==="json"?r.jsx(w0,{value:u,onChange:w=>x(w.target.value),rows:20,style:{fontFamily:"monospace",fontSize:13},placeholder:JSON.stringify(Vi("example-server"),null,2)}):r.jsxs(Z,{layout:"vertical",form:l,preserve:!0,initialValues:y,children:[r.jsx(Z.Item,{name:"id",label:i("settings.mcpServerForm.serverId"),rules:[{required:!0,message:i("settings.mcpServerForm.serverIdRequired")},{pattern:/^[a-zA-Z0-9_-]+$/,message:i("settings.mcpServerForm.serverIdPatternError")}],children:r.jsx(me,{placeholder:"filesystem",disabled:t==="edit",autoComplete:"off"})}),r.jsx(Z.Item,{name:"name",label:i("settings.mcpServerForm.displayName"),children:r.jsx(me,{placeholder:"Filesystem MCP",autoComplete:"off"})}),r.jsx(Z.Item,{name:"enabled",label:i("settings.mcpServerForm.enabled"),valuePropName:"checked",extra:i("settings.mcpServerForm.enabledHelp"),children:r.jsx(it,{})}),r.jsx(Z.Item,{name:"transportType",label:i("settings.mcpServerForm.transportType"),rules:[{required:!0,message:i("settings.mcpServerForm.transportTypeRequired")}],children:r.jsx(Pe,{options:[{label:i("settings.mcpServerForm.transportOptions.stdio"),value:"stdio"},{label:i("settings.mcpServerForm.transportOptions.sse"),value:"sse"}]})}),f==="stdio"?r.jsxs(r.Fragment,{children:[r.jsx(Z.Item,{name:"command",label:i("settings.mcpServerForm.command"),rules:[{required:!0,message:i("settings.mcpServerForm.commandRequired")}],children:r.jsx(me,{placeholder:"npx",autoComplete:"off"})}),r.jsx(Z.Item,{name:"args",label:i("settings.mcpServerForm.arguments"),children:r.jsx(Pe,{mode:"tags",tokenSeparators:[","],placeholder:i("settings.mcpServerForm.argumentsPlaceholder"),open:!1})}),r.jsx(Z.List,{name:"envEntries",children:(w,{add:k,remove:C})=>r.jsxs(X,{direction:"vertical",style:{width:"100%"},children:[r.jsxs(X,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[r.jsx(Sm,{strong:!0,children:i("settings.mcpServerForm.envVars")}),r.jsx(Y,{icon:r.jsx(Us,{}),onClick:()=>k({key:"",value:""}),type:"dashed",children:i("settings.mcpServerForm.addEnv")})]}),w.map(E=>r.jsxs(X,{align:"baseline",style:{display:"flex"},children:[r.jsx(Z.Item,{...E,name:[E.name,"key"],rules:[{required:!0,message:i("settings.mcpServerForm.keyRequired")}],children:r.jsx(me,{placeholder:"MCP_ROOT",autoComplete:"off"})}),r.jsx(Z.Item,{...E,name:[E.name,"value"],children:r.jsx(me,{placeholder:"/Users/me/workspace",autoComplete:"off"})}),r.jsx(Y,{danger:!0,type:"text",icon:r.jsx(nc,{}),onClick:()=>C(E.name),"aria-label":i("settings.mcpServerForm.removeEnv","Remove environment variable")})]},E.key))]})})]}):r.jsxs(r.Fragment,{children:[r.jsx(Z.Item,{name:"url",label:i("settings.mcpServerForm.sseUrl"),rules:[{required:!0,message:i("settings.mcpServerForm.sseUrlRequired")},{validator:async(w,k)=>{if(k)try{new URL(k)}catch{throw new Error(i("settings.mcpServerForm.validUrlRequired"))}}}],children:r.jsx(me,{placeholder:"http://localhost:4000/sse",autoComplete:"off"})}),r.jsx(Z.List,{name:"headerEntries",children:(w,{add:k,remove:C})=>r.jsxs(X,{direction:"vertical",style:{width:"100%"},children:[r.jsxs(X,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[r.jsx(Sm,{strong:!0,children:i("settings.mcpServerForm.headers")}),r.jsx(Y,{icon:r.jsx(Us,{}),onClick:()=>k({name:"",value:""}),type:"dashed",children:i("settings.mcpServerForm.addHeader")})]}),w.map(E=>r.jsxs(X,{align:"baseline",style:{display:"flex"},children:[r.jsx(Z.Item,{...E,name:[E.name,"name"],rules:[{required:!0,message:i("settings.mcpServerForm.headerNameRequired")}],children:r.jsx(me,{placeholder:"Authorization",autoComplete:"off"})}),r.jsx(Z.Item,{...E,name:[E.name,"value"],children:r.jsx(me,{placeholder:"Bearer token",autoComplete:"off"})}),r.jsx(Y,{danger:!0,type:"text",icon:r.jsx(nc,{}),onClick:()=>C(E.name),"aria-label":i("settings.mcpServerForm.removeHeader","Remove header")})]},E.key))]})})]})]})]})},j0={maxLines:8,maxCharacters:500},on=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Zs=e=>typeof e=="string"?e:void 0,Mn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,km=e=>typeof e=="boolean"?e:void 0,Xd=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const s=JSON.parse(t);return on(s)?s:null}catch{return null}},Ey=e=>/\\u[0-9a-fA-F]{4}|\\n|\\t|\\r/.test(e)?e.replace(/\\u([0-9a-fA-F]{4})/g,(t,s)=>String.fromCharCode(parseInt(s,16))).replace(/\\n/g,`
|
|
113
113
|
`).replace(/\\t/g," ").replace(/\\r/g,"\r"):e,js=e=>Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>Ey(t).trim()).filter(Boolean):[],gt=e=>{if(typeof e!="string")return;const t=Ey(e).trim();return t.length>0?t:void 0},C0=e=>{if(!on(e))return;const t=gt(e.graph);if(t)return{title:gt(e.title),graph:t}},M0=e=>{if(!on(e))return;const t=gt(e.summary)??gt(e.conclusion);if(t)return{title:gt(e.title)||"Conclusion",summary:t,key_points:js(e.key_points),next_steps:js(e.next_steps),confidence:gt(e.confidence),mermaid:C0(e.mermaid)}},P0=e=>{const t=Xd(e);if(!t)return null;const s=gt(t.conclusion);return!s||t.type!=null&&t.type!=="conclusion"?null:{type:"conclusion",title:gt(t.title)||"Conclusion",conclusion:s,key_points:js(t.key_points),next_steps:js(t.next_steps),confidence:gt(t.confidence)}},E0=e=>{const t=Xd(e);if(!t)return null;const s=gt(t.question);if(!s)return null;const n=gt(t.status);return n&&n!=="awaiting_user_input"&&n!=="awaiting_permission_approval"?null:{question:s,options:js(t.options),allow_custom:typeof t.allow_custom=="boolean"?t.allow_custom:!0,conclusion:M0(t.conclusion)}},R0=e=>{var s;if(!e)return null;const t=[`## ${e.title}`,e.summary];if(e.confidence&&t.push(`**Confidence:** ${e.confidence}`),e.key_points.length>0&&t.push(["**Key points**",...e.key_points.map(n=>`- ${n}`)].join(`
|
|
114
114
|
`)),e.next_steps.length>0&&t.push(["**Next steps**",...e.next_steps.map((n,o)=>`${o+1}. ${n}`)].join(`
|
|
115
115
|
`)),(s=e.mermaid)!=null&&s.graph){const n=e.mermaid.title?`**${e.mermaid.title}**
|
|
@@ -149,7 +149,7 @@ ${e.mermaid.graph}
|
|
|
149
149
|
`," "]})}),r.jsx(Rt,{dashed:!0}),_e("openai"),Ce("openai")]});case"anthropic":return r.jsxs(r.Fragment,{children:[r.jsx(Z.Item,{name:["providers","anthropic","api_key"],label:e("settings.providerTab.anthropicApiKey"),rules:[{required:!0,message:e("settings.providerTab.anthropicApiKeyRequired")}],children:r.jsx(Ym,{placeholder:"sk-ant-...",prefix:r.jsx(ja,{})})}),r.jsx(Z.Item,{name:["providers","anthropic","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.anthropicBaseUrlHelp"),children:r.jsx(me,{placeholder:"https://api.anthropic.com/v1"})}),r.jsx(Z.Item,{name:["providers","anthropic","model"],label:e("settings.providerTab.defaultModel"),rules:[{required:!0,message:e("settings.providerTab.selectModelRequired")}],children:r.jsx(nr,{provider:"anthropic",disabled:$==="saving",placeholder:e("settings.providerTab.selectModel"),onChange:re=>Ge("anthropic",re)})}),r.jsx(Z.Item,{name:["providers","anthropic","max_tokens"],label:e("settings.providerTab.maxTokensOptional"),extra:e("settings.providerTab.maxTokensHelp"),children:r.jsx(me,{type:"number",placeholder:"4096",min:1,max:1e5})}),r.jsx(Rt,{dashed:!0}),_e("anthropic"),Ce("anthropic")]});case"gemini":return r.jsxs(r.Fragment,{children:[r.jsx(Z.Item,{name:["providers","gemini","api_key"],label:e("settings.providerTab.geminiApiKey"),rules:[{required:!0,message:e("settings.providerTab.geminiApiKeyRequired")}],children:r.jsx(Ym,{placeholder:"AIza...",prefix:r.jsx(ja,{})})}),r.jsx(Z.Item,{name:["providers","gemini","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.geminiBaseUrlHelp"),children:r.jsx(me,{placeholder:"https://generativelanguage.googleapis.com/v1beta"})}),r.jsx(Z.Item,{name:["providers","gemini","model"],label:e("settings.providerTab.defaultModel"),rules:[{required:!0,message:e("settings.providerTab.selectModelRequired")}],children:r.jsx(nr,{provider:"gemini",disabled:$==="saving",placeholder:e("settings.providerTab.selectModel"),onChange:re=>Ge("gemini",re)})}),r.jsx(Rt,{dashed:!0}),_e("gemini"),Ce("gemini")]});case"copilot":return r.jsxs(r.Fragment,{children:[r.jsxs(ee,{size:"small",style:{marginBottom:16},title:e("settings.providerTab.authStatusTitle"),extra:g?r.jsx(ps,{size:"small"}):h!=null&&h.authenticated?r.jsx(oe,{icon:r.jsx(Hs,{}),color:"success",children:e("settings.providerTab.authenticated")}):r.jsx(oe,{icon:r.jsx(rc,{}),color:"error",children:e("settings.providerTab.notAuthenticated")}),children:[(h==null?void 0:h.message)&&r.jsx(Cl,{type:"secondary",style:{marginBottom:16},children:h.message}),r.jsxs(X,{children:[h!=null&&h.authenticated?r.jsx(Y,{danger:!0,icon:r.jsx(px,{}),onClick:z,loading:f,children:e("settings.providerTab.logoutCopilot")}):r.jsx(Y,{type:"primary",icon:r.jsx(fx,{}),onClick:B,loading:f,children:e("settings.providerTab.authenticateCopilot")}),r.jsx(Y,{onClick:H,loading:g,children:e("settings.providerTab.refreshStatus")})]})]}),r.jsx(Z.Item,{name:["providers","copilot","headless_auth"],label:e("settings.providerTab.headlessAuth"),valuePropName:"checked",extra:e("settings.providerTab.headlessAuthHelp"),children:r.jsx(it,{})}),r.jsx(Z.Item,{name:["providers","copilot","model"],label:e("settings.providerTab.defaultModel"),rules:[{required:!0,message:e("settings.providerTab.selectModelRequired")}],children:r.jsx(nr,{provider:"copilot",disabled:$==="saving",placeholder:e("settings.providerTab.selectModel"),onChange:re=>Ge("copilot",re)})}),r.jsx(Z.Item,{name:["providers","copilot","responses_only_models"],label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:Xm(e),children:r.jsx(Pe,{mode:"tags",placeholder:'e.g. "gpt-5.3-codex", "gpt-5*"',tokenSeparators:[","," ",`
|
|
150
150
|
`," "]})}),r.jsx(Rt,{dashed:!0}),_e("copilot"),Ce("copilot"),r.jsxs(Cl,{type:"secondary",children:[e("settings.providerTab.copilotUsageTitle"),r.jsxs("ul",{style:{marginTop:8,marginBottom:0},children:[r.jsx("li",{children:e("settings.providerTab.copilotUsageStep1")}),r.jsx("li",{children:e("settings.providerTab.copilotUsageStep2")}),r.jsx("li",{children:e("settings.providerTab.copilotUsageStep3")})]})]})]});case"bodhi":return r.jsxs(r.Fragment,{children:[r.jsx(Z.Item,{name:["providers","bodhi","api_key"],label:"Bodhi API Key",rules:[{required:!0,message:"API key is required"}],children:r.jsx(me.Password,{"data-testid":"bodhi-api-key-input",placeholder:"bhi_sk_...",prefix:r.jsx(ja,{})})}),r.jsx(Z.Item,{name:["providers","bodhi","base_url"],label:"Base URL",extra:"Your Bodhi Server endpoint address",children:r.jsx(me,{placeholder:"http://localhost:8080"})}),r.jsx(Z.Item,{name:["providers","bodhi","target_provider"],label:"Target Provider",extra:"Which upstream provider to route through Bodhi",children:r.jsxs(Pe,{placeholder:"openai",allowClear:!0,children:[r.jsx(Pe.Option,{value:"openai",children:"OpenAI"}),r.jsx(Pe.Option,{value:"anthropic",children:"Anthropic"}),r.jsx(Pe.Option,{value:"gemini",children:"Gemini"})]})}),r.jsx(Z.Item,{name:["providers","bodhi","reasoning_effort"],label:"Reasoning Effort (optional)",children:r.jsxs(Pe,{placeholder:"Default",allowClear:!0,children:[r.jsx(Pe.Option,{value:"low",children:"Low"}),r.jsx(Pe.Option,{value:"medium",children:"Medium"}),r.jsx(Pe.Option,{value:"high",children:"High"}),r.jsx(Pe.Option,{value:"xhigh",children:"Extra High"}),r.jsx(Pe.Option,{value:"max",children:"Max"})]})}),r.jsx(Rt,{dashed:!0}),Ce("bodhi")]});default:return null}},qe=J=>{const re=U(J),V=jl[J];return r.jsxs(X,{size:"small",children:[r.jsx("span",{style:{fontWeight:500},children:V}),re?r.jsx(oe,{color:"success",style:{fontSize:11},children:e("settings.providerTab.authenticated")}):r.jsx(oe,{color:"default",style:{fontSize:11},children:e("settings.providerTab.providerNotConfigured")})]})};return r.jsxs(ee,{title:e("settings.providerTab.title"),loading:n&&!d,className:"lotus-settings-card",children:[r.jsx(Cl,{type:"secondary",children:e("settings.providerTab.description")}),r.jsx(Rt,{}),r.jsxs(Z,{form:s,layout:"vertical",onFinish:ht,disabled:n&&!d,children:[r.jsx(Z.Item,{name:"provider",label:e("settings.providerTab.activeProvider"),rules:[{required:!0,message:e("settings.providerTab.selectProviderRequired")}],children:r.jsx(Pe,{"data-testid":"provider-select",size:"large",children:Object.keys(jl).map(J=>r.jsx(Pe.Option,{value:J,children:jl[J]},J))})}),r.jsx(Rt,{}),r.jsxs("div",{style:{marginBottom:16},children:[r.jsx(Y,{icon:r.jsx(Ms,{}),onClick:de,loading:S,children:e(S?"settings.providerTab.fetchingAllModels":"settings.providerTab.fetchAllModels")}),$==="saving"&&r.jsx(ps,{size:"small",style:{marginLeft:8}}),$==="success"&&r.jsx(Hs,{style:{color:"var(--lotus-chart-secondary)",marginLeft:8}}),$==="error"&&r.jsx(ke,{title:W,children:r.jsx(rc,{style:{color:"var(--lotus-chart-danger)",marginLeft:8}})})]}),r.jsx(ns,{defaultActiveKey:Ba.filter(J=>U(J)),ghost:!0,style:{marginBottom:16},children:Ba.map(J=>r.jsx(ns.Panel,{header:qe(J),children:Ve(J)},J))}),r.jsx(Rt,{}),r.jsx(X,{size:"middle",children:r.jsx(Y,{"data-testid":"save-api-settings",type:"primary",htmlType:"submit",icon:r.jsx(Di,{}),loading:n||a,size:"large",children:e("settings.providerTab.saveAndApply")})})]}),r.jsx(ZT,{open:_,onCancel:()=>w(!1),onComplete:K,onCopyCode:F,completingAuth:k,copiedUserCode:R,deviceCodeInfo:b,timeRemaining:E,token:t})]})},{Text:Vm}=le,ak=({skill:e,disabled:t=!1,busy:s=!1,onToggleDisabled:n})=>{const{t:o}=ne(),{token:a}=he.useToken();return r.jsx(ee,{title:r.jsxs(X,{size:a.marginXS,wrap:!0,style:{width:"100%",justifyContent:"space-between"},children:[r.jsxs(X,{size:a.marginXS,wrap:!0,children:[r.jsx("span",{children:e.name}),t&&r.jsx(oe,{color:"default",children:o("components.skillManager.disabledTag")}),e.license&&r.jsxs(oe,{color:"processing",children:["License: ",e.license]})]}),n&&r.jsx(it,{checked:!t,loading:s,onChange:i=>n(e.id,!i),checkedChildren:o("components.skillManager.switchEnabled"),unCheckedChildren:o("components.skillManager.switchDisabled")})]}),styles:{body:{padding:a.paddingMD}},style:{opacity:t?.72:1},children:r.jsxs(X,{direction:"vertical",size:a.marginXS,style:{width:"100%"},children:[r.jsx(Vm,{type:"secondary",children:e.description}),e.compatibility&&r.jsxs(Vm,{type:"secondary",children:["Compatibility: ",e.compatibility]}),e.tool_refs.length>0&&r.jsx(X,{size:a.marginXXS,wrap:!0,children:e.tool_refs.map(i=>r.jsx(oe,{style:{background:a.colorFillSecondary,borderColor:a.colorBorderSecondary,color:a.colorText},children:i},i))})]})})},ik=3e4,lk=()=>{const{t:e}=ne(),t=ms(C=>C.config),s=ms(C=>C.loadConfig),n=ms(C=>C.saveConfig),[o,a]=m.useState([]),[i,l]=m.useState(!1),[c,d]=m.useState(null),[u,h]=m.useState(null),[p,g]=m.useState(""),[y,f]=m.useState(new Date),v=m.useMemo(()=>{var C;return new Set((((C=t==null?void 0:t.skills)==null?void 0:C.disabled)??[]).map(E=>E.trim()).filter(Boolean))},[t]),b=m.useCallback(async(C=!0)=>{l(!0),d(null);try{const[E]=await Promise.all([lc.listSkills({includeDisabled:!0},C),s({force:C})]);a(E.skills),f(new Date)}catch(E){const j=E instanceof Error?E.message:e("components.skillManager.loadFailed");d(j)}finally{l(!1)}},[s,e]);m.useEffect(()=>{b(!0);const C=setInterval(()=>{b(!0)},ik);return()=>clearInterval(C)},[b]),m.useEffect(()=>{const C=()=>{b(!0)};return window.addEventListener("focus",C),()=>window.removeEventListener("focus",C)},[b]);const x=m.useCallback(async()=>{await b(!0),fe.success(e("components.skillManager.skillsRefreshed"))},[b,e]);m.useEffect(()=>{c&&(fe.error(c),d(null))},[c]);const _=m.useCallback(async(C,E)=>{var j;h(C);try{const R=await s({force:!0}),M=((j=R==null?void 0:R.skills)==null?void 0:j.disabled)??[],T=Array.from(new Set((E?[...M,C]:M.filter(P=>P!==C)).map(P=>P.trim()).filter(Boolean))).sort();await n({...R??{},skills:{...(R==null?void 0:R.skills)??{},disabled:T}}),fe.success(e("components.skillManager.skillStateSaved"))}catch(R){fe.error(R instanceof Error?R.message:e("components.skillManager.saveFailed"))}finally{h(null)}},[s,n,e]),w=o.filter(C=>{const E=p.trim().toLowerCase();return!(E&&![C.name,C.description,C.license??"",C.compatibility??"",...C.tool_refs].join(" ").toLowerCase().includes(E))}),k=()=>{const E=new Date().getTime()-y.getTime(),j=Math.floor(E/1e3);if(j<5)return e("components.skillManager.justNow");if(j<60)return e("components.skillManager.secondsAgo",{count:j});const R=Math.floor(j/60);return R<60?e("components.skillManager.minutesAgo",{count:R}):y.toLocaleTimeString()};return r.jsx("div",{style:{padding:"24px"},children:r.jsxs(ee,{className:"lotus-settings-card",title:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[r.jsx("span",{children:e("components.skillManager.title")}),r.jsx(Y,{icon:r.jsx(Ms,{spin:i}),onClick:x,loading:i,size:"small",children:e("components.skillManager.refresh")}),r.jsx("span",{className:"lotus-settings-note",style:{fontSize:"12px",marginLeft:"auto"},children:e("components.skillManager.lastUpdated",{value:k()})})]}),children:[r.jsx("div",{className:"lotus-settings-note",style:{marginBottom:"16px"},children:e("components.skillManager.readOnlyHint")}),r.jsx("div",{className:"lotus-settings-note",style:{marginBottom:"16px"},children:e("components.skillManager.disabledHint")}),r.jsx(Gt,{style:{marginBottom:"24px"},children:r.jsx(me,{placeholder:e("components.skillManager.searchPlaceholder"),prefix:r.jsx(sa,{}),value:p,onChange:C=>g(C.target.value),allowClear:!0})}),r.jsx(ps,{spinning:i,children:w.length===0?r.jsx(kt,{description:e(p?"components.skillManager.noMatch":"components.skillManager.noSkillsFound")}):r.jsx(nt,{grid:{gutter:16,xs:1,sm:2,md:3,lg:3,xl:4},dataSource:w,renderItem:C=>r.jsx(nt.Item,{children:r.jsx(ak,{skill:C,disabled:v.has(C.id),busy:u===C.id,onToggleDisabled:_})})})})]})})},{Title:ck,Text:Ml,Paragraph:dk}=le,Km="model_limits",Fc="modelLimitsConfigs",Gm="defaultBudgetStrategy",Kt=1e3;function Jm(e){return[{vendor:"OpenAI (GPT-5)",model_pattern:"gpt-5.4-thinking",max_context_tokens:1e6,max_output_tokens:128e3,safety_margin:Kt,note:e("settings.modelLimits.defaults.gpt54")},{vendor:"OpenAI (GPT-5)",model_pattern:"gpt-5.3-codex",max_context_tokens:4e5,max_output_tokens:128e3,safety_margin:Kt,note:e("settings.modelLimits.defaults.gpt53Codex")},{vendor:"OpenAI (GPT-5)",model_pattern:"gpt-5.2-pro",max_context_tokens:256e3,max_output_tokens:64e3,safety_margin:Kt,note:e("settings.modelLimits.defaults.gpt52Pro")},{vendor:"OpenAI (GPT-5)",model_pattern:"gpt-5-mini",max_context_tokens:4e5,max_output_tokens:128e3,safety_margin:Kt,note:e("settings.modelLimits.defaults.gpt5Mini")},{vendor:"OpenAI (Legacy)",model_pattern:"gpt-4.1",max_context_tokens:128e3,max_output_tokens:16384,safety_margin:Kt,note:e("settings.modelLimits.defaults.gpt41")},{vendor:"OpenAI (Legacy)",model_pattern:"gpt-4o",max_context_tokens:128e3,max_output_tokens:16e3,safety_margin:Kt,note:e("settings.modelLimits.defaults.gpt4o")},{vendor:"Google",model_pattern:"gemini-2.5-pro",max_context_tokens:128e3,max_output_tokens:16e3,safety_margin:Kt,note:e("settings.modelLimits.defaults.gemini25Pro")},{vendor:"Moonshot",model_pattern:"kimi-k2.5",max_context_tokens:256e3,max_output_tokens:64e3,safety_margin:Kt,note:e("settings.modelLimits.defaults.kimiK25")},{vendor:"Moonshot",model_pattern:"kimi-for-coding",max_context_tokens:256e3,max_output_tokens:64e3,safety_margin:Kt,note:e("settings.modelLimits.defaults.kimiCoding")},{vendor:"Zhipu",model_pattern:"glm-5",max_context_tokens:2e5,max_output_tokens:128e3,safety_margin:Kt,note:e("settings.modelLimits.defaults.glm5")}]}function uk(e){return Array.isArray(e)?Kd(e):[]}function Qm(e,t){if(typeof e!="number"||!Number.isFinite(e))return t;const s=Math.floor(e);return s>0?s:t}function mk(e,t){if(typeof e!="number"||!Number.isFinite(e))return t;const s=Math.floor(e);return s>=0?s:t}function hk(e){if(!e||typeof e!="object")return null;const t=e,s=t.model_pattern??t.model;if(typeof s!="string"||!s.trim())return null;const n=Qm(t.max_context_tokens??t.maxContextTokens,128e3),o=Qm(t.max_output_tokens??t.maxOutputTokens,Math.min(4096,Math.floor(n/4))),a=mk(t.safety_margin??t.safetyMargin,Kt);return{vendor:typeof t.vendor=="string"&&t.vendor.trim()?t.vendor.trim():"",model_pattern:s.trim(),max_context_tokens:n,max_output_tokens:o,safety_margin:a,note:typeof t.note=="string"?t.note:""}}function Kd(e){return Array.isArray(e)?e.map(t=>hk(t)).filter(t=>!!t):[]}function pk(){const e=localStorage.getItem(Fc);if(!e)return[];try{const t=JSON.parse(e);return Kd(t)}catch{return[]}}function fk(e){const t=Object.prototype.hasOwnProperty.call(e,Km);return t?{hasModelLimitsKey:t,modelLimits:Kd(e[Km])}:{hasModelLimitsKey:!1,modelLimits:[]}}function gk(e,t){if(e.length===0)return t("settings.modelLimits.validation.atLeastOneRow");const s=new Set;for(const n of e){const o=n.model_pattern.trim();if(!o)return t("settings.modelLimits.validation.modelPatternEmpty");const a=o.toLowerCase();if(s.has(a))return t("settings.modelLimits.validation.duplicateModelPattern",{pattern:o});if(s.add(a),n.max_context_tokens<1e3)return t("settings.modelLimits.validation.contextWindowMin",{pattern:o});if(n.max_output_tokens<1)return t("settings.modelLimits.validation.maxOutputMin",{pattern:o});if(n.max_output_tokens>n.max_context_tokens)return t("settings.modelLimits.validation.maxOutputExceedsContext",{pattern:o});if(n.safety_margin<0)return t("settings.modelLimits.validation.safetyMarginNegative",{pattern:o});if(n.safety_margin>=n.max_context_tokens)return t("settings.modelLimits.validation.safetyMarginTooLarge",{pattern:o})}return null}const yk=()=>{const{t:e}=ne(),[t,s]=m.useState(()=>Jm(e)),[n,o]=m.useState(!1),[a,i]=fe.useMessage(),l=m.useCallback((f,v)=>{s(b=>b.map((x,_)=>_===f?{...x,...v}:x))},[]),c=m.useCallback(()=>{s(f=>[...f,{vendor:"",model_pattern:"",max_context_tokens:128e3,max_output_tokens:4096,safety_margin:Kt,note:""}])},[]),d=m.useCallback(f=>{s(v=>v.filter((b,x)=>x!==f))},[]),u=m.useCallback(async()=>{const f=Jm(e),v=await et.getModelLimitDefaults(),b=uk(v.model_limits);return b.length>0?b:f},[e]),h=m.useCallback(async()=>{o(!0);try{const f=await et.getBambooConfig(),{hasModelLimitsKey:v,modelLimits:b}=fk(f);if(b.length>0){s(b);return}if(v){s(await u());return}const x=pk();if(x.length>0){await et.setBambooConfig({model_limits:x}),localStorage.removeItem(Fc),localStorage.removeItem(Gm),s(x),a.info(e("settings.modelLimits.migratedFromLocalStorage"));return}s(await u())}catch(f){console.error("Failed to load model limits settings:",f),a.error(e("settings.modelLimits.loadFailed")),s(await u())}finally{o(!1)}},[u,a,e]);m.useEffect(()=>{h()},[h]);const p=async()=>{const f=gk(t,e);if(f){a.error(f);return}o(!0);try{await et.setBambooConfig({model_limits:t}),a.success(e("settings.modelLimits.saveSuccess"))}catch(v){console.error("Failed to save model limits settings:",v),a.error(e("settings.modelLimits.saveFailed"))}finally{o(!1)}},g=async()=>{o(!0);try{const f=await u();await et.setBambooConfig({model_limits:f}),s(f),localStorage.removeItem(Fc),localStorage.removeItem(Gm),a.success(e("settings.modelLimits.resetSuccess"))}catch(f){console.error("Failed to reset model limits settings:",f),a.error(e("settings.modelLimits.resetFailed"))}finally{o(!1)}},y=m.useMemo(()=>[{title:e("settings.modelLimits.columns.vendor"),dataIndex:"vendor",key:"vendor",width:170,render:(f,v,b)=>r.jsx(me,{value:f,placeholder:e("settings.modelLimits.placeholders.vendor"),onChange:x=>l(b,{vendor:x.target.value})})},{title:e("settings.modelLimits.columns.model"),dataIndex:"model_pattern",key:"model_pattern",width:220,render:(f,v,b)=>r.jsx(me,{value:f,placeholder:e("settings.modelLimits.placeholders.model"),onChange:x=>l(b,{model_pattern:x.target.value})})},{title:e("settings.modelLimits.columns.contextWindow"),dataIndex:"max_context_tokens",key:"max_context_tokens",width:180,render:(f,v,b)=>r.jsx(rt,{value:f,onChange:x=>l(b,{max_context_tokens:Math.max(1e3,Number(x)||128e3)}),min:1e3,max:2e6,step:1e3,style:{width:"100%"}})},{title:e("settings.modelLimits.columns.maxOutput"),dataIndex:"max_output_tokens",key:"max_output_tokens",width:160,render:(f,v,b)=>r.jsx(rt,{value:f,onChange:x=>l(b,{max_output_tokens:Math.max(1,Number(x)||4096)}),min:1,max:2e6,step:256,style:{width:"100%"}})},{title:e("settings.modelLimits.columns.notes"),dataIndex:"note",key:"note",width:240,render:(f,v,b)=>r.jsx(me,{value:f,placeholder:e("settings.modelLimits.placeholders.optional"),onChange:x=>l(b,{note:x.target.value})})},{title:e("settings.modelLimits.columns.actions"),key:"actions",width:100,render:(f,v,b)=>r.jsx(Y,{danger:!0,size:"small",onClick:()=>d(b),children:e("settings.modelLimits.actions.remove")})}],[d,e,l]);return r.jsxs("div",{className:"model-limits-settings",children:[i,r.jsxs(ee,{children:[r.jsx(ck,{level:4,children:e("settings.modelLimits.title")}),r.jsxs(dk,{type:"secondary",children:[e("settings.modelLimits.descriptionPrefix")," ",r.jsx(Ml,{code:!0,children:"config.json"})," ",e("settings.modelLimits.descriptionSuffix")]}),r.jsx(Rt,{}),r.jsxs(X,{direction:"vertical",size:"small",style:{width:"100%"},children:[r.jsx(Ml,{strong:!0,children:e("settings.modelLimits.defaultsTitle")}),r.jsx(Ml,{type:"secondary",children:e("settings.modelLimits.defaultsDescription")})]}),r.jsx(qs,{dataSource:t,columns:y,rowKey:(f,v)=>`${f.model_pattern}-${v}`,pagination:!1,size:"small",style:{margin:"16px 0"},scroll:{x:1150}}),r.jsxs(X,{children:[r.jsx(Y,{onClick:c,children:e("settings.modelLimits.actions.addRow")}),r.jsx(Y,{type:"primary",icon:r.jsx(Di,{}),onClick:()=>void p(),loading:n,children:e("settings.modelLimits.actions.save")}),r.jsx(Y,{icon:r.jsx(Ms,{}),onClick:()=>void g(),loading:n,children:e("settings.modelLimits.actions.resetToDefaults")}),r.jsx(Y,{onClick:()=>void h(),loading:n,children:e("settings.modelLimits.actions.reload")})]})]})]})},zc="lotus_experience_mode_v1",Fy=new Set(["skills","hooks","masking","env-vars","metrics","sessions","config"]);function Zm(){try{const e=localStorage.getItem(zc);if(e==="simple"||e==="advanced")return e}catch{}return"advanced"}const Mi=un(e=>({mode:Zm(),isAdvanced:Zm()==="advanced",setMode:t=>{try{localStorage.setItem(zc,t)}catch{}e({mode:t,isAdvanced:t==="advanced"})},toggleMode:()=>e(t=>{const s=t.mode==="simple"?"advanced":"simple";try{localStorage.setItem(zc,s)}catch{}return{mode:s,isAdvanced:s==="advanced"}})})),{Text:Pl}=le,{useToken:bk}=he,xk="bamboo_dark_mode",vk=({themeMode:e,onThemeModeChange:t,locale:s,onLocaleChange:n,onBack:o})=>{const{t:a}=ne(),{token:i}=bk(),{deleteAllChats:l,autoGenerateTitles:c,setAutoGenerateTitlesPreference:d,isUpdatingAutoTitlePreference:u}=T_(),[h,p]=m.useState(!1),[g,y]=fe.useMessage(),[f,v]=m.useState(""),[b,x]=m.useState(Cc()),[_,w]=m.useState(Pc()),[k,C]=m.useState(ki()),[E,j]=m.useState(ji()),M=Ee(z=>z.currentProvider)==="copilot",T=Bs(z=>z.activeTabKey),P=Bs(z=>z.setActiveTabKey),S=Mi(z=>z.isAdvanced),L=i.paddingSM,$=(z,de)=>({key:z,label:r.jsx(Pl,{type:"secondary",style:{fontSize:11,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em",cursor:"default",userSelect:"none"},children:de}),disabled:!0,children:null}),I=(z,de)=>r.jsx("span",{"data-testid":`settings-tab-${z}`,children:de}),W=()=>{localStorage.clear(),g.success(a("settings.notifications.localStorageCleared"))},A=async()=>{p(!0);try{await l(),await et.resetSetupStatus(),await et.resetBambooConfig(),localStorage.clear(),g.success(a("settings.notifications.resetSuccessReloading")),setTimeout(()=>{window.location.reload()},1500)}catch(z){console.error("Failed to reset application:",z),g.error(z instanceof Error?z.message:a("settings.notifications.resetFailed")),p(!1)}},O=async z=>{try{await d(z),g.success(a(z?"settings.notifications.autoTitleEnabled":"settings.notifications.autoTitleDisabled"))}catch{g.error(a("settings.notifications.autoTitleUpdateFailed"))}},D=()=>{v_(f),g.success(a("settings.notifications.promptEnhancementSaved"))},H=z=>{x(z),l_(z)},B=z=>{w(z),u_(z)},K=z=>{C(z),f_(z)},F=z=>{j(z),k_(z),window.dispatchEvent(new Event("lotus-vdi-safe-mode-change")),g.success(z?a("settings.appTab.vdiSafeModeEnabled","Graphics compatibility mode enabled"):a("settings.appTab.vdiSafeModeDisabled","Graphics compatibility mode disabled"))};return m.useEffect(()=>{v(jy()),x(Cc()),w(Pc()),C(ki()),j(ji())},[]),r.jsxs(G,{vertical:!0,role:"region","aria-label":a("settings.page.title"),style:{height:"100vh",overflow:"hidden",background:i.colorBgContainer},children:[y,r.jsxs(G,{align:"center",justify:"space-between",style:{padding:i.padding,paddingTop:i.padding+L,borderBottom:`1px solid ${i.colorBorderSecondary}`},children:[r.jsxs(G,{align:"center",gap:i.marginSM,children:[r.jsx(Y,{icon:r.jsx(gx,{}),onClick:o,"aria-label":a("settings.page.back"),children:a("settings.page.back")}),r.jsx(Pl,{strong:!0,"data-testid":"settings-page-title",children:a("settings.page.title")})]}),r.jsxs(Pl,{type:"secondary","data-testid":"settings-page-version",children:[a("settings.appTab.runningVersion","Running version"),": v",xd]})]}),r.jsx(Dn.Content,{style:{flex:1,minHeight:0,overflow:"auto",padding:i.padding},children:r.jsx(ui,{tabPosition:"left",activeKey:T,onChange:z=>P(z),items:[$("group-ai",a("settings.page.groups.ai")),{key:"provider",label:I("provider",a("settings.page.tabs.provider")),children:r.jsx(ok,{})},{key:"model-limits",label:I("model-limits",a("settings.page.tabs.modelLimits")),children:r.jsx(yk,{})},{key:"prompts",label:I("prompts",a("settings.page.tabs.prompts")),children:r.jsx(B_,{promptEnhancement:f,onPromptEnhancementChange:v,mermaidEnhancementEnabled:b,taskEnhancementEnabled:_,showCopilotConclusionWithOptionsEnhancement:M,copilotConclusionWithOptionsEnhancementEnabled:k,onMermaidToggle:H,onTaskToggle:B,onCopilotConclusionWithOptionsToggle:K,onSaveEnhancement:D})},$("group-tools",a("settings.page.groups.toolsAndExtensions")),{key:"skills",label:I("skills",a("settings.page.tabs.skills")),children:r.jsx(lk,{})},{key:"mcp",label:I("mcp",a("settings.page.tabs.mcp")),children:r.jsx(Y0,{})},{key:"workflows",label:I("workflows",a("settings.page.tabs.workflows")),children:r.jsx(o0,{})},{key:"hooks",label:I("hooks",a("settings.page.tabs.hooks")),children:r.jsx(FT,{})},$("group-security",a("settings.page.groups.securityAndPrivacy")),{key:"masking",label:I("masking",a("settings.page.tabs.masking")),children:r.jsx(Q_,{})},{key:"env-vars",label:I("env-vars",a("settings.page.tabs.envVars")),children:r.jsx(t0,{})},$("group-monitoring",a("settings.page.groups.monitoring")),{key:"metrics",label:I("metrics",a("settings.page.tabs.metrics")),children:r.jsx($T,{})},{key:"sessions",label:I("sessions",a("settings.page.tabs.sessions")),children:r.jsx(JT,{})},$("group-system",a("settings.page.groups.system")),{key:"config",label:I("config",a("settings.page.tabs.config")),children:r.jsx(I_,{msgApi:g,locale:s,onLocaleChange:n})},{key:"schedules",label:I("schedules",a("settings.page.tabs.schedules")),children:r.jsx(GT,{})},{key:"app",label:I("app",a("settings.page.tabs.app")),children:r.jsx(K_,{autoGenerateTitles:c,isUpdatingAutoTitlePreference:u,onAutoTitleToggle:O,themeMode:e,onThemeModeChange:t,vdiSafeMode:E,onVdiSafeModeToggle:F,onClearLocalStorage:W,onResetApp:A,isResetting:h,darkModeKey:xk})}].filter(z=>!(!S&&z.key&&Fy.has(z.key)||!S&&(z.key==="group-security"||z.key==="group-monitoring")))})})]})},{Text:eh,Paragraph:Sk}=le;class ia extends m.Component{constructor(s){super(s);He(this,"handleReset",()=>{this.setState({hasError:!1,error:null})});this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,n){var a,i;const o=this.props.name??"ErrorBoundary";console.error(`[${o}] Uncaught error:`,s,n),(i=(a=this.props).onError)==null||i.call(a,s,n)}render(){if(!this.state.hasError)return this.props.children;const{fallback:s}=this.props,n=this.state.error;return typeof s=="function"?s(n,this.handleReset):s!==void 0?s:r.jsx(wk,{error:n,onReset:this.handleReset})}}const wk=({error:e,onReset:t})=>{const{token:s}=he.useToken(),[n,o]=ut.useState(!1);return r.jsxs("div",{role:"alert",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12,padding:s.paddingLG,minHeight:200,textAlign:"center"},children:[r.jsx(bf,{style:{fontSize:36,color:s.colorWarning}}),r.jsx(eh,{strong:!0,style:{fontSize:16},children:"Something went wrong"}),r.jsx(eh,{type:"secondary",style:{maxWidth:420},children:"An unexpected error occurred in this section. You can try again or reload the page if the issue persists."}),r.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[r.jsx(Y,{type:"primary",icon:r.jsx(Ms,{}),onClick:t,"aria-label":"Retry rendering this section",children:"Try Again"}),r.jsx(Y,{type:"text",size:"small",onClick:()=>o(a=>!a),"aria-expanded":n,"aria-label":"Toggle error details",children:n?"Hide Details":"Show Details"})]}),n&&r.jsxs(Sk,{code:!0,copyable:!0,style:{maxWidth:560,maxHeight:200,overflow:"auto",fontSize:12,textAlign:"left",marginTop:8,background:s.colorFillTertiary,padding:s.paddingSM,borderRadius:s.borderRadius},children:[e.message,e.stack?`
|
|
151
151
|
|
|
152
|
-
${e.stack}`:""]})]})},_k=15e3,Tk=()=>{const e=N(a=>a.chats),t=N(a=>a.updateSession),{generateChatTitle:s}=Ud({chats:e,updateSession:t}),n=m.useRef(new Map),o=m.useRef(new Map);return m.useEffect(()=>{e.forEach(a=>{const i=a.id,l=a.messages;if(l.length===0)return;const c=l[l.length-1];if(c.role!=="assistant")return;const d=n.current.get(i);if(c.id===d)return;const u=o.current.get(i);u&&u.messageId===c.id&&Date.now()-u.at<_k||s(i).then(h=>{h&&(n.current.set(i,c.id),o.current.delete(i))}).catch(h=>{o.current.set(i,{messageId:c.id,at:Date.now()}),console.warn("Auto title generation failed for chat",i,":",h)})})},[e,s]),m.useEffect(()=>{const a=new Set(e.map(l=>l.id));Array.from(n.current.keys()).forEach(l=>{a.has(l)||(n.current.delete(l),o.current.delete(l))})},[e]),null},kk=()=>{const{token:e}=he.useToken(),t=Xi(),s=m.useRef("");m.useEffect(()=>{const n=jk(e.colorBgContainer),o=`${n}-${t.theme}-${JSON.stringify(t.themeVariables)}`;if(s.current===o)return;s.current=o;let a=t.theme;(t.theme==="default"||t.theme==="neutral")&&(a=n?"dark":t.theme),ud.initialize({startOnLoad:!1,theme:a,securityLevel:"loose",suppressErrorRendering:!0,fontSize:t.fontSize,themeVariables:Object.keys(t.themeVariables).length>0?t.themeVariables:void 0,flowchart:{useMaxWidth:t.useMaxWidth,htmlLabels:!0,curve:t.flowchartCurve,nodeSpacing:t.flowchartNodeSpacing,rankSpacing:t.flowchartRankSpacing},sequence:{useMaxWidth:t.useMaxWidth,diagramMarginX:10,diagramMarginY:10,actorMargin:t.sequenceActorMargin,width:t.sequenceWidth,height:t.sequenceHeight,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:t.sequenceMessageMargin,mirrorActors:!0,bottomMarginAdj:1,rightAngles:!1,showSequenceNumbers:!1},gantt:{useMaxWidth:t.useMaxWidth,leftPadding:75,gridLineStartPadding:35,barHeight:t.ganttBarHeight,barGap:4,topPadding:t.ganttTopPadding},journey:{useMaxWidth:t.useMaxWidth,diagramMarginX:50,diagramMarginY:10,leftMargin:150,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35,messageAlign:"center"},timeline:{useMaxWidth:t.useMaxWidth,diagramMarginX:50,diagramMarginY:10,leftMargin:150,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35},gitGraph:{useMaxWidth:t.useMaxWidth,showBranches:!0,showCommitLabel:!0},c4:{useMaxWidth:t.useMaxWidth,diagramMarginX:50,diagramMarginY:10,c4ShapeMargin:50,c4ShapePadding:20,width:216,height:60,boxMargin:10},sankey:{useMaxWidth:t.useMaxWidth},xyChart:{useMaxWidth:t.useMaxWidth},block:{useMaxWidth:t.useMaxWidth,padding:8}})},[e,t])};function jk(e){if(e.startsWith("#")){const s=e.slice(1),n=parseInt(s.substr(0,2),16),o=parseInt(s.substr(2,2),16),a=parseInt(s.substr(4,2),16);return(.299*n+.587*o+.114*a)/255<.5}const t=e.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(t){const s=parseInt(t[1]),n=parseInt(t[2]),o=parseInt(t[3]);return(.299*s+.587*n+.114*o)/255<.5}return!1}ud.initialize({startOnLoad:!1,theme:"dark",securityLevel:"loose",suppressErrorRendering:!0});ud.parseError=function(e){console.warn("Mermaid parse error (handled gracefully):",e)};const th=new Map,Ck=/^(\s*%%\{[\s\S]*?\}%%\s*)*\s*gantt\b/i,Mk=e=>e.replace(/:/g,":").replace(/,/g,",").replace(/;/g,";").replace(/(/g,"(").replace(/)/g,")").replace(/-/g,"-"),Pk=e=>(Ck.test(e)?Mk(e):e).replace(/\[([\s\S]*?)\]/g,(s,n)=>{const o=String(n),a=/\r?\n/.test(o),i=/[()]/.test(o),l=/@/.test(o);if(!a&&!i&&!l)return s;const c=o.trim(),d=c.startsWith("(")&&c.endsWith(")")&&c.length>=2;let u=o;return a&&(u=u.replace(/\r?\n/g,"<br/>")),i&&!d&&(u=u.replace(/\(/g,"(").replace(/\)/g,")")),l&&(u=u.replace(/@/g,"@")),u===o?s:`[${u}]`}),Ek=200,Ts=new Map,li=new Map;let El=null;const Rk=e=>{const s=new DOMParser().parseFromString(e,"image/svg+xml");return Array.from(s.querySelectorAll("rect")).reduce((o,a)=>{const i=Number(a.getAttribute("width"));return Number.isFinite(i)&&i<0?o+1:o},0)};async function Ak(){El||(El=Dt(()=>import("./vendor-mermaid-CrWGhc5e.js").then(t=>t.bd),__vite__mapDeps([7,1,2,3,6]),import.meta.url));const e=await El;return e.default??e}function Ik(e,t){if(Ts.has(e)&&Ts.delete(e),Ts.set(e,t),Ts.size>Ek){const s=Ts.keys().next().value;s&&Ts.delete(s)}}function ci(e){const t=Ts.get(e);return t?(Ts.delete(e),Ts.set(e,t),t):null}function sh(){Ts.clear(),li.clear()}function $k(e,t){const s=ci(e);if(s)return Promise.resolve(s);const n=li.get(e);if(n)return n;const o=(async()=>{var x,_;const a=await Ak();await a.parse(t);const i=`mermaid-${e}`,l=document.createElement("div"),c=Math.max(1600,window.innerWidth||0,((x=document.documentElement)==null?void 0:x.clientWidth)||0);l.style.cssText=["position:absolute","left:-9999px","top:-9999px",`width:${c}px`,`min-width:${c}px`,"visibility:hidden","pointer-events:none","overflow:visible"].join(";"),document.body.appendChild(l);let d;try{d=await a.render(i,t,l)}finally{document.body.removeChild(l)}const u=typeof d=="object"&&"svg"in d?d.svg:String(d),h=Rk(u);if(h>0)throw new Error(`Mermaid rendered invalid SVG (${h} rect widths < 0)`);const y=new DOMParser().parseFromString(u,"image/svg+xml").querySelector("svg");let f=800,v=300;if(y){const w=y.getAttribute("viewBox");if(w){const k=w.split(/\s+/).map(Number);k.length===4&&(f=k[2]||800,v=k[3]||300)}if(f===800&&v===300){const k=document.createElement("div");k.style.cssText="position:absolute;visibility:hidden;width:800px;",k.innerHTML=u,document.body.appendChild(k);const C=(_=k.querySelector("svg"))==null?void 0:_.getBoundingClientRect();C&&(f=C.width,v=C.height),document.body.removeChild(k)}}const b={svg:u,width:f,height:v};return Ik(e,b),b})().finally(()=>{li.delete(e)});return li.set(e,o),o}const Dk=e=>{const t=e;return(t==null?void 0:t.name)==="AbortError"||(t==null?void 0:t.code)===20},nh=220,rh=e=>{const t=e.replace(/\s+/g," ").trim();return t.length<=nh?t:`${t.slice(0,nh)}...`},Lk=e=>e==="pending"||e==="in_progress"||e==="completed"||e==="blocked",Wa=e=>{const t=e.trim().toLowerCase();return t==="memory_note"||t==="session_note"};function Ok(){const e=N(j=>j.processingChats),t=N(j=>j.addMessage),s=N(j=>j.setSessionProcessing),n=N(j=>j.updateTokenUsage),o=N(j=>j.setTruncationInfo),a=N(j=>j.updateSession),i=N(j=>j.updateMessage),l=N(j=>j.setTaskList),c=N(j=>j.updateTaskListDelta),d=N(j=>j.setEvaluationState),u=N(j=>j.upsertSubSessionProgress),h=N(j=>j.refreshChats),p=m.useRef(new rs),g=m.useRef(new Map),y=m.useRef(new Map),f=m.useRef(new Map),v=m.useRef(new Map),b=m.useRef(new Map),x=m.useRef(new Set),_=m.useRef(new Map),w=m.useCallback(j=>{const R=_.current.get(j);R!=null&&R.timer&&clearTimeout(R.timer),_.current.delete(j)},[]),k=m.useCallback((j,R)=>{w(j),x.current.delete(j);const M=g.current.get(j);if(!M)return;g.current.delete(j),M.controller.abort(),ze.forceFlush();const T=y.current.get(M.sessionId);T?(R!=null&&R.clearDraft&&(ze.clear(T.sessionId,T.messageId),ze.clear(T.sessionId,T.reasoningMessageId),ze.clear(T.sessionId,T.statusMessageId)),y.current.delete(M.sessionId)):R!=null&&R.clearDraft&&(ze.clear(j,`streaming-${j}`),ze.clear(j,`streaming-reasoning-${j}`),ze.clear(j,`streaming-status-${j}`))},[w]),C=m.useCallback(j=>{w(j);const R=new AbortController;g.current.set(j,{sessionId:j,controller:R});const M=`streaming-${j}`,T=`streaming-reasoning-${j}`,P=`streaming-status-${j}`,S=ze.getLatest(M),L=ze.getLatest(T),$=ze.getLatest(P);y.current.set(j,{sessionId:j,messageId:M,content:S??"",reasoningMessageId:T,reasoningContent:L??"",statusMessageId:P,status:$??""});const I=A=>{const O=y.current.get(j);if(!O)return;const D=(A??"").trim();if(!D){if(!O.status)return;O.status="",ze.clear(O.sessionId,O.statusMessageId);return}O.status!==D&&(O.status=D,ze.publish({sessionId:O.sessionId,messageId:O.statusMessageId,content:O.status}))};S===null&&ze.publish({sessionId:j,messageId:M,content:""});const W=()=>{const A=_.current.get(j),O=(A==null?void 0:A.attempt)??0,D=Math.min(5e3,250*Math.pow(2,O));k(j,{clearDraft:!1});const H=setTimeout(()=>{var F;if(_.current.delete(j),!N.getState().processingChats.has(j))return;const B=N.getState().chats.find(z=>z.id===j),K=(F=B==null?void 0:B.id)==null?void 0:F.trim();K&&C(K)},D);_.current.set(j,{attempt:O+1,timer:H})};p.current.subscribeToEvents(j,{onToken:A=>{const O=y.current.get(j);O&&(I(null),O.content+=A,ze.publish({sessionId:O.sessionId,messageId:O.messageId,content:O.content}))},onReasoningToken:A=>{const O=y.current.get(j);O&&(O.reasoningContent+=A,ze.publish({sessionId:O.sessionId,messageId:O.reasoningMessageId,content:O.reasoningContent}))},onToolStart:(A,O,D)=>{var $e,De;const H=y.current.get(j),B=(H==null?void 0:H.content)||"",K=(H==null?void 0:H.reasoningContent)||"",F=B.trim().length>0,z=K.trim().length>0;if(F||z){const be=N.getState().chats.find(ht=>ht.id===j),ye=($e=be==null?void 0:be.messages)==null?void 0:$e[be.messages.length-1],je=typeof((De=ye==null?void 0:ye.metadata)==null?void 0:De.reasoning)=="string"?ye.metadata.reasoning:"";(ye==null?void 0:ye.role)==="assistant"&&(ye==null?void 0:ye.type)==="text"&&typeof(ye==null?void 0:ye.content)=="string"&&ye.content===B&&je===K||t(j,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:B,createdAt:new Date().toISOString(),metadata:{sessionId:j,model:"agent",...z?{reasoning:K}:{}}}),H&&(H.content="",H.reasoningContent="",H.status&&(H.status="",ze.clear(H.sessionId,H.statusMessageId)),ze.publish({sessionId:H.sessionId,messageId:H.messageId,content:""}),ze.publish({sessionId:H.sessionId,messageId:H.reasoningMessageId,content:""}))}v.current.set(A,O);const de=O.trim().toLowerCase();Wa(O)?I("memory_updating"):I(`tool_running:${de||"tool"}`);const Te=crypto.randomUUID();b.current.set(A,Te),t(j,{id:Te,role:"assistant",type:"tool_call",toolCalls:[{toolCallId:A,toolName:O,parameters:D||{},streamingOutput:""}],metadata:{},createdAt:new Date().toISOString()})},onToolToken:(A,O)=>{const D=b.current.get(A),H=N.getState().chats.find(z=>z.id===j);if(!H)return;const B=(D?H==null?void 0:H.messages.find(z=>z.id===D):null)||(H==null?void 0:H.messages[H.messages.length-1]);if(!B||!("type"in B)||B.type!=="tool_call"||!("toolCalls"in B)||!Array.isArray(B.toolCalls))return;const K=B.toolCalls.find(z=>z.toolCallId===A);K&&!v.current.has(A)&&(v.current.set(A,K.toolName),b.current.set(A,B.id));const F=B.toolCalls.map(z=>{if(z.toolCallId!==A)return z;const de=(z.streamingOutput||"")+(O||"");return{...z,streamingOutput:de}});i(j,B.id,{toolCalls:F})},onToolComplete:(A,O)=>{const D=v.current.get(A)||"unknown";v.current.delete(A),b.current.delete(A);const H=D.trim().toLowerCase(),B=y.current.get(j);(Wa(D)?(B==null?void 0:B.status)==="memory_updating":!!(B!=null&&B.status&&B.status.includes(H)))&&I(null);const F=(O==null?void 0:O.display_preference)||"Default";t(j,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:D,toolCallId:A,result:{tool_name:D,result:(O==null?void 0:O.result)??"",display_preference:F},isError:!(O!=null&&O.success),createdAt:new Date().toISOString()})},onToolError:(A,O)=>{v.current.delete(A),b.current.delete(A),I(null),t(j,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:"unknown",toolCallId:A,result:{tool_name:"unknown",result:O,display_preference:"Default"},isError:!0,createdAt:new Date().toISOString()})},onToolLifecycle:(A,O,D,H,B)=>{if(D==="begin"){const K=(O||"").trim().toLowerCase();Wa(O||"")?I("memory_updating"):I(`tool_running:${K||"tool"}`)}if(D==="finished"||D==="error"||D==="cancelled"){const K=b.current.get(A);K&&i(j,K,{metadata:{elapsed_ms:H,is_mutating:B}});const F=(O||"").trim().toLowerCase(),z=y.current.get(j);(Wa(O||"")?(z==null?void 0:z.status)==="memory_updating":!!(z!=null&&z.status&&z.status.includes(F)))&&I(null)}},onContextCompressionStatus:(A,O)=>{if(O==="started"){I("context_compacting");return}if(O==="degraded_sections"){I("context_compaction_degraded");return}if(O==="failed"){I("context_compaction_failed");return}I(null)},onTokenBudgetUpdated:A=>{const O=typeof A.max_context_tokens=="number"&&A.max_context_tokens>0?A.max_context_tokens:void 0,D={systemTokens:A.system_tokens,summaryTokens:A.summary_tokens,windowTokens:A.window_tokens,totalTokens:A.total_tokens,budgetLimit:A.budget_limit,...O?{maxContextTokens:O}:{},...typeof A.prompt_cached_tool_outputs=="number"&&A.prompt_cached_tool_outputs>0?{promptCachedToolOutputs:A.prompt_cached_tool_outputs}:{}};n(j,D),o(j,A.truncation_occurred,A.segments_removed);const H=N.getState().chats.find(B=>B.id===j);H&&a(j,{config:{...H.config,tokenUsage:D,truncationOccurred:A.truncation_occurred,segmentsRemoved:A.segments_removed}})},onContextSummarized:A=>{I(null),fe.info(`Conversation summarized: ${A.messages_summarized} messages compressed, saved ${A.tokens_saved.toLocaleString()} tokens`,5)},onTaskListUpdated:A=>{A.session_id&&l(A.session_id,A)},onTaskListItemProgress:A=>{A.session_id&&c(A.session_id,A)},onTaskListCompleted:(A,O,D)=>{fe.success(`All tasks completed! Total rounds: ${O}, Tool calls: ${D}`,3)},onTaskEvaluationStarted:(A,O)=>{d(A,{isEvaluating:!0,reasoning:null,timestamp:Date.now()}),fe.info(`Evaluating ${O} task(s)...`,2)},onTaskEvaluationCompleted:(A,O,D)=>{const H=rh(D);d(A,{isEvaluating:!1,reasoning:O>0?H:null,timestamp:Date.now()}),O>0?fe.success(`Evaluation complete: ${O} task(s) updated.`,3):fe.info("Evaluation complete: No updates needed",2)},onComplete:()=>{const A=R;(async()=>{var de,Te,$e;I(null),ze.forceFlush();const O=()=>{const De=g.current.get(j);return De!=null&&De.controller!==A};if(O())return;const D=y.current.get(j),H=(D==null?void 0:D.content)||"",B=(D==null?void 0:D.reasoningContent)||"",K=H.trim().length>0,F=B.trim().length>0;if(K||F){const De=N.getState().chats.find(Ue=>Ue.id===j),be=(de=De==null?void 0:De.messages)==null?void 0:de[De.messages.length-1],ye=typeof((Te=be==null?void 0:be.metadata)==null?void 0:Te.reasoning)=="string"?be.metadata.reasoning:"";(be==null?void 0:be.role)==="assistant"&&(be==null?void 0:be.type)==="text"&&typeof(be==null?void 0:be.content)=="string"&&be.content===H&&ye===B||await t(j,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:H,createdAt:new Date().toISOString(),metadata:{sessionId:j,model:"agent",...F?{reasoning:B}:{}}})}if(O()||(await N.getState().loadChatHistory(j,{mode:"monotonic",retries:4,retryDelayMs:200,waitForAssistant:!0}),O()))return;if(F){const De=N.getState().chats.find(je=>je.id===j),be=[...(De==null?void 0:De.messages)||[]].reverse().find(je=>(je==null?void 0:je.role)==="assistant"&&(je==null?void 0:je.type)==="text"),ye=typeof(($e=be==null?void 0:be.metadata)==null?void 0:$e.reasoning)=="string"&&be.metadata.reasoning.trim().length>0;be!=null&&be.id&&!ye&&i(j,be.id,{metadata:{...be.metadata||{},reasoning:B}})}if(O())return;const z=f.current.get(j)??{children:new Set};if(f.current.set(j,{children:new Set(z.children),parentDone:!0}),z.children.size===0)k(j,{clearDraft:!0}),s(j,!1);else{const De=g.current.get(j);De&&(ze.clear(j,`streaming-${j}`),ze.clear(j,`streaming-reasoning-${j}`),ze.clear(j,`streaming-status-${j}`),y.current.delete(De.sessionId))}})()},onError:async A=>{I(null);const O=Ec(A)?Rc(A):A;await t(j,{id:`error-${Date.now()}`,role:"assistant",type:"text",content:`❌ **Error**: ${O}`,createdAt:new Date().toISOString(),finishReason:"error"});const D=f.current.get(j)??{children:new Set};f.current.set(j,{children:new Set(D.children),parentDone:!0}),D.children.size===0&&(k(j,{clearDraft:!0}),s(j,!1))},onSubSessionStarted:(A,O,D)=>{const H=f.current.get(A)??{children:new Set,parentDone:!1},B=new Set(H.children);B.add(O),f.current.set(A,{children:B,parentDone:H.parentDone}),s(j,!0),u(A,O,{title:D,status:"pending",lastEventAt:new Date().toISOString()}),h()},onSubSessionEvent:(A,O,D)=>{var H,B,K;if(D.type==="task_list_updated"&&D.task_list){const F=D.task_list.session_id||A;l(F,D.task_list);return}if(D.type==="task_list_item_progress"){const F=D.session_id||A;typeof D.item_id=="string"&&Lk(D.status)&&typeof D.tool_calls_count=="number"&&typeof D.version=="number"&&c(F,{session_id:F,item_id:D.item_id,status:D.status,tool_calls_count:D.tool_calls_count,version:D.version});return}if(D.type==="task_evaluation_started"){const F=D.session_id||A;d(F,{isEvaluating:!0,reasoning:null,timestamp:Date.now()});return}if(D.type==="task_evaluation_completed"){const F=D.session_id||A,z=D.updates_count??0;d(F,{isEvaluating:!1,reasoning:z>0?rh(D.reasoning??""):null,timestamp:Date.now()});return}if(D.type==="token"&&typeof D.content=="string"){const z=((((K=(B=(H=N.getState().subSessionsByParent)==null?void 0:H[A])==null?void 0:B[O])==null?void 0:K.outputPreview)||"")+D.content).slice(-2e3);u(A,O,{status:"running",outputPreview:z,lastEventAt:new Date().toISOString()})}else u(A,O,{status:"running",lastEventAt:new Date().toISOString()})},onSubSessionHeartbeat:(A,O,D)=>{u(A,O,{status:"running",lastHeartbeatAt:D})},onSubSessionCompleted:(A,O,D,H)=>{const B=f.current.get(A)??{children:new Set,parentDone:!1},K=new Set(B.children);K.delete(O),f.current.set(A,{children:K,parentDone:B.parentDone}),u(A,O,{status:D,error:H,lastEventAt:new Date().toISOString()}),B.parentDone&&K.size===0&&(k(j,{clearDraft:!0}),s(j,!1)),h()}},R).then(()=>{if(R.signal.aborted)return;const A=g.current.get(j);if(A&&A.controller!==R)return;if(!N.getState().processingChats.has(j)){k(j,{clearDraft:!0});return}W()}).catch(A=>{if(!R.signal.aborted){if(Dk(A)){if(!N.getState().processingChats.has(j)){k(j,{clearDraft:!0});return}W();return}console.error("[useAgentEventSubscription] Subscription error:",A),k(j,{clearDraft:!0}),s(j,!1)}})},[t,k,w,h,d,s,l,o,i,a,c,n,u]),E=m.useCallback(j=>{const R=j.trim();if(!R)return;x.current.delete(R);const M=g.current.get(R);(M==null?void 0:M.sessionId)===R&&!M.controller.signal.aborted||(M&&k(R,{clearDraft:!1}),C(R))},[k,C]);m.useEffect(()=>{e.forEach(j=>E(j));for(const j of Array.from(g.current.keys()))e.has(j)||k(j,{clearDraft:!0});for(const j of Array.from(x.current))e.has(j)||x.current.delete(j)},[e,E,k]),m.useEffect(()=>N.subscribe(j=>j.chats,()=>{if(x.current.size!==0)for(const j of Array.from(x.current)){if(!N.getState().processingChats.has(j)){x.current.delete(j);continue}E(j)}}),[E]),m.useEffect(()=>{const j=g.current;return()=>{const R=Array.from(j.keys());for(const M of R)k(M,{clearDraft:!0})}},[k])}const zy=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_result",Fk=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_call",zk=e=>e.role==="assistant"&&"type"in e&&e.type==="workflow_result",Nk=e=>e.role==="user"&&"type"in e&&e.type==="file_reference",Bk=e=>e.role==="assistant"&&"type"in e&&e.type==="task_list",Pi=["image/jpeg","image/jpg","image/png","image/gif","image/webp","image/bmp"],oh=10*1024*1024,Wk=2048,Uk=2048,qk=.82,Hk=512*1024,Yk=e=>Pi.includes(e.type)?e.size>oh?{isValid:!1,error:`Image size too large: ${(e.size/1024/1024).toFixed(2)}MB. Maximum size: ${oh/1024/1024}MB`}:{isValid:!0}:{isValid:!1,error:`Unsupported image type: ${e.type}. Supported types: ${Pi.join(", ")}`},Xk=e=>new Promise((t,s)=>{const n=new Image;n.onload=()=>t(n),n.onerror=()=>s(new Error("Failed to load image")),n.src=e}),ah=e=>new Promise((t,s)=>{const n=new FileReader;n.onload=()=>{typeof n.result=="string"?t(n.result):s(new Error("Failed to convert file to base64"))},n.onerror=()=>s(new Error("Failed to read file")),n.readAsDataURL(e)}),Vk=e=>URL.createObjectURL(e),Kk=(e,t,s,n)=>{let{width:o,height:a}=t;if(o>s||a>n){const l=o/a;o>a?(o=s,a=Math.round(o/l)):(a=n,o=Math.round(a*l))}e.width=o,e.height=a;const i=e.getContext("2d");i&&(i.fillStyle="#ffffff",i.fillRect(0,0,o,a),i.drawImage(t,0,0,o,a))},Gk=async(e,t)=>{const s=await Xk(e),n=document.createElement("canvas");return Kk(n,s,Wk,Uk),Zk(n,t)},Jk=async e=>{const t=Yk(e);if(!t.isValid)throw new Error(t.error);const s=Vk(e);try{let n;if(e.type==="image/gif"||e.size<Hk)n=await ah(e);else try{n=await Gk(s,qk)}catch(a){console.warn("[imageUtils] Failed to re-encode image, using original:",a),n=await ah(e)}const o=`img_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return{file:e,base64:n,preview:s,id:o,name:e.name,size:e.size,type:e.type}}catch(n){throw Ny(s),n}},Qk=async e=>{const t=Array.from(e),s=[];for(const n of t)try{const o=await Jk(n);s.push(o)}catch(o){console.error(`Failed to process image ${n.name}:`,o)}return s},Zk=(e,t=.8)=>e.toDataURL("image/jpeg",t),Ny=e=>{e.startsWith("blob:")&&URL.revokeObjectURL(e)},ih=e=>{e.forEach(t=>Ny(t.preview))},ej=e=>{if(e===0)return"0 Bytes";const t=1024,s=["Bytes","KB","MB","GB"],n=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,n)).toFixed(2))+" "+s[n]},tj=e=>!e.files||e.files.length===0?!1:Array.from(e.files).some(t=>Pi.includes(t.type)),sj=e=>e.files?Array.from(e.files).filter(t=>Pi.includes(t.type)):[],{Text:nj,Title:rj}=le,oj=({visible:e,images:t,currentIndex:s=0,onClose:n,onDownload:o})=>{const{token:a}=he.useToken(),[i,l]=m.useState(s);if(!t||t.length===0)return null;const c=t[i],d=()=>{if(o&&c)o(c);else{const p=document.createElement("a");p.href=c.base64,p.download=c.name,document.body.appendChild(p),p.click(),document.body.removeChild(p)}},u=()=>{l(p=>p>0?p-1:t.length-1)},h=()=>{l(p=>p<t.length-1?p+1:0)};return r.jsxs(Lt,{open:e,onCancel:n,footer:null,width:"90vw",style:{top:20},styles:{body:{padding:0,height:"80vh",display:"flex",flexDirection:"column"}},closeIcon:r.jsx(wr,{style:{color:a.colorTextLightSolid}}),children:[r.jsx("div",{style:{padding:a.paddingMD,borderBottom:`1px solid ${a.colorBorder}`,background:a.colorBgContainer},children:r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",width:"100%"},children:[r.jsxs("div",{children:[r.jsx(rj,{level:5,style:{margin:0},children:c.name}),r.jsxs(nj,{type:"secondary",style:{fontSize:a.fontSizeSM},children:[ej(c.size)," • ",c.type,t.length>1&&` • ${i+1} of ${t.length}`]})]}),r.jsxs(X,{children:[t.length>1&&r.jsxs(r.Fragment,{children:[r.jsx(Y,{icon:r.jsx(du,{}),onClick:u,disabled:t.length<=1}),r.jsx(Y,{icon:r.jsx(Ws,{}),onClick:h,disabled:t.length<=1})]}),r.jsx(Y,{icon:r.jsx(yr,{}),onClick:d,children:"Download"})]})]})}),r.jsxs("div",{style:{flex:1,display:"flex",justifyContent:"center",alignItems:"center",background:a.colorBgLayout,position:"relative",overflow:"hidden"},children:[t.length===1?r.jsx("img",{src:c.preview,alt:c.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}}):r.jsx(yx,{dots:!1,arrows:!0,infinite:!0,afterChange:l,style:{width:"100%",height:"100%"},children:t.map(p=>r.jsx("div",{children:r.jsx("div",{style:{height:"70vh",display:"flex",justifyContent:"center",alignItems:"center"},children:r.jsx("img",{src:p.preview,alt:p.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}})})},p.id))}),t.length>1&&r.jsxs(r.Fragment,{children:[r.jsx(Y,{type:"primary",shape:"circle",icon:r.jsx(du,{}),onClick:u,style:{position:"absolute",left:20,top:"50%",transform:"translateY(-50%)",zIndex:10}}),r.jsx(Y,{type:"primary",shape:"circle",icon:r.jsx(Ws,{}),onClick:h,style:{position:"absolute",right:20,top:"50%",transform:"translateY(-50%)",zIndex:10}})]})]}),t.length>1&&r.jsx("div",{style:{padding:a.paddingSM,borderTop:`1px solid ${a.colorBorder}`,background:a.colorBgContainer,display:"flex",gap:a.marginXS,overflowX:"auto",maxHeight:80},children:t.map((p,g)=>r.jsx("div",{style:{minWidth:60,height:60,border:g===i?`2px solid ${a.colorPrimary}`:`1px solid ${a.colorBorder}`,borderRadius:a.borderRadius,overflow:"hidden",cursor:"pointer",opacity:g===i?1:.7},onClick:()=>l(g),children:r.jsx("img",{src:p.preview,alt:p.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},p.id))})]})},Yr=e=>/\s/.test(e),aj=e=>{if(!e)return[{text:"",type:"text"}];const t=[],s=e.length;let n=0;for(;n<s;){const o=e[n],a=n>0?e[n-1]:"",i=o==="/"&&(n===0||Yr(a)),l=o==="@"&&(n===0||Yr(a));if(!i&&!l){let u=n;for(;n<s&&!((e[n]==="/"||e[n]==="@")&&(n===0||Yr(e[n-1])));)n+=1;t.push({text:e.slice(u,n),type:"text"});continue}let c=n+1;for(;c<s&&!Yr(e[c]);)c+=1;const d=e.slice(n,c);i?c===s||Yr(e[c])?t.push({text:d,type:"workflow"}):t.push({text:d,type:"text"}):l&&t.push({text:d,type:"file"}),n=c}return t.length>0?t:[{text:"",type:"text"}]},ij=/(\/)([a-zA-Z0-9_-]*)$/,lj=e=>{if(!e)return{command:null,isTriggerActive:!1,searchText:""};const t=e.match(ij);if(!t)return{command:null,isTriggerActive:!1,searchText:""};const s=t[2]||"",n=!s.includes(" ")&&t.index!==void 0;return{command:s||null,isTriggerActive:n,searchText:s}},cj=/@([a-zA-Z0-9._\-\/\\]*)$/,dj=e=>{if(!e)return{isTriggerActive:!1,searchText:"",tokenStart:null};const t=e.match(cj);if(!t||t.index===void 0)return{isTriggerActive:!1,searchText:"",tokenStart:null};const s=t[1]||"",n=t.index;return{isTriggerActive:!s.includes(" "),searchText:s,tokenStart:n}},uj=(e,t=80)=>{const[s,n]=m.useState(e);return m.useEffect(()=>{const o=window.setTimeout(()=>{n(e)},t);return()=>{window.clearTimeout(o)}},[e,t]),s},{Text:mj}=le,hj=({visible:e,token:t})=>e?r.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:t.colorPrimaryBg,borderRadius:t.borderRadius,zIndex:10,pointerEvents:"none"},children:r.jsxs(X,{direction:"vertical",align:"center",children:[r.jsx(bx,{style:{fontSize:32,color:t.colorPrimary}}),r.jsx(mj,{style:{color:t.colorPrimary,fontWeight:500},children:"Drop images here"})]})}):null,{Text:lh}=le,pj=({images:e,token:t,allowImages:s,onPreview:n,onClear:o})=>{const{t:a}=ne();return!s||e.length===0?null:r.jsx("div",{style:{marginBottom:t.marginSM,padding:`${t.paddingXXS}px ${t.paddingXS}px`,borderRadius:999,border:`1px solid ${t.colorBorderSecondary}`,background:t.colorFillSecondary},children:r.jsxs(G,{align:"center",wrap:"wrap",gap:t.marginXS,children:[r.jsx(lh,{type:"secondary",style:{fontSize:t.fontSizeSM,minWidth:"fit-content"},children:e.length>1?a("chat.input.imageCountPlural",{count:e.length}):a("chat.input.imageCountSingular",{count:e.length})}),e.slice(0,3).map(i=>r.jsx("div",{style:{position:"relative",width:32,height:32,borderRadius:999,overflow:"hidden",border:`1px solid ${t.colorBorderSecondary}`,cursor:"pointer"},onClick:()=>n(i),children:r.jsx("img",{src:i.preview,alt:i.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},i.id)),e.length>3&&r.jsx(lh,{type:"secondary",style:{fontSize:t.fontSizeSM},children:a("chat.input.moreImages",{count:e.length-3})}),r.jsx(Y,{type:"text",size:"small",icon:r.jsx(wr,{}),onClick:o,style:{marginLeft:"auto",minWidth:"auto",padding:"0 4px",height:24},title:a("chat.input.clearAllImages")})]})})},{TextArea:fj}=me,gj=({value:e,placeholder:t,disabled:s,token:n,highlightSegments:o,textAreaRef:a,highlightOverlayRef:i,onChange:l,onKeyDown:c,onPaste:d,onScrollSync:u})=>{const h=e.length>0&&o.some(f=>f.type!=="text"),p="6px 4px",g=1.65,y=s?n.colorTextDisabled:n.colorText;return r.jsxs("div",{style:{position:"relative",flex:1},children:[h?r.jsxs("div",{ref:i,"aria-hidden":!0,style:{position:"absolute",top:0,left:0,right:0,bottom:0,padding:p,whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"anywhere",overflow:"hidden",pointerEvents:"none",color:"transparent",fontSize:n.fontSize,lineHeight:g,fontFamily:"inherit",fontWeight:400,letterSpacing:"normal",transform:"translate(0, 0)",zIndex:0},children:[o.map((f,v)=>{let b;return f.type==="workflow"?b={backgroundColor:n.colorPrimaryBg,color:"transparent",WebkitTextFillColor:"transparent",fontWeight:400,textDecoration:"underline",textDecorationStyle:"dotted",textDecorationColor:n.colorPrimary}:f.type==="file"&&(b={backgroundColor:n.colorSuccessBg,color:"transparent",WebkitTextFillColor:"transparent"}),r.jsx("span",{style:b,children:f.text},`segment-${v}`)}),e.endsWith(`
|
|
152
|
+
${e.stack}`:""]})]})},_k=15e3,Tk=()=>{const e=N(a=>a.chats),t=N(a=>a.updateSession),{generateChatTitle:s}=Ud({chats:e,updateSession:t}),n=m.useRef(new Map),o=m.useRef(new Map);return m.useEffect(()=>{e.forEach(a=>{const i=a.id,l=a.messages;if(l.length===0)return;const c=l[l.length-1];if(c.role!=="assistant")return;const d=n.current.get(i);if(c.id===d)return;const u=o.current.get(i);u&&u.messageId===c.id&&Date.now()-u.at<_k||s(i).then(h=>{h&&(n.current.set(i,c.id),o.current.delete(i))}).catch(h=>{o.current.set(i,{messageId:c.id,at:Date.now()}),console.warn("Auto title generation failed for chat",i,":",h)})})},[e,s]),m.useEffect(()=>{const a=new Set(e.map(l=>l.id));Array.from(n.current.keys()).forEach(l=>{a.has(l)||(n.current.delete(l),o.current.delete(l))})},[e]),null},kk=()=>{const{token:e}=he.useToken(),t=Xi(),s=m.useRef("");m.useEffect(()=>{const n=jk(e.colorBgContainer),o=`${n}-${t.theme}-${JSON.stringify(t.themeVariables)}`;if(s.current===o)return;s.current=o;let a=t.theme;(t.theme==="default"||t.theme==="neutral")&&(a=n?"dark":t.theme),ud.initialize({startOnLoad:!1,theme:a,securityLevel:"loose",suppressErrorRendering:!0,fontSize:t.fontSize,themeVariables:Object.keys(t.themeVariables).length>0?t.themeVariables:void 0,flowchart:{useMaxWidth:t.useMaxWidth,htmlLabels:!0,curve:t.flowchartCurve,nodeSpacing:t.flowchartNodeSpacing,rankSpacing:t.flowchartRankSpacing},sequence:{useMaxWidth:t.useMaxWidth,diagramMarginX:10,diagramMarginY:10,actorMargin:t.sequenceActorMargin,width:t.sequenceWidth,height:t.sequenceHeight,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:t.sequenceMessageMargin,mirrorActors:!0,bottomMarginAdj:1,rightAngles:!1,showSequenceNumbers:!1},gantt:{useMaxWidth:t.useMaxWidth,leftPadding:75,gridLineStartPadding:35,barHeight:t.ganttBarHeight,barGap:4,topPadding:t.ganttTopPadding},journey:{useMaxWidth:t.useMaxWidth,diagramMarginX:50,diagramMarginY:10,leftMargin:150,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35,messageAlign:"center"},timeline:{useMaxWidth:t.useMaxWidth,diagramMarginX:50,diagramMarginY:10,leftMargin:150,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35},gitGraph:{useMaxWidth:t.useMaxWidth,showBranches:!0,showCommitLabel:!0},c4:{useMaxWidth:t.useMaxWidth,diagramMarginX:50,diagramMarginY:10,c4ShapeMargin:50,c4ShapePadding:20,width:216,height:60,boxMargin:10},sankey:{useMaxWidth:t.useMaxWidth},xyChart:{useMaxWidth:t.useMaxWidth},block:{useMaxWidth:t.useMaxWidth,padding:8}})},[e,t])};function jk(e){if(e.startsWith("#")){const s=e.slice(1),n=parseInt(s.substr(0,2),16),o=parseInt(s.substr(2,2),16),a=parseInt(s.substr(4,2),16);return(.299*n+.587*o+.114*a)/255<.5}const t=e.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(t){const s=parseInt(t[1]),n=parseInt(t[2]),o=parseInt(t[3]);return(.299*s+.587*n+.114*o)/255<.5}return!1}ud.initialize({startOnLoad:!1,theme:"dark",securityLevel:"loose",suppressErrorRendering:!0});ud.parseError=function(e){console.warn("Mermaid parse error (handled gracefully):",e)};const th=new Map,Ck=/^(\s*%%\{[\s\S]*?\}%%\s*)*\s*gantt\b/i,Mk=e=>e.replace(/:/g,":").replace(/,/g,",").replace(/;/g,";").replace(/(/g,"(").replace(/)/g,")").replace(/-/g,"-"),Pk=e=>(Ck.test(e)?Mk(e):e).replace(/\[([\s\S]*?)\]/g,(s,n)=>{const o=String(n),a=/\r?\n/.test(o),i=/[()]/.test(o),l=/@/.test(o);if(!a&&!i&&!l)return s;const c=o.trim(),d=c.startsWith("(")&&c.endsWith(")")&&c.length>=2;let u=o;return a&&(u=u.replace(/\r?\n/g,"<br/>")),i&&!d&&(u=u.replace(/\(/g,"(").replace(/\)/g,")")),l&&(u=u.replace(/@/g,"@")),u===o?s:`[${u}]`}),Ek=200,Ts=new Map,li=new Map;let El=null;const Rk=e=>{const s=new DOMParser().parseFromString(e,"image/svg+xml");return Array.from(s.querySelectorAll("rect")).reduce((o,a)=>{const i=Number(a.getAttribute("width"));return Number.isFinite(i)&&i<0?o+1:o},0)};async function Ak(){El||(El=Dt(()=>import("./vendor-mermaid-Siz_U5T6.js").then(t=>t.bd),__vite__mapDeps([7,1,2,3,6]),import.meta.url));const e=await El;return e.default??e}function Ik(e,t){if(Ts.has(e)&&Ts.delete(e),Ts.set(e,t),Ts.size>Ek){const s=Ts.keys().next().value;s&&Ts.delete(s)}}function ci(e){const t=Ts.get(e);return t?(Ts.delete(e),Ts.set(e,t),t):null}function sh(){Ts.clear(),li.clear()}function $k(e,t){const s=ci(e);if(s)return Promise.resolve(s);const n=li.get(e);if(n)return n;const o=(async()=>{var x,_;const a=await Ak();await a.parse(t);const i=`mermaid-${e}`,l=document.createElement("div"),c=Math.max(1600,window.innerWidth||0,((x=document.documentElement)==null?void 0:x.clientWidth)||0);l.style.cssText=["position:absolute","left:-9999px","top:-9999px",`width:${c}px`,`min-width:${c}px`,"visibility:hidden","pointer-events:none","overflow:visible"].join(";"),document.body.appendChild(l);let d;try{d=await a.render(i,t,l)}finally{document.body.removeChild(l)}const u=typeof d=="object"&&"svg"in d?d.svg:String(d),h=Rk(u);if(h>0)throw new Error(`Mermaid rendered invalid SVG (${h} rect widths < 0)`);const y=new DOMParser().parseFromString(u,"image/svg+xml").querySelector("svg");let f=800,v=300;if(y){const w=y.getAttribute("viewBox");if(w){const k=w.split(/\s+/).map(Number);k.length===4&&(f=k[2]||800,v=k[3]||300)}if(f===800&&v===300){const k=document.createElement("div");k.style.cssText="position:absolute;visibility:hidden;width:800px;",k.innerHTML=u,document.body.appendChild(k);const C=(_=k.querySelector("svg"))==null?void 0:_.getBoundingClientRect();C&&(f=C.width,v=C.height),document.body.removeChild(k)}}const b={svg:u,width:f,height:v};return Ik(e,b),b})().finally(()=>{li.delete(e)});return li.set(e,o),o}const Dk=e=>{const t=e;return(t==null?void 0:t.name)==="AbortError"||(t==null?void 0:t.code)===20},nh=220,rh=e=>{const t=e.replace(/\s+/g," ").trim();return t.length<=nh?t:`${t.slice(0,nh)}...`},Lk=e=>e==="pending"||e==="in_progress"||e==="completed"||e==="blocked",Wa=e=>{const t=e.trim().toLowerCase();return t==="memory_note"||t==="session_note"};function Ok(){const e=N(j=>j.processingChats),t=N(j=>j.addMessage),s=N(j=>j.setSessionProcessing),n=N(j=>j.updateTokenUsage),o=N(j=>j.setTruncationInfo),a=N(j=>j.updateSession),i=N(j=>j.updateMessage),l=N(j=>j.setTaskList),c=N(j=>j.updateTaskListDelta),d=N(j=>j.setEvaluationState),u=N(j=>j.upsertSubSessionProgress),h=N(j=>j.refreshChats),p=m.useRef(new rs),g=m.useRef(new Map),y=m.useRef(new Map),f=m.useRef(new Map),v=m.useRef(new Map),b=m.useRef(new Map),x=m.useRef(new Set),_=m.useRef(new Map),w=m.useCallback(j=>{const R=_.current.get(j);R!=null&&R.timer&&clearTimeout(R.timer),_.current.delete(j)},[]),k=m.useCallback((j,R)=>{w(j),x.current.delete(j);const M=g.current.get(j);if(!M)return;g.current.delete(j),M.controller.abort(),ze.forceFlush();const T=y.current.get(M.sessionId);T?(R!=null&&R.clearDraft&&(ze.clear(T.sessionId,T.messageId),ze.clear(T.sessionId,T.reasoningMessageId),ze.clear(T.sessionId,T.statusMessageId)),y.current.delete(M.sessionId)):R!=null&&R.clearDraft&&(ze.clear(j,`streaming-${j}`),ze.clear(j,`streaming-reasoning-${j}`),ze.clear(j,`streaming-status-${j}`))},[w]),C=m.useCallback(j=>{w(j);const R=new AbortController;g.current.set(j,{sessionId:j,controller:R});const M=`streaming-${j}`,T=`streaming-reasoning-${j}`,P=`streaming-status-${j}`,S=ze.getLatest(M),L=ze.getLatest(T),$=ze.getLatest(P);y.current.set(j,{sessionId:j,messageId:M,content:S??"",reasoningMessageId:T,reasoningContent:L??"",statusMessageId:P,status:$??""});const I=A=>{const O=y.current.get(j);if(!O)return;const D=(A??"").trim();if(!D){if(!O.status)return;O.status="",ze.clear(O.sessionId,O.statusMessageId);return}O.status!==D&&(O.status=D,ze.publish({sessionId:O.sessionId,messageId:O.statusMessageId,content:O.status}))};S===null&&ze.publish({sessionId:j,messageId:M,content:""});const W=()=>{const A=_.current.get(j),O=(A==null?void 0:A.attempt)??0,D=Math.min(5e3,250*Math.pow(2,O));k(j,{clearDraft:!1});const H=setTimeout(()=>{var F;if(_.current.delete(j),!N.getState().processingChats.has(j))return;const B=N.getState().chats.find(z=>z.id===j),K=(F=B==null?void 0:B.id)==null?void 0:F.trim();K&&C(K)},D);_.current.set(j,{attempt:O+1,timer:H})};p.current.subscribeToEvents(j,{onToken:A=>{const O=y.current.get(j);O&&(I(null),O.content+=A,ze.publish({sessionId:O.sessionId,messageId:O.messageId,content:O.content}))},onReasoningToken:A=>{const O=y.current.get(j);O&&(O.reasoningContent+=A,ze.publish({sessionId:O.sessionId,messageId:O.reasoningMessageId,content:O.reasoningContent}))},onToolStart:(A,O,D)=>{var $e,De;const H=y.current.get(j),B=(H==null?void 0:H.content)||"",K=(H==null?void 0:H.reasoningContent)||"",F=B.trim().length>0,z=K.trim().length>0;if(F||z){const be=N.getState().chats.find(ht=>ht.id===j),ye=($e=be==null?void 0:be.messages)==null?void 0:$e[be.messages.length-1],je=typeof((De=ye==null?void 0:ye.metadata)==null?void 0:De.reasoning)=="string"?ye.metadata.reasoning:"";(ye==null?void 0:ye.role)==="assistant"&&(ye==null?void 0:ye.type)==="text"&&typeof(ye==null?void 0:ye.content)=="string"&&ye.content===B&&je===K||t(j,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:B,createdAt:new Date().toISOString(),metadata:{sessionId:j,model:"agent",...z?{reasoning:K}:{}}}),H&&(H.content="",H.reasoningContent="",H.status&&(H.status="",ze.clear(H.sessionId,H.statusMessageId)),ze.publish({sessionId:H.sessionId,messageId:H.messageId,content:""}),ze.publish({sessionId:H.sessionId,messageId:H.reasoningMessageId,content:""}))}v.current.set(A,O);const de=O.trim().toLowerCase();Wa(O)?I("memory_updating"):I(`tool_running:${de||"tool"}`);const Te=crypto.randomUUID();b.current.set(A,Te),t(j,{id:Te,role:"assistant",type:"tool_call",toolCalls:[{toolCallId:A,toolName:O,parameters:D||{},streamingOutput:""}],metadata:{},createdAt:new Date().toISOString()})},onToolToken:(A,O)=>{const D=b.current.get(A),H=N.getState().chats.find(z=>z.id===j);if(!H)return;const B=(D?H==null?void 0:H.messages.find(z=>z.id===D):null)||(H==null?void 0:H.messages[H.messages.length-1]);if(!B||!("type"in B)||B.type!=="tool_call"||!("toolCalls"in B)||!Array.isArray(B.toolCalls))return;const K=B.toolCalls.find(z=>z.toolCallId===A);K&&!v.current.has(A)&&(v.current.set(A,K.toolName),b.current.set(A,B.id));const F=B.toolCalls.map(z=>{if(z.toolCallId!==A)return z;const de=(z.streamingOutput||"")+(O||"");return{...z,streamingOutput:de}});i(j,B.id,{toolCalls:F})},onToolComplete:(A,O)=>{const D=v.current.get(A)||"unknown";v.current.delete(A),b.current.delete(A);const H=D.trim().toLowerCase(),B=y.current.get(j);(Wa(D)?(B==null?void 0:B.status)==="memory_updating":!!(B!=null&&B.status&&B.status.includes(H)))&&I(null);const F=(O==null?void 0:O.display_preference)||"Default";t(j,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:D,toolCallId:A,result:{tool_name:D,result:(O==null?void 0:O.result)??"",display_preference:F},isError:!(O!=null&&O.success),createdAt:new Date().toISOString()})},onToolError:(A,O)=>{v.current.delete(A),b.current.delete(A),I(null),t(j,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:"unknown",toolCallId:A,result:{tool_name:"unknown",result:O,display_preference:"Default"},isError:!0,createdAt:new Date().toISOString()})},onToolLifecycle:(A,O,D,H,B)=>{if(D==="begin"){const K=(O||"").trim().toLowerCase();Wa(O||"")?I("memory_updating"):I(`tool_running:${K||"tool"}`)}if(D==="finished"||D==="error"||D==="cancelled"){const K=b.current.get(A);K&&i(j,K,{metadata:{elapsed_ms:H,is_mutating:B}});const F=(O||"").trim().toLowerCase(),z=y.current.get(j);(Wa(O||"")?(z==null?void 0:z.status)==="memory_updating":!!(z!=null&&z.status&&z.status.includes(F)))&&I(null)}},onContextCompressionStatus:(A,O)=>{if(O==="started"){I("context_compacting");return}if(O==="degraded_sections"){I("context_compaction_degraded");return}if(O==="failed"){I("context_compaction_failed");return}I(null)},onTokenBudgetUpdated:A=>{const O=typeof A.max_context_tokens=="number"&&A.max_context_tokens>0?A.max_context_tokens:void 0,D={systemTokens:A.system_tokens,summaryTokens:A.summary_tokens,windowTokens:A.window_tokens,totalTokens:A.total_tokens,budgetLimit:A.budget_limit,...O?{maxContextTokens:O}:{},...typeof A.prompt_cached_tool_outputs=="number"&&A.prompt_cached_tool_outputs>0?{promptCachedToolOutputs:A.prompt_cached_tool_outputs}:{}};n(j,D),o(j,A.truncation_occurred,A.segments_removed);const H=N.getState().chats.find(B=>B.id===j);H&&a(j,{config:{...H.config,tokenUsage:D,truncationOccurred:A.truncation_occurred,segmentsRemoved:A.segments_removed}})},onContextSummarized:A=>{I(null),fe.info(`Conversation summarized: ${A.messages_summarized} messages compressed, saved ${A.tokens_saved.toLocaleString()} tokens`,5)},onTaskListUpdated:A=>{A.session_id&&l(A.session_id,A)},onTaskListItemProgress:A=>{A.session_id&&c(A.session_id,A)},onTaskListCompleted:(A,O,D)=>{fe.success(`All tasks completed! Total rounds: ${O}, Tool calls: ${D}`,3)},onTaskEvaluationStarted:(A,O)=>{d(A,{isEvaluating:!0,reasoning:null,timestamp:Date.now()}),fe.info(`Evaluating ${O} task(s)...`,2)},onTaskEvaluationCompleted:(A,O,D)=>{const H=rh(D);d(A,{isEvaluating:!1,reasoning:O>0?H:null,timestamp:Date.now()}),O>0?fe.success(`Evaluation complete: ${O} task(s) updated.`,3):fe.info("Evaluation complete: No updates needed",2)},onComplete:()=>{const A=R;(async()=>{var de,Te,$e;I(null),ze.forceFlush();const O=()=>{const De=g.current.get(j);return De!=null&&De.controller!==A};if(O())return;const D=y.current.get(j),H=(D==null?void 0:D.content)||"",B=(D==null?void 0:D.reasoningContent)||"",K=H.trim().length>0,F=B.trim().length>0;if(K||F){const De=N.getState().chats.find(Ue=>Ue.id===j),be=(de=De==null?void 0:De.messages)==null?void 0:de[De.messages.length-1],ye=typeof((Te=be==null?void 0:be.metadata)==null?void 0:Te.reasoning)=="string"?be.metadata.reasoning:"";(be==null?void 0:be.role)==="assistant"&&(be==null?void 0:be.type)==="text"&&typeof(be==null?void 0:be.content)=="string"&&be.content===H&&ye===B||await t(j,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:H,createdAt:new Date().toISOString(),metadata:{sessionId:j,model:"agent",...F?{reasoning:B}:{}}})}if(O()||(await N.getState().loadChatHistory(j,{mode:"monotonic",retries:4,retryDelayMs:200,waitForAssistant:!0}),O()))return;if(F){const De=N.getState().chats.find(je=>je.id===j),be=[...(De==null?void 0:De.messages)||[]].reverse().find(je=>(je==null?void 0:je.role)==="assistant"&&(je==null?void 0:je.type)==="text"),ye=typeof(($e=be==null?void 0:be.metadata)==null?void 0:$e.reasoning)=="string"&&be.metadata.reasoning.trim().length>0;be!=null&&be.id&&!ye&&i(j,be.id,{metadata:{...be.metadata||{},reasoning:B}})}if(O())return;const z=f.current.get(j)??{children:new Set};if(f.current.set(j,{children:new Set(z.children),parentDone:!0}),z.children.size===0)k(j,{clearDraft:!0}),s(j,!1);else{const De=g.current.get(j);De&&(ze.clear(j,`streaming-${j}`),ze.clear(j,`streaming-reasoning-${j}`),ze.clear(j,`streaming-status-${j}`),y.current.delete(De.sessionId))}})()},onError:async A=>{I(null);const O=Ec(A)?Rc(A):A;await t(j,{id:`error-${Date.now()}`,role:"assistant",type:"text",content:`❌ **Error**: ${O}`,createdAt:new Date().toISOString(),finishReason:"error"});const D=f.current.get(j)??{children:new Set};f.current.set(j,{children:new Set(D.children),parentDone:!0}),D.children.size===0&&(k(j,{clearDraft:!0}),s(j,!1))},onSubSessionStarted:(A,O,D)=>{const H=f.current.get(A)??{children:new Set,parentDone:!1},B=new Set(H.children);B.add(O),f.current.set(A,{children:B,parentDone:H.parentDone}),s(j,!0),u(A,O,{title:D,status:"pending",lastEventAt:new Date().toISOString()}),h()},onSubSessionEvent:(A,O,D)=>{var H,B,K;if(D.type==="task_list_updated"&&D.task_list){const F=D.task_list.session_id||A;l(F,D.task_list);return}if(D.type==="task_list_item_progress"){const F=D.session_id||A;typeof D.item_id=="string"&&Lk(D.status)&&typeof D.tool_calls_count=="number"&&typeof D.version=="number"&&c(F,{session_id:F,item_id:D.item_id,status:D.status,tool_calls_count:D.tool_calls_count,version:D.version});return}if(D.type==="task_evaluation_started"){const F=D.session_id||A;d(F,{isEvaluating:!0,reasoning:null,timestamp:Date.now()});return}if(D.type==="task_evaluation_completed"){const F=D.session_id||A,z=D.updates_count??0;d(F,{isEvaluating:!1,reasoning:z>0?rh(D.reasoning??""):null,timestamp:Date.now()});return}if(D.type==="token"&&typeof D.content=="string"){const z=((((K=(B=(H=N.getState().subSessionsByParent)==null?void 0:H[A])==null?void 0:B[O])==null?void 0:K.outputPreview)||"")+D.content).slice(-2e3);u(A,O,{status:"running",outputPreview:z,lastEventAt:new Date().toISOString()})}else u(A,O,{status:"running",lastEventAt:new Date().toISOString()})},onSubSessionHeartbeat:(A,O,D)=>{u(A,O,{status:"running",lastHeartbeatAt:D})},onSubSessionCompleted:(A,O,D,H)=>{const B=f.current.get(A)??{children:new Set,parentDone:!1},K=new Set(B.children);K.delete(O),f.current.set(A,{children:K,parentDone:B.parentDone}),u(A,O,{status:D,error:H,lastEventAt:new Date().toISOString()}),B.parentDone&&K.size===0&&(k(j,{clearDraft:!0}),s(j,!1)),h()}},R).then(()=>{if(R.signal.aborted)return;const A=g.current.get(j);if(A&&A.controller!==R)return;if(!N.getState().processingChats.has(j)){k(j,{clearDraft:!0});return}W()}).catch(A=>{if(!R.signal.aborted){if(Dk(A)){if(!N.getState().processingChats.has(j)){k(j,{clearDraft:!0});return}W();return}console.error("[useAgentEventSubscription] Subscription error:",A),k(j,{clearDraft:!0}),s(j,!1)}})},[t,k,w,h,d,s,l,o,i,a,c,n,u]),E=m.useCallback(j=>{const R=j.trim();if(!R)return;x.current.delete(R);const M=g.current.get(R);(M==null?void 0:M.sessionId)===R&&!M.controller.signal.aborted||(M&&k(R,{clearDraft:!1}),C(R))},[k,C]);m.useEffect(()=>{e.forEach(j=>E(j));for(const j of Array.from(g.current.keys()))e.has(j)||k(j,{clearDraft:!0});for(const j of Array.from(x.current))e.has(j)||x.current.delete(j)},[e,E,k]),m.useEffect(()=>N.subscribe(j=>j.chats,()=>{if(x.current.size!==0)for(const j of Array.from(x.current)){if(!N.getState().processingChats.has(j)){x.current.delete(j);continue}E(j)}}),[E]),m.useEffect(()=>{const j=g.current;return()=>{const R=Array.from(j.keys());for(const M of R)k(M,{clearDraft:!0})}},[k])}const zy=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_result",Fk=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_call",zk=e=>e.role==="assistant"&&"type"in e&&e.type==="workflow_result",Nk=e=>e.role==="user"&&"type"in e&&e.type==="file_reference",Bk=e=>e.role==="assistant"&&"type"in e&&e.type==="task_list",Pi=["image/jpeg","image/jpg","image/png","image/gif","image/webp","image/bmp"],oh=10*1024*1024,Wk=2048,Uk=2048,qk=.82,Hk=512*1024,Yk=e=>Pi.includes(e.type)?e.size>oh?{isValid:!1,error:`Image size too large: ${(e.size/1024/1024).toFixed(2)}MB. Maximum size: ${oh/1024/1024}MB`}:{isValid:!0}:{isValid:!1,error:`Unsupported image type: ${e.type}. Supported types: ${Pi.join(", ")}`},Xk=e=>new Promise((t,s)=>{const n=new Image;n.onload=()=>t(n),n.onerror=()=>s(new Error("Failed to load image")),n.src=e}),ah=e=>new Promise((t,s)=>{const n=new FileReader;n.onload=()=>{typeof n.result=="string"?t(n.result):s(new Error("Failed to convert file to base64"))},n.onerror=()=>s(new Error("Failed to read file")),n.readAsDataURL(e)}),Vk=e=>URL.createObjectURL(e),Kk=(e,t,s,n)=>{let{width:o,height:a}=t;if(o>s||a>n){const l=o/a;o>a?(o=s,a=Math.round(o/l)):(a=n,o=Math.round(a*l))}e.width=o,e.height=a;const i=e.getContext("2d");i&&(i.fillStyle="#ffffff",i.fillRect(0,0,o,a),i.drawImage(t,0,0,o,a))},Gk=async(e,t)=>{const s=await Xk(e),n=document.createElement("canvas");return Kk(n,s,Wk,Uk),Zk(n,t)},Jk=async e=>{const t=Yk(e);if(!t.isValid)throw new Error(t.error);const s=Vk(e);try{let n;if(e.type==="image/gif"||e.size<Hk)n=await ah(e);else try{n=await Gk(s,qk)}catch(a){console.warn("[imageUtils] Failed to re-encode image, using original:",a),n=await ah(e)}const o=`img_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return{file:e,base64:n,preview:s,id:o,name:e.name,size:e.size,type:e.type}}catch(n){throw Ny(s),n}},Qk=async e=>{const t=Array.from(e),s=[];for(const n of t)try{const o=await Jk(n);s.push(o)}catch(o){console.error(`Failed to process image ${n.name}:`,o)}return s},Zk=(e,t=.8)=>e.toDataURL("image/jpeg",t),Ny=e=>{e.startsWith("blob:")&&URL.revokeObjectURL(e)},ih=e=>{e.forEach(t=>Ny(t.preview))},ej=e=>{if(e===0)return"0 Bytes";const t=1024,s=["Bytes","KB","MB","GB"],n=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,n)).toFixed(2))+" "+s[n]},tj=e=>!e.files||e.files.length===0?!1:Array.from(e.files).some(t=>Pi.includes(t.type)),sj=e=>e.files?Array.from(e.files).filter(t=>Pi.includes(t.type)):[],{Text:nj,Title:rj}=le,oj=({visible:e,images:t,currentIndex:s=0,onClose:n,onDownload:o})=>{const{token:a}=he.useToken(),[i,l]=m.useState(s);if(!t||t.length===0)return null;const c=t[i],d=()=>{if(o&&c)o(c);else{const p=document.createElement("a");p.href=c.base64,p.download=c.name,document.body.appendChild(p),p.click(),document.body.removeChild(p)}},u=()=>{l(p=>p>0?p-1:t.length-1)},h=()=>{l(p=>p<t.length-1?p+1:0)};return r.jsxs(Lt,{open:e,onCancel:n,footer:null,width:"90vw",style:{top:20},styles:{body:{padding:0,height:"80vh",display:"flex",flexDirection:"column"}},closeIcon:r.jsx(wr,{style:{color:a.colorTextLightSolid}}),children:[r.jsx("div",{style:{padding:a.paddingMD,borderBottom:`1px solid ${a.colorBorder}`,background:a.colorBgContainer},children:r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",width:"100%"},children:[r.jsxs("div",{children:[r.jsx(rj,{level:5,style:{margin:0},children:c.name}),r.jsxs(nj,{type:"secondary",style:{fontSize:a.fontSizeSM},children:[ej(c.size)," • ",c.type,t.length>1&&` • ${i+1} of ${t.length}`]})]}),r.jsxs(X,{children:[t.length>1&&r.jsxs(r.Fragment,{children:[r.jsx(Y,{icon:r.jsx(du,{}),onClick:u,disabled:t.length<=1}),r.jsx(Y,{icon:r.jsx(Ws,{}),onClick:h,disabled:t.length<=1})]}),r.jsx(Y,{icon:r.jsx(yr,{}),onClick:d,children:"Download"})]})]})}),r.jsxs("div",{style:{flex:1,display:"flex",justifyContent:"center",alignItems:"center",background:a.colorBgLayout,position:"relative",overflow:"hidden"},children:[t.length===1?r.jsx("img",{src:c.preview,alt:c.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}}):r.jsx(yx,{dots:!1,arrows:!0,infinite:!0,afterChange:l,style:{width:"100%",height:"100%"},children:t.map(p=>r.jsx("div",{children:r.jsx("div",{style:{height:"70vh",display:"flex",justifyContent:"center",alignItems:"center"},children:r.jsx("img",{src:p.preview,alt:p.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}})})},p.id))}),t.length>1&&r.jsxs(r.Fragment,{children:[r.jsx(Y,{type:"primary",shape:"circle",icon:r.jsx(du,{}),onClick:u,style:{position:"absolute",left:20,top:"50%",transform:"translateY(-50%)",zIndex:10}}),r.jsx(Y,{type:"primary",shape:"circle",icon:r.jsx(Ws,{}),onClick:h,style:{position:"absolute",right:20,top:"50%",transform:"translateY(-50%)",zIndex:10}})]})]}),t.length>1&&r.jsx("div",{style:{padding:a.paddingSM,borderTop:`1px solid ${a.colorBorder}`,background:a.colorBgContainer,display:"flex",gap:a.marginXS,overflowX:"auto",maxHeight:80},children:t.map((p,g)=>r.jsx("div",{style:{minWidth:60,height:60,border:g===i?`2px solid ${a.colorPrimary}`:`1px solid ${a.colorBorder}`,borderRadius:a.borderRadius,overflow:"hidden",cursor:"pointer",opacity:g===i?1:.7},onClick:()=>l(g),children:r.jsx("img",{src:p.preview,alt:p.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},p.id))})]})},Yr=e=>/\s/.test(e),aj=e=>{if(!e)return[{text:"",type:"text"}];const t=[],s=e.length;let n=0;for(;n<s;){const o=e[n],a=n>0?e[n-1]:"",i=o==="/"&&(n===0||Yr(a)),l=o==="@"&&(n===0||Yr(a));if(!i&&!l){let u=n;for(;n<s&&!((e[n]==="/"||e[n]==="@")&&(n===0||Yr(e[n-1])));)n+=1;t.push({text:e.slice(u,n),type:"text"});continue}let c=n+1;for(;c<s&&!Yr(e[c]);)c+=1;const d=e.slice(n,c);i?c===s||Yr(e[c])?t.push({text:d,type:"workflow"}):t.push({text:d,type:"text"}):l&&t.push({text:d,type:"file"}),n=c}return t.length>0?t:[{text:"",type:"text"}]},ij=/(\/)([a-zA-Z0-9_-]*)$/,lj=e=>{if(!e)return{command:null,isTriggerActive:!1,searchText:""};const t=e.match(ij);if(!t)return{command:null,isTriggerActive:!1,searchText:""};const s=t[2]||"",n=!s.includes(" ")&&t.index!==void 0;return{command:s||null,isTriggerActive:n,searchText:s}},cj=/@([a-zA-Z0-9._\-\/\\]*)$/,dj=e=>{if(!e)return{isTriggerActive:!1,searchText:"",tokenStart:null};const t=e.match(cj);if(!t||t.index===void 0)return{isTriggerActive:!1,searchText:"",tokenStart:null};const s=t[1]||"",n=t.index;return{isTriggerActive:!s.includes(" "),searchText:s,tokenStart:n}},uj=(e,t=80)=>{const[s,n]=m.useState(e);return m.useEffect(()=>{const o=window.setTimeout(()=>{n(e)},t);return()=>{window.clearTimeout(o)}},[e,t]),s},{Text:mj}=le,hj=({visible:e,token:t})=>e?r.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:t.colorPrimaryBg,borderRadius:t.borderRadius,zIndex:10,pointerEvents:"none"},children:r.jsxs(X,{direction:"vertical",align:"center",children:[r.jsx(bx,{style:{fontSize:32,color:t.colorPrimary}}),r.jsx(mj,{style:{color:t.colorPrimary,fontWeight:500},children:"Drop images here"})]})}):null,{Text:lh}=le,pj=({images:e,token:t,allowImages:s,onPreview:n,onClear:o})=>{const{t:a}=ne();return!s||e.length===0?null:r.jsx("div",{style:{marginBottom:t.marginSM,padding:`${t.paddingXXS}px ${t.paddingXS}px`,borderRadius:999,border:`1px solid ${t.colorBorderSecondary}`,background:t.colorFillSecondary},children:r.jsxs(G,{align:"center",wrap:"wrap",gap:t.marginXS,children:[r.jsx(lh,{type:"secondary",style:{fontSize:t.fontSizeSM,minWidth:"fit-content"},children:e.length>1?a("chat.input.imageCountPlural",{count:e.length}):a("chat.input.imageCountSingular",{count:e.length})}),e.slice(0,3).map(i=>r.jsx("div",{style:{position:"relative",width:32,height:32,borderRadius:999,overflow:"hidden",border:`1px solid ${t.colorBorderSecondary}`,cursor:"pointer"},onClick:()=>n(i),children:r.jsx("img",{src:i.preview,alt:i.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},i.id)),e.length>3&&r.jsx(lh,{type:"secondary",style:{fontSize:t.fontSizeSM},children:a("chat.input.moreImages",{count:e.length-3})}),r.jsx(Y,{type:"text",size:"small",icon:r.jsx(wr,{}),onClick:o,style:{marginLeft:"auto",minWidth:"auto",padding:"0 4px",height:24},title:a("chat.input.clearAllImages")})]})})},{TextArea:fj}=me,gj=({value:e,placeholder:t,disabled:s,token:n,highlightSegments:o,textAreaRef:a,highlightOverlayRef:i,onChange:l,onKeyDown:c,onPaste:d,onScrollSync:u})=>{const h=e.length>0&&o.some(f=>f.type!=="text"),p="6px 4px",g=1.65,y=s?n.colorTextDisabled:n.colorText;return r.jsxs("div",{style:{position:"relative",flex:1},children:[h?r.jsxs("div",{ref:i,"aria-hidden":!0,style:{position:"absolute",top:0,left:0,right:0,bottom:0,padding:p,whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"anywhere",overflow:"hidden",pointerEvents:"none",color:"transparent",fontSize:n.fontSize,lineHeight:g,fontFamily:"inherit",fontWeight:400,letterSpacing:"normal",transform:"translate(0, 0)",zIndex:0},children:[o.map((f,v)=>{let b;return f.type==="workflow"?b={backgroundColor:n.colorPrimaryBg,color:"transparent",WebkitTextFillColor:"transparent",fontWeight:400,textDecoration:"underline",textDecorationStyle:"dotted",textDecorationColor:n.colorPrimary}:f.type==="file"&&(b={backgroundColor:n.colorSuccessBg,color:"transparent",WebkitTextFillColor:"transparent"}),r.jsx("span",{style:b,children:f.text},`segment-${v}`)}),e.endsWith(`
|
|
153
153
|
`)?`
|
|
154
154
|
`:null]}):null,r.jsx(fj,{"data-testid":"chat-input",ref:a,value:e,onChange:f=>l(f.target.value),onKeyDown:c,onPaste:d,placeholder:t,disabled:s,autoSize:{minRows:3,maxRows:8},variant:"borderless",onScroll:u,className:"lotus-message-input-field",style:{resize:"none",flex:1,fontSize:n.fontSize,padding:p,lineHeight:g,border:"none",outline:"none",background:"transparent",color:y,WebkitTextFillColor:y,caretColor:y,position:"relative",zIndex:1,whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"anywhere",overflowY:"auto"}})]})},yj=({allowImages:e,disabled:t,isStreaming:s,token:n,fileInputRef:o,onFileInputChange:a,onFileReferenceButtonClick:i,extraControl:l})=>{const{t:c}=ne();return r.jsxs(G,{align:"center",style:{minWidth:0,gap:0},children:[e&&r.jsxs(r.Fragment,{children:[r.jsx("input",{ref:o,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:a}),r.jsx(Y,{type:"text",icon:r.jsx(Us,{}),onClick:()=>{var d;return(d=o.current)==null?void 0:d.click()},disabled:t||s,size:"small",style:{minWidth:36,padding:"0 8px",height:36,borderRadius:18,color:n.colorTextSecondary},title:c("chat.input.addAttachments"),"aria-label":c("chat.input.addAttachments")})]}),i&&r.jsx(Y,{type:"text",icon:r.jsx(br,{}),onClick:i,disabled:t||s,size:"small",style:{minWidth:36,padding:"0 8px",height:36,borderRadius:18,color:n.colorTextSecondary},title:c("chat.input.referenceWorkspaceFiles"),"aria-label":c("chat.input.referenceWorkspaceFiles")}),l]})},bj=({allowRetry:e,hasMessages:t,isStreaming:s,disabled:n,onRetry:o,onCancel:a,onSubmit:i,value:l,images:c,isOverCharLimit:d,token:u,statusIndicator:h,submitButtonLabel:p})=>{const{t:g}=ne(),y=!l.trim()&&c.length===0,f=s||n||!o,v=p??g("chat.actions.sendMessage");return r.jsxs(G,{align:"center",style:{flex:"0 0 auto",gap:u.marginXS},children:[h?r.jsx("span",{style:{flex:"0 0 auto"},children:h}):null,e&&t&&r.jsx(zn,{trigger:["click"],menu:{items:[{key:"regenerate",label:g("chat.actions.regenerate"),icon:r.jsx(Ms,{})},{key:"error_retry",label:g("chat.actions.retryFailed"),icon:r.jsx(Oi,{})}],onClick:({key:b})=>o==null?void 0:o(b)},disabled:f,children:r.jsx(Y,{"data-testid":"regenerate-button",type:"text",icon:r.jsx(od,{spin:s}),disabled:f,title:g("chat.actions.retryOptions"),"aria-label":g("chat.actions.retryOptions"),size:"small",className:"lotus-secondary-button",style:{minWidth:38,padding:"0 8px",height:38,width:38,borderRadius:19,color:u.colorTextSecondary}})}),r.jsx(Y,{"data-testid":s?"cancel-button":"send-button",type:"primary",icon:s?r.jsx(xx,{}):r.jsx(vx,{}),onClick:s?a:i,loading:s&&!a,disabled:s?!a||n:y||n||d,size:"small",danger:s,className:s?"message-input-send-button":"message-input-send-button lotus-primary-cta",style:{minWidth:50,padding:0,height:50,width:50,borderRadius:25,display:"inline-flex",alignItems:"center",justifyContent:"center",background:s?void 0:"linear-gradient(135deg, var(--lotus-primary) 0%, var(--lotus-accent-secondary) 100%)",border:s?void 0:"none",boxShadow:s?void 0:"var(--lotus-send-btn-shadow)",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",transform:"scale(1)"},title:s?g("chat.actions.cancelRequest"):v,"aria-label":s?g("chat.actions.cancelRequest"):v})]})},{Text:ch}=le,xj=({charCount:e,maxCharCount:t,isOverCharLimit:s,isNearCharLimit:n,isProcessingAttachments:o,token:a})=>{const i=typeof t=="number"&&Number.isFinite(t)&&t>0;return!o&&!n&&!s?null:r.jsxs(r.Fragment,{children:[i&&r.jsx(G,{justify:"flex-end",style:{marginTop:a.marginXXS},children:r.jsxs(ch,{type:s?"danger":n?"warning":"secondary",style:{fontSize:a.fontSizeSM},children:[e.toLocaleString()," / ",t.toLocaleString()]})}),o&&r.jsxs(X,{size:"small",style:{marginTop:a.marginXS},children:[r.jsx(ps,{size:"small"}),r.jsx(ch,{type:"secondary",children:"Processing files…"})]})]})},vj=({onFiles:e,mode:t="images"})=>{const[s,n]=m.useState(!1),o=m.useCallback(l=>{var d,u;l.preventDefault(),l.stopPropagation(),(t==="images"?tj(l.dataTransfer):((u=(d=l.dataTransfer)==null?void 0:d.files)==null?void 0:u.length)>0)&&n(!0)},[t]),a=m.useCallback(l=>{l.preventDefault(),l.stopPropagation(),n(!1)},[]),i=m.useCallback(l=>{if(l.preventDefault(),l.stopPropagation(),n(!1),t==="images"){const d=sj(l.dataTransfer);d.length>0&&e(d);return}const c=Array.from(l.dataTransfer.files||[]);c.length>0&&e(c)},[t,e]);return{isDragOver:s,handleDragOver:o,handleDragLeave:a,handleDrop:i}},Sj=e=>{const{message:t}=Ot.useApp(),[s,n]=m.useState([]),[o,a]=m.useState(!1),[i,l]=m.useState(0),c=m.useCallback(async p=>{if(e)try{const g=await Qk(p);g.length>0&&(n(y=>[...y,...g]),t.success(`Added ${g.length} image(s)`))}catch(g){t.error(`Failed to process images: ${g}`)}},[e,t]),d=m.useCallback(p=>{const g=s.find(y=>y.id===p);g&&ih([g]),n(y=>y.filter(f=>f.id!==p))},[s]),u=m.useCallback(p=>{const g=s.findIndex(y=>y.id===p.id);l(g>=0?g:0),a(!0)},[s]),h=m.useCallback(()=>{ih(s),n([])},[s]);return{images:s,setImages:n,previewModalVisible:o,setPreviewModalVisible:a,previewImageIndex:i,handleImageFiles:c,handleRemoveImage:d,handleImagePreview:u,clearImages:h}},wj=({onImages:e,onAttachments:t,allowImages:s})=>({handlePaste:m.useCallback(o=>{if(!o.clipboardData)return;const a=Array.from(o.clipboardData.items),i=[],l=[];a.forEach(c=>{if(c.kind==="file"){const d=c.getAsFile();if(!d)return;d.type.startsWith("image/")?i.push(d):l.push(d)}}),i.length>0&&s&&(o.preventDefault(),e(i)),l.length>0&&t&&(o.preventDefault(),t(l))},[s,e,t])}),bt=[];for(let e=0;e<256;++e)bt.push((e+256).toString(16).slice(1));function _j(e,t=0){return(bt[e[t+0]]+bt[e[t+1]]+bt[e[t+2]]+bt[e[t+3]]+"-"+bt[e[t+4]]+bt[e[t+5]]+"-"+bt[e[t+6]]+bt[e[t+7]]+"-"+bt[e[t+8]]+bt[e[t+9]]+"-"+bt[e[t+10]]+bt[e[t+11]]+bt[e[t+12]]+bt[e[t+13]]+bt[e[t+14]]+bt[e[t+15]]).toLowerCase()}let Rl;const Tj=new Uint8Array(16);function kj(){if(!Rl){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Rl=crypto.getRandomValues.bind(crypto)}return Rl(Tj)}const jj=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),dh={randomUUID:jj};function uh(e,t,s){var o;if(dh.randomUUID&&!e)return dh.randomUUID();e=e||{};const n=e.random??((o=e.rng)==null?void 0:o.call(e))??kj();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=n[6]&15|64,n[8]=n[8]&63|128,_j(n)}const Cj=["text/","application/json","application/xml"],Mj=[".md",".markdown",".txt",".log",".json",".yaml",".yml",".toml",".ini",".csv",".ts",".tsx",".js",".jsx",".py",".java",".rs",".go",".rb",".php",".css",".scss",".less",".html",".sh",".bash",".zsh",".sql",".swift",".kt",".c",".cpp",".h",".hpp"],Pj=200*1024,By=e=>e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`,mh=e=>{const t=e.toLowerCase();return Mj.some(s=>t.endsWith(s))},Ej=e=>!e.type&&mh(e.name)?!0:Cj.some(t=>e.type.startsWith(t))||mh(e.name),Rj=e=>new Promise((t,s)=>{const n=new FileReader;n.onerror=()=>s(n.error),n.onload=()=>t(n.result),n.readAsText(e)}),hh=async(e,t)=>{const s=Pj,n=[],o=[];for(const a of e)try{if(Ej(a)&&a.size<=s){const i=await Rj(a);n.push({id:uh(),file:a,name:a.name,size:a.size,type:a.type||"text/plain",kind:"text",content:i,preview:i.length>400?`${i.slice(0,400)}…`:i,lastModified:a.lastModified})}else n.push({id:uh(),file:a,name:a.name,size:a.size,type:a.type||"application/octet-stream",kind:"binary",preview:`(${By(a.size)}) Preview unavailable for this file type.`,lastModified:a.lastModified})}catch(i){console.error("[fileUtils] Failed to process file",a.name,i),o.push(`Failed to process ${a.name}: ${i.message}`)}return{processed:n,errors:o}},Aj=e=>{const t=[],s=[];return e.forEach(n=>{n.type.startsWith("image/")?t.push(n):s.push(n)}),{images:t,others:s}},Ij=e=>e.length===0?"":e.map(t=>{const s=`### File: ${t.name}`,n=`(_${By(t.size)}_, ${t.type||"unknown"})`;return t.kind==="text"&&t.content?`${s}
|
|
155
155
|
${n}
|
|
@@ -171,7 +171,7 @@ ${n}
|
|
|
171
171
|
|
|
172
172
|
`)}}if(!_&&!b&&(!f||f.length===0))return;const k=[x,_,b].filter(Boolean).join(`
|
|
173
173
|
|
|
174
|
-
`);if(l(k),d(""),c(),o.size>0){const C=Array.from(k.matchAll(/@([^\\s]+)/g));if(C.length>0){const E=[];for(const j of C){const R=j[1],M=o.get(R);M&&E.push(M)}if(E.length>0){const j=JSON.stringify({type:"file_reference",paths:E.map(R=>R.path),display_text:k});await i(j,f,a,w)}else await i(k,f,a,w)}else await i(k,f,a,w)}else await i(k,f,a,w);u(null),h([]),p(new Map)},[e,c,o,n,l,a,s,i,h,d,p,u,t])}),Xj=({currentSessionId:e,currentChat:t,currentMessages:s,reasoningEffort:n,retryLastTurn:o,navigate:a})=>{const i=m.useCallback(async(c="regenerate")=>{if(!e||!t)return;const d=[...s];d.length===0||[...d].reverse().findIndex(h=>h.role==="user")===-1||await o(n,c)},[t,e,s,n,o]),l=m.useCallback((c,d)=>{const u=a(c,d);return u.applied?u.value:null},[a]);return{retryLastMessage:i,handleHistoryNavigate:l}},Vj=({referenceText:e,isToolSpecificMode:t,isRestrictConversation:s,allowedTools:n,autoToolPrefix:o,t:a})=>a(e?"chat.input.placeholderWithReference":"chat.input.placeholderWithWorkflows");function Kj({value:e,onChange:t,disabled:s}){const n=Ee(d=>d.catalog),o=Ee(d=>d.isCatalogFetching),a=m.useMemo(()=>{if(!(n!=null&&n.models))return[];const d={};for(const p of n.models){const g=p.reference.provider;d[g]||(d[g]={display:p.provider_display_name,models:[]}),d[g].models.push(p)}const u=[];return Object.keys(d).forEach((p,g)=>{const y=d[p];g>0&&u.push({type:"divider"}),u.push({type:"group",label:y.display,children:y.models.map(f=>({key:`${f.reference.provider}/${f.reference.model}`,label:r.jsxs(X,{size:4,children:[r.jsx("span",{children:f.display_name}),f.capabilities.supports_vision&&r.jsx(oe,{color:"blue",style:{fontSize:10,lineHeight:"16px",padding:"0 3px"},children:"Vision"})]})}))})}),u},[n]),i=e?`${e.provider}/${e.model}`:void 0,l=m.useCallback(d=>{const[u,...h]=d.key.split("/"),p=h.join("/");u&&p&&t({provider:u,model:p})},[t]),c=m.useCallback(async()=>{await Ee.getState().fetchCatalogModels()},[]);return r.jsxs(X,{size:4,"data-tour-id":"model-picker",children:[r.jsx(zn,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:i?[i]:[],items:a,style:{maxHeight:"50vh",overflowY:"auto"},onClick:l},disabled:s,children:r.jsx(Y,{type:"text",size:"small",disabled:s,style:{minWidth:146,padding:"0 12px",height:36,borderRadius:18},title:e?`${e.provider}/${e.model}`:"Select model",children:r.jsxs(X,{size:4,children:[r.jsx("span",{style:{maxWidth:150,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13},children:e?`${e.provider}/${e.model}`:"Select model"}),r.jsx(Wt,{style:{fontSize:10}})]})})}),r.jsx(Y,{type:"text",size:"small",icon:r.jsx(Ms,{spin:o}),onClick:c,disabled:o,style:{height:36,borderRadius:18},title:"Fetch all provider models"})]})}const Nc="chat-toggle-batch-export-selection",Bc="chat-focus-input",pr="chat-pending-question-resolved",Gj=m.lazy(()=>Dt(()=>import("./index-CYeT_vWc.js"),__vite__mapDeps([8,1,2,3]),import.meta.url)),Jj=m.lazy(()=>Dt(()=>import("./index-BIPq1exu.js"),__vite__mapDeps([9,1,2,3,4,5,6,7,10]),import.meta.url)),Qj=m.lazy(()=>Dt(()=>import("./index-aEud9Tjx.js"),__vite__mapDeps([11,1,2,3,4,5,6,7]),import.meta.url)),Zj=m.lazy(()=>Dt(()=>import("./index-B9rhKJTy.js"),__vite__mapDeps([12,1,2,3]),import.meta.url)),{useToken:eC}=he,fh="chat-send-message",gh="reference-text",tC="chat-model-options-cache-v1",sC=24*60*60*1e3,nC=["low","medium","high","xhigh","max"],rC=[],Wy=e=>`${tC}:${e}`,oC=e=>{if(typeof window>"u")return null;try{const t=localStorage.getItem(Wy(e));if(!t)return null;const s=JSON.parse(t);return!s||!Array.isArray(s.options)||Date.now()-s.timestamp>sC?null:s.options.filter(n=>n&&typeof n.value=="string"&&n.value.trim().length>0&&typeof n.label=="string").map(n=>({value:n.value,label:n.label}))}catch{return null}},aC=(e,t)=>{if(!(typeof window>"u"))try{const s={timestamp:Date.now(),options:t};localStorage.setItem(Wy(e),JSON.stringify(s))}catch{}},iC=({sessionId:e,onWorkflowDraftChange:t,statusIndicator:s})=>{var ru,ou;const{t:n}=ne(),o=m.useRef(null),{token:a}=eC(),i=md(),l=Bs(te=>te.open),c=N(te=>e??te.currentSessionId),d=N(te=>te.currentSessionId),u=N(Xn(c)),h=(u==null?void 0:u.messages)||[],p=N(te=>te.addMessage),g=N(te=>te.updateSession),y=N(te=>te.processingChats),f=N(te=>te.setSessionProcessing),v=N(te=>te.pendingQuestionRespond),b=N(te=>te.clearPendingQuestionRespondForSession),x=Hi(c),_=Bd((ru=u==null?void 0:u.config)==null?void 0:ru.model_ref),w=Ee(te=>te.isProviderModelRefEnabled),k=N(te=>c?te.inputStates[c]:void 0),C=N(te=>te.setInputContent),E=N(te=>te.setReferenceText),j=N(te=>te.setInputReasoningEffort),R=Ee(te=>te.currentProvider),M=Ee(te=>te.providerConfig),[T,P]=m.useState([]),[S,L]=m.useState(!1),[$,I]=m.useState(null),[W,A]=m.useState(!1),O=(k==null?void 0:k.content)||"",D=(k==null?void 0:k.referenceText)||null,H=m.useMemo(()=>{var te;return(te=M.providers[R])==null?void 0:te.reasoning_effort},[M,R]),B=m.useMemo(()=>c?bd(c):void 0,[c]),K=((ou=u==null?void 0:u.config)==null?void 0:ou.reasoningEffort)??(k==null?void 0:k.reasoningEffort)??B??H??"medium",F=m.useCallback(te=>{c&&C(c,te)},[c,C]),z=m.useCallback(te=>{c&&E(c,te)},[c,E]),de=m.useCallback(async te=>{if(c&&(j(c,te),!!u))try{await Wn.patchSession(c,{reasoning_effort:te}),g(c,{config:{...u.config,reasoningEffort:te}})}catch(Ne){console.warn("[InputContainer] Failed to persist reasoning effort:",Ne)}},[u,c,j,g]),Te=c?y.has(c):!1,{sendMessage:$e,retryLastTurn:De,cancel:be}=Cy({sessionId:c,addMessage:p,setSessionProcessing:f,updateSession:g});m.useEffect(()=>{if(typeof window>"u")return;const te=at=>at?c===at:c!==null&&c===d,Ne=at=>{const Be=at;if(!Be.detail||typeof Be.detail.text!="string")return;const is=typeof Be.detail.sessionId=="string"?Be.detail.sessionId:null;if(!te(is))return;const ls=Be.detail.text.trim();ls&&(Be.detail.handled=!0,z(ls),requestAnimationFrame(()=>{var bs;(bs=o.current)==null||bs.focus()}))},Ke=at=>{var ls;const Be=at,is=typeof((ls=Be.detail)==null?void 0:ls.sessionId)=="string"?Be.detail.sessionId:null;te(is)&&(Be.detail&&(Be.detail.handled=!0),requestAnimationFrame(()=>{var bs;(bs=o.current)==null||bs.focus()}))};return window.addEventListener(gh,Ne),window.addEventListener(Bc,Ke),()=>{window.removeEventListener(gh,Ne),window.removeEventListener(Bc,Ke)}},[d,c,z]);const ye=Te,{message:je}=Ot.useApp(),Ue=!1,ht=!1,Ge=rC,wt=void 0,{recordEntry:U,navigate:_e,acknowledgeManualInput:Ce}=Nj(c),{attachments:Ve,setAttachments:qe,handleAttachmentsAdded:J,handleAttachmentRemove:re,handleClearAttachments:V}=Hj(),Q=Bj({setContent:F,onWorkflowDraftChange:t,acknowledgeManualInput:Ce,currentSessionId:c,textAreaRef:o,content:O}),se=qj({content:O,setContent:F,currentSessionId:c,currentChat:u,updateSession:g,messageApi:je}),{setShowFileSelector:ce}=se;m.useEffect(()=>{Q.showCommandSelector&&ce(!1)},[Q.showCommandSelector,ce]);const{handleSubmit:Ie}=Yj({attachments:Ve,referenceText:D,selectedWorkflow:Q.selectedCommand,matchesWorkflowToken:Q.matchesCommandToken,fileReferences:se.fileReferences,reasoningEffort:K,sendMessage:$e,recordEntry:U,clearWorkflowDraft:Q.clearCommandDraft,setContent:F,setReferenceText:z,setAttachments:qe,setFileReferences:se.setFileReferences}),Je=v&&v.sessionId===c?v:null,_t=!!Je,jt=(Je==null?void 0:Je.options)||[],Ct=(Je==null?void 0:Je.allowCustom)??!0,Tt=m.useCallback(te=>{if(!te)return!1;const Ne=N.getState().pendingQuestionRespond;return(Ne==null?void 0:Ne.sessionId)===te},[]),hn=m.useCallback(async te=>{const Ne=te.trim();if(!Ne||!c)return;const Ke=N.getState().pendingQuestionRespond,at=(Ke==null?void 0:Ke.sessionId)===c?Ke:null;if(at&&!at.allowCustom&&at.options.length>0&&!at.options.includes(Ne)){je.warning(n("components.questionDialog.selectOptionWarning"));return}try{const Be={response:Ne,reasoning_effort:K};w()&&_&&(Be.model_ref=_,Be.provider=_.provider);const is=await pe.post(`respond/${c}`,Be);je.success(n("components.questionDialog.responseSubmittedContinue")),F(""),b(c),typeof window<"u"&&window.dispatchEvent(new CustomEvent(pr,{detail:{sessionId:c}}));const ls=is==null?void 0:is.auto_resume_status;ls&&["started","already_running"].includes(ls)&&f(c,!0)}catch(Be){console.error("[InputContainer] Failed to submit respond:",Be),je.error(Be instanceof Error?Be.message:n("components.questionDialog.submitFailed"))}},[c,K,_,w,je,F,b,f,n]),Vs=m.useCallback(async(te,Ne)=>{if(Tt(c)){await hn(te);return}await Ie(te,Ne)},[c,Tt,hn,Ie]),Pr=m.useCallback(async(te,Ne)=>{await Vs(te,Ne)},[Vs]);m.useEffect(()=>{if(typeof window>"u")return;const te=Ne=>{var ls,bs,au;const Ke=Ne;if(!Ke.detail)return;const at=typeof Ke.detail.sessionId=="string"?Ke.detail.sessionId:null;if(!(at?c===at:c!==null&&c===d))return;Ke.detail.handled=!0;const is=(ls=Ke.detail)==null?void 0:ls.content;if(typeof is!="string"||is.trim().length===0){(au=(bs=Ke.detail)==null?void 0:bs.reject)==null||au.call(bs,new Error("External send message content is empty"));return}Vs(is,void 0).then(()=>{var Gn,yn;(yn=(Gn=Ke.detail)==null?void 0:Gn.resolve)==null||yn.call(Gn)}).catch(Gn=>{var yn,iu;(iu=(yn=Ke.detail)==null?void 0:yn.reject)==null||iu.call(yn,Gn)})};return window.addEventListener(fh,te),()=>{window.removeEventListener(fh,te)}},[d,c,Vs]);const{retryLastMessage:Vn,handleHistoryNavigate:Ks}=Xj({currentSessionId:c,currentChat:u,currentMessages:h,reasoningEffort:K,retryLastTurn:De,navigate:_e}),Er=()=>z(null),Ps=m.useMemo(()=>M.providers[R],[M,R]),Ut=m.useMemo(()=>!Ps||typeof Ps!="object"?!1:R==="copilot"?Object.keys(Ps).length>0:"api_key"in Ps?typeof Ps.api_key=="string"&&Ps.api_key.trim().length>0:!1,[R,Ps]),pn=m.useCallback(()=>Ut?!1:(l("chat"),je.warning("Please configure provider first"),!0),[Ut,je,l]);m.useEffect(()=>{const te=oC(R);P(te??[]),I(null)},[R]);const fn=m.useCallback(te=>te instanceof Error&&te.message.trim()?te.message:"Unknown error",[]),gn=m.useMemo(()=>({openai:[...ek],anthropic:[...tk],gemini:[...sk],copilot:[...nk],bodhi:[]})[R]||[],[R]),Kn=m.useMemo(()=>{const Ne=[...T.length>0?T:gn];return x&&!Ne.some(Ke=>Ke.value===x)&&Ne.unshift({value:x,label:x}),Ne},[T,gn,x]),Rr=m.useCallback(async(te,Ne)=>{if(!(!(Ne!=null&&Ne.force)&&T.length>0))try{L(!0),I(null);const at=(te==="copilot"?await If.getModels():gn).map(Be=>({value:typeof Be=="string"?Be:Be.value,label:typeof Be=="string"?Be:Be.label}));P(at),aC(te,at)}catch(Ke){I(fn(Ke))}finally{L(!1)}},[gn,fn,T.length]),ka=m.useCallback(te=>{te&&(pn()||S||T.length>0||Rr(R))},[R,Rr,S,T.length,pn]),ae=m.useCallback(async te=>{var Ne,Ke,at;if(!(!te||te===x)&&!W)try{if(pn())return;if(A(!0),!c||!u){c&&g(c,{config:{systemPromptId:((Ne=u==null?void 0:u.config)==null?void 0:Ne.systemPromptId)||"default",baseSystemPrompt:((Ke=u==null?void 0:u.config)==null?void 0:Ke.baseSystemPrompt)||"",lastUsedEnhancedPrompt:((at=u==null?void 0:u.config)==null?void 0:at.lastUsedEnhancedPrompt)??null,...(u==null?void 0:u.config)||{},model:te}});return}await Wn.patchSession(c,{model:te}),g(c,{config:{...u.config,model:te}}),je.success(n("settings.providerTab.modelUpdated"))}catch(Be){je.error(`${n("settings.providerTab.updateModelErrorPrefix")}: ${fn(Be)}`)}finally{A(!1)}},[x,u,fn,W,je,pn,c,n,g]),Me=m.useCallback(te=>{Ee.getState().setSelectedModelRef(te),c&&(u!=null&&u.config)&&g(c,{config:{systemPromptId:u.config.systemPromptId,baseSystemPrompt:u.config.baseSystemPrompt,lastUsedEnhancedPrompt:u.config.lastUsedEnhancedPrompt,model_ref:te}})},[u==null?void 0:u.config,c,g]),Le=m.useMemo(()=>Vj({referenceText:D,isToolSpecificMode:Ue,isRestrictConversation:ht,allowedTools:Ge,autoToolPrefix:wt,t:n}),[D,Ue,ht,Ge,wt,n]),Qe=_t&&Ct?n("chat.respond.customAnswerPlaceholder"):_t?n("components.questionDialog.selectOptionWarning"):Le,Mt=_t?n("chat.respond.submitToolResult","Submit tool result"):void 0,Es=m.useMemo(()=>({low:n("chat.input.reasoning.low"),medium:n("chat.input.reasoning.medium"),high:n("chat.input.reasoning.high"),xhigh:n("chat.input.reasoning.xhigh"),max:n("chat.input.reasoning.max")}),[n]),Rs=m.useMemo(()=>Es[K]??K,[K,Es]),as=r.jsx(zn,{trigger:["click"],placement:"topLeft",disabled:!x||ye,menu:{selectable:!0,selectedKeys:[K],items:nC.map(te=>({key:te,label:Es[te]})),onClick:({key:te})=>{de(te)}},children:r.jsx(Y,{type:"text",size:"small",disabled:!x||ye,style:{minWidth:i?74:88,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:K==="medium"?a.colorTextSecondary:a.colorPrimary},title:n("chat.input.reasoningTitle",{label:Rs}),children:r.jsxs(X,{size:6,children:[r.jsx(xf,{}),r.jsx("span",{children:Rs}),r.jsx(Wt,{style:{fontSize:10}})]})})}),ys=x||n(Ut?"chat.model.selectModel":"chat.model.configureProvider"),As=m.useMemo(()=>Kn.length>0?Kn.map(te=>({key:te.value,label:te.label})):[{key:"__no_models__",label:$||n("chat.model.noModelsAvailable"),disabled:!0}],[Kn,$,n]),Is=r.jsx(Y,{type:"text",size:"small",disabled:ye||W,onClick:()=>{Ut||pn()},style:{minWidth:i?112:146,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:$?a.colorError:a.colorTextSecondary},title:ys,children:r.jsxs(X,{size:6,children:[S?r.jsx(gr,{}):r.jsx(ad,{}),r.jsx("span",{style:{maxWidth:i?84:128,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ys}),r.jsx(Wt,{style:{fontSize:10}})]})}),Kb=w()?r.jsx(Kj,{value:_,onChange:Me,disabled:ye||W}):Ut?r.jsx(zn,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:x?[x]:[],items:As,style:{maxHeight:"50vh",overflowY:"auto"},onClick:({key:te})=>{te!=="__no_models__"&&ae(String(te))}},onOpenChange:ka,disabled:ye||W,children:Is}):Is;return r.jsxs("div",{style:{padding:`${a.paddingXXS}px ${a.paddingXS}px`,background:"transparent",borderTop:"none",boxShadow:"none",width:"100%",position:"relative",overflow:"visible"},children:[!x&&r.jsx(Xe,{type:"warning",showIcon:!0,icon:r.jsx(da,{}),message:n(Ut?"chat.model.noModelSelected":"chat.model.providerNotConfigured"),description:n(Ut?"chat.model.selectModelHint":"chat.model.configureProviderHint"),action:Ut?void 0:r.jsx(X,{children:r.jsx("a",{onClick:()=>l("chat"),children:n("chat.model.openSettings")})}),style:{marginBottom:a.marginSM}}),Ue,D&&r.jsx(zj,{text:D,onClose:Er}),Ve.length>0&&r.jsx(m.Suspense,{fallback:r.jsx(ps,{size:"small"}),children:r.jsx(Gj,{files:Ve,onRemove:re,onClear:V})}),_t&&jt.length>0&&r.jsx("div",{style:{marginBottom:a.marginSM},children:r.jsx(X,{wrap:!0,size:[8,8],children:jt.map(te=>r.jsx(Y,{size:"small",onClick:()=>{hn(te)},disabled:ye,children:te},te))})}),r.jsx(Oj,{value:O,onChange:Q.handleInputChange,onSubmit:Pr,placeholder:Qe,allowImages:!0,disabled:!x||_t&&!Ct&&jt.length>0,statusIndicator:s,submitButtonLabel:Mt,isWorkflowSelectorVisible:Q.showCommandSelector,textAreaRef:o,validateMessage:te=>({isValid:!0}),onAttachmentsAdded:J,onWorkflowCommandChange:Q.handleCommandChange,onFileReferenceChange:se.handleFileReferenceChange,onFileReferenceButtonClick:se.handleFileReferenceButtonClick,leftControlsExtra:r.jsxs(X,{size:0,wrap:!0,children:[Kb,as]}),interaction:{isStreaming:ye,hasMessages:h.some(te=>te.role==="user"),allowRetry:!0,onRetry:Vn,onCancel:be,onHistoryNavigate:Ks}}),r.jsx(m.Suspense,{fallback:null,children:r.jsx(Jj,{visible:Q.showCommandSelector,onSelect:Q.handleCommandSelect,onCancel:Q.handleCommandSelectorCancel,onAutoComplete:Q.handleAutoComplete,searchText:Q.commandSearchText})}),se.showFileSelector&&r.jsx(m.Suspense,{fallback:r.jsx(ps,{size:"small"}),children:r.jsx(Zj,{visible:se.showFileSelector,files:se.workspaceFiles,searchText:se.fileSearchText,loading:se.isWorkspaceLoading,error:se.workspaceError,onSelect:se.handleFileReferenceSelect,onCancel:se.handleFileSelectorCancel,onChangeWorkspace:()=>{se.setWorkspacePathInput((u==null?void 0:u.config.workspacePath)??""),se.setIsWorkspaceModalVisible(!0)}})}),r.jsx(m.Suspense,{fallback:null,children:r.jsx(Qj,{open:se.isWorkspaceModalVisible,initialPath:se.workspacePathInput,loading:se.isSavingWorkspace,onSubmit:se.handleWorkspaceModalSubmit,onCancel:se.handleWorkspaceModalCancel})})]})},{Text:Fs}=le,lC=220,cC="chat-session-diff-collapse:",dC=e=>e.split(/[\\/]/).pop()||e,Uy=e=>`${cC}${e??"default"}`,Al=e=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(Uy(e));if(!t)return null;const s=JSON.parse(t);if(!s||typeof s!="object")return null;const n="isExpanded"in s&&typeof s.isExpanded=="boolean"?s.isExpanded:!0,o="expandedFiles"in s&&Array.isArray(s.expandedFiles)?s.expandedFiles.filter(a=>typeof a=="string"):[];return{isExpanded:n,expandedFiles:o}}catch{return null}},uC=(e,t)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Uy(e),JSON.stringify(t))}catch{}},mC=({sessionDiffSummary:e,sessionId:t})=>{const{token:s}=he.useToken(),n=!!(e&&e.files.length>0),[o,a]=m.useState(n),[i,l]=m.useState(n),[c,d]=m.useState(()=>{var y;return((y=Al(t))==null?void 0:y.isExpanded)??!0}),[u,h]=m.useState(()=>{var y;return new Set(((y=Al(t))==null?void 0:y.expandedFiles)??[])});m.useEffect(()=>{if(n){a(!0);const f=window.setTimeout(()=>l(!0),0);return()=>window.clearTimeout(f)}l(!1);const y=window.setTimeout(()=>a(!1),lC);return()=>window.clearTimeout(y)},[n]);const p=m.useMemo(()=>e?e.files:[],[e]),g=m.useMemo(()=>{const y=new Map;return e&&e.files.forEach(f=>{y.set(f.filePath,Iy(f.unifiedDiff))}),y},[e]);return m.useEffect(()=>{const y=Al(t);d((y==null?void 0:y.isExpanded)??!0),h(new Set((y==null?void 0:y.expandedFiles)??[]))},[t]),m.useEffect(()=>{uC(t,{isExpanded:c,expandedFiles:Array.from(u)})},[t,c,u]),m.useEffect(()=>{if(!e||e.files.length===0)return;const y=new Set(e.files.map(f=>f.filePath));h(f=>{const v=new Set;let b=!1;return f.forEach(x=>{y.has(x)?v.add(x):b=!0}),!b&&v.size===f.size?f:v})},[e]),!o||!e?null:r.jsx("div",{className:`active-tool-card-wrapper ${i?"visible":""}`,"aria-hidden":!i,"data-testid":"session-diff-card",children:r.jsx(ee,{size:"small",style:{width:"100%",borderRadius:s.borderRadiusLG,border:`1px solid ${s.colorBorderSecondary}`,background:s.colorBgContainer,boxShadow:s.boxShadowSecondary},bodyStyle:{padding:`${s.paddingXS}px ${s.paddingSM}px`},children:r.jsxs(X,{direction:"vertical",style:{width:"100%"},size:6,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:s.marginSM,cursor:"pointer"},onClick:()=>d(y=>!y),"data-testid":"session-diff-toggle",children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:s.marginSM,minWidth:0},children:[r.jsx(vf,{style:{color:s.colorPrimary}}),r.jsx(Fs,{strong:!0,style:{whiteSpace:"nowrap"},children:"Session diffs"}),r.jsxs(Fs,{type:"secondary",style:{fontSize:s.fontSizeSM,whiteSpace:"nowrap"},children:["(",e.files.length," files / ",e.changedTools," tools)"]}),r.jsxs(X,{size:4,style:{marginInlineStart:s.marginXS},children:[r.jsxs(Fs,{style:{color:s.colorSuccess,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",e.totalAdded]}),r.jsxs(Fs,{style:{color:s.colorError,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",e.totalRemoved]})]})]}),r.jsx("div",{style:{color:s.colorTextSecondary},children:c?r.jsx(Wt,{}):r.jsx(Ws,{})})]}),c&&r.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr",gap:6,maxHeight:280,overflowY:"auto"},"data-testid":"session-diff-file-list",children:p.map(y=>{const f=u.has(y.filePath),v=g.get(y.filePath)??[];return r.jsxs("div",{style:{border:`1px solid ${s.colorBorderSecondary}`,borderRadius:s.borderRadiusSM,overflow:"hidden",background:s.colorBgContainer},"data-testid":"session-diff-file-item","data-file-path":y.filePath,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:s.marginSM,padding:"4px 8px",borderRadius:s.borderRadiusSM,background:s.colorFillTertiary,cursor:"pointer"},onClick:()=>{h(b=>{const x=new Set(b);return x.has(y.filePath)?x.delete(y.filePath):x.add(y.filePath),x})},"data-testid":"session-diff-file-header","data-file-path":y.filePath,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:s.marginXS,minWidth:0,flex:1},children:[r.jsx("span",{style:{color:s.colorTextSecondary},children:f?r.jsx(Wt,{}):r.jsx(Ws,{})}),r.jsx(Fs,{ellipsis:{tooltip:y.filePath},style:{flex:1,minWidth:0,fontSize:s.fontSizeSM},children:dC(y.filePath)})]}),r.jsxs(X,{size:4,children:[r.jsxs(Fs,{style:{color:s.colorSuccess,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",y.added]}),r.jsxs(Fs,{style:{color:s.colorError,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",y.removed]})]})]}),f&&r.jsxs("div",{style:{borderTop:`1px solid ${s.colorBorderSecondary}`,maxHeight:220,overflow:"auto",background:s.colorBgContainer},"data-testid":"session-diff-file-panel","data-file-path":y.filePath,children:[v.length>0?v.map((b,x)=>{const _={margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:s.fontSizeSM,lineHeight:1.5,padding:"0 8px",fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace"};return b.kind==="add"?_.background=s.colorSuccessBg:b.kind==="remove"?_.background=s.colorErrorBg:b.kind==="modified_add"?(_.background=s.colorWarningBg,_.borderLeft=`3px solid ${s.colorSuccess}`):b.kind==="modified_remove"?(_.background=s.colorWarningBg,_.borderLeft=`3px solid ${s.colorError}`):b.kind==="hunk"?(_.background=s.colorFillSecondary,_.color=s.colorTextSecondary):b.kind==="meta"&&(_.background=s.colorFillTertiary,_.color=s.colorTextSecondary),r.jsx("pre",{style:_,"data-testid":"session-diff-line","data-kind":b.kind,children:b.text||" "},`${y.filePath}-${x}`)}):r.jsx(Fs,{type:"secondary",style:{display:"block",padding:"8px",fontSize:s.fontSizeSM},children:"No diff preview available."}),y.truncated&&r.jsx(Fs,{type:"secondary",style:{display:"block",padding:"6px 8px 8px",fontSize:s.fontSizeSM},children:"Diff truncated for display."})]})]},y.filePath)})})]})})})},hC=e=>{if(!e)return;const{activeLeafId:t,setLeafSessionId:s,setActiveLeafId:n}=Ae.getState();s(t,e),n(t),N.getState().selectSession(e)},pC=["You are Bodhi operating in code review mode.","Review code changes with emphasis on correctness, regressions, security, maintainability, tests, and rollout risk.","Prefer concise findings with severity, rationale, and actionable fixes.","Ask for missing scope or repository context before making strong assumptions."].join(" "),fC=["You are Bodhi operating in bug investigation mode.","Help diagnose issues by analyzing code, logs, stack traces, and runtime behavior.","Trace root causes methodically, suggest targeted fixes, and flag related risks.","Ask for reproduction steps or error messages if not provided."].join(" "),gC=["You are Bodhi operating in feature implementation mode.","Help plan and implement new features step by step, following existing code conventions.","Consider edge cases, testing strategies, and backward compatibility.","Propose an implementation plan before writing code when scope is large."].join(" "),yC=["You are Bodhi operating in architecture analysis mode.","Analyze the repository structure, key abstractions, data flow, and module boundaries.","Identify architectural patterns, coupling hotspots, and potential improvements.","Use diagrams to illustrate relationships when helpful."].join(" "),bC=["You are Bodhi operating in error explanation mode.","Help users understand error messages, stack traces, and unexpected behavior.","Explain the root cause clearly, suggest fixes, and provide prevention tips.","Keep explanations accessible even for less experienced developers."].join(" "),xC=["You are Bodhi operating in file comparison mode.","Compare the given files or code sections, highlighting key differences and their implications.","Focus on functional changes, potential regressions, and design trade-offs."].join(" "),vC=["You are Bodhi operating in refactoring advisor mode.","Suggest targeted refactoring improvements for readability, maintainability, and performance.","Respect existing code style, propose incremental changes, and explain the rationale.","Flag any risks introduced by the refactoring."].join(" "),SC=["You are Bodhi operating in release notes generation mode.","Generate clear, well-structured release notes from git history and code changes.","Categorize changes (features, fixes, improvements, breaking changes).","Write for both technical and non-technical readers."].join(" "),wC=["You are Bodhi operating in work summary mode.","Help summarize recent work activity for standups, weeklies, or status reports.","Pull key accomplishments, blockers, and next steps from session history or code changes.","Keep output concise and actionable."].join(" "),_C=["You are Bodhi operating in documentation writer mode.","Help create or improve technical documentation from code and project context.","Follow good documentation practices: clear structure, examples, and consistent terminology.","Produce Markdown-formatted output by default."].join(" "),TC=["You are Bodhi operating in scheduled task setup mode.","Help the user create a recurring scheduled task in Bamboo.","Clarify the task goal, frequency, workspace, and expected output before proceeding.","Guide the user through configuration and confirm before saving."].join(" "),kC=["You are Bodhi operating in session review mode.","Help inspect and analyze past session history for patterns, insights, or issues.","Summarize key decisions, outcomes, and areas that may need follow-up."].join(" "),jC=["You are Bodhi operating in context diagnostics mode.","Help analyze token usage, prompt bloat, context growth, truncation, and compression behavior.","Quantify likely causes when possible and recommend concrete, prioritized fixes.","Keep the output practical for engineers improving prompt and session efficiency."].join(" "),CC=["development","debugging","analysis","documentation","operations"],MC={development:{titleKey:"chat.emptyLauncher.categories.development",fallback:"Development"},debugging:{titleKey:"chat.emptyLauncher.categories.debugging",fallback:"Debugging"},analysis:{titleKey:"chat.emptyLauncher.categories.analysis",fallback:"Analysis"},documentation:{titleKey:"chat.emptyLauncher.categories.documentation",fallback:"Documentation"},operations:{titleKey:"chat.emptyLauncher.categories.operations",fallback:"Operations"}},PC=(e,t)=>{const s=e.find(o=>o.id===t),n=e.find(o=>o.id==="general_assistant")||e[0];return{systemPromptId:(s==null?void 0:s.id)||(n==null?void 0:n.id)||"",baseSystemPrompt:(s==null?void 0:s.content)||(n==null?void 0:n.content)||""}},qy=({sessionId:e=null,embedded:t=!1,hideHeader:s=!1,layoutMode:n="default"})=>{var T;const{t:o}=ne(),{token:a}=he.useToken(),{message:i}=Ot.useApp(),l=N(P=>e??P.currentSessionId),c=N(Xn(l)),d=N(P=>P.addChat),u=N(P=>P.lastSelectedPromptId),h=N(P=>P.setInputContent),p=N(P=>P.systemPrompts),g=N(P=>P.chats),[y,f]=m.useState(null),[v,b]=m.useState(""),x=(c==null?void 0:c.config.workspacePath)??((T=g.find(P=>P.config.workspacePath))==null?void 0:T.config.workspacePath),_=m.useMemo(()=>[{id:"blank",icon:r.jsx(Us,{}),title:o("chat.emptyLauncher.actions.blank.title","Blank session"),description:o("chat.emptyLauncher.actions.blank.description","Start from scratch with the default assistant and an empty composer."),sessionTitle:o("chat.emptyLauncher.actions.blank.sessionTitle","New Session"),prefill:o("chat.emptyLauncher.actions.blank.prefill",""),category:"development"},{id:"codeReview",icon:r.jsx(Li,{}),title:o("chat.emptyLauncher.actions.codeReview.title","Code review"),description:o("chat.emptyLauncher.actions.codeReview.description","Open a review-focused session with an editable review brief."),sessionTitle:o("chat.emptyLauncher.actions.codeReview.sessionTitle","Code Review"),prefill:o("chat.emptyLauncher.actions.codeReview.prefill","Review the relevant code changes in this workspace or repository. Start with the overall scope, then list risks, notable diffs, and the most important fixes."),baseSystemPrompt:pC,category:"development",recommendWorkspace:!0},{id:"implementFeature",icon:r.jsx(Sr,{}),title:o("chat.emptyLauncher.actions.implementFeature.title","Implement feature"),description:o("chat.emptyLauncher.actions.implementFeature.description","Plan and build a feature step by step following existing code conventions."),sessionTitle:o("chat.emptyLauncher.actions.implementFeature.sessionTitle","Implement Feature"),prefill:o("chat.emptyLauncher.actions.implementFeature.prefill","Help me implement a new feature in this workspace. Start by understanding the codebase structure, then propose an implementation plan before writing code."),baseSystemPrompt:gC,category:"development",recommendWorkspace:!0},{id:"refactor",icon:r.jsx(vf,{}),title:o("chat.emptyLauncher.actions.refactor.title","Refactor code"),description:o("chat.emptyLauncher.actions.refactor.description","Get targeted suggestions for improving code quality and maintainability."),sessionTitle:o("chat.emptyLauncher.actions.refactor.sessionTitle","Refactor Suggestion"),prefill:o("chat.emptyLauncher.actions.refactor.prefill","Suggest refactoring improvements for the code in this workspace. Focus on readability, maintainability, and performance. Propose incremental changes with clear rationale."),baseSystemPrompt:vC,category:"development",recommendWorkspace:!0},{id:"bugInvestigation",icon:r.jsx(bf,{}),title:o("chat.emptyLauncher.actions.bugInvestigation.title","Bug investigation"),description:o("chat.emptyLauncher.actions.bugInvestigation.description","Diagnose issues by analyzing code, logs, and runtime behavior."),sessionTitle:o("chat.emptyLauncher.actions.bugInvestigation.sessionTitle","Bug Investigation"),prefill:o("chat.emptyLauncher.actions.bugInvestigation.prefill","Help me investigate a bug. I'll describe the symptoms and share relevant code or logs. Trace the root cause and suggest targeted fixes."),baseSystemPrompt:fC,category:"debugging",recommendWorkspace:!0},{id:"explainError",icon:r.jsx(nd,{}),title:o("chat.emptyLauncher.actions.explainError.title","Explain error"),description:o("chat.emptyLauncher.actions.explainError.description","Understand what went wrong from an error message or stack trace."),sessionTitle:o("chat.emptyLauncher.actions.explainError.sessionTitle","Explain Error"),prefill:o("chat.emptyLauncher.actions.explainError.prefill","Help me understand the following error. Explain the root cause, suggest fixes, and share prevention tips."),baseSystemPrompt:bC,category:"debugging"},{id:"tokenUsage",icon:r.jsx(Sx,{}),title:o("chat.emptyLauncher.actions.tokenUsage.title","Token usage investigation"),description:o("chat.emptyLauncher.actions.tokenUsage.description","Diagnose context growth, truncation risk, and token budget pressure."),sessionTitle:o("chat.emptyLauncher.actions.tokenUsage.sessionTitle","Token Usage Investigation"),prefill:o("chat.emptyLauncher.actions.tokenUsage.prefill","Help me investigate token usage, context growth, and truncation risk for this session or workflow. Summarize the likely drivers and recommend concrete next fixes."),baseSystemPrompt:jC,category:"debugging"},{id:"architectureReview",icon:r.jsx(wx,{}),title:o("chat.emptyLauncher.actions.architectureReview.title","Read repo architecture"),description:o("chat.emptyLauncher.actions.architectureReview.description","Analyze repository structure, modules, and architectural patterns."),sessionTitle:o("chat.emptyLauncher.actions.architectureReview.sessionTitle","Architecture Review"),prefill:o("chat.emptyLauncher.actions.architectureReview.prefill","Analyze the architecture of this repository. Map the key modules, data flow, abstractions, and dependency patterns. Identify strengths and potential improvements."),baseSystemPrompt:yC,category:"analysis",recommendWorkspace:!0},{id:"compareFiles",icon:r.jsx(_x,{}),title:o("chat.emptyLauncher.actions.compareFiles.title","Compare files"),description:o("chat.emptyLauncher.actions.compareFiles.description","Diff and understand differences between files or code sections."),sessionTitle:o("chat.emptyLauncher.actions.compareFiles.sessionTitle","Compare Files"),prefill:o("chat.emptyLauncher.actions.compareFiles.prefill","Compare the following files or code sections. Highlight key differences, their implications, and any potential risks."),baseSystemPrompt:xC,category:"analysis",recommendWorkspace:!0},{id:"releaseNotes",icon:r.jsx(br,{}),title:o("chat.emptyLauncher.actions.releaseNotes.title","Generate release notes"),description:o("chat.emptyLauncher.actions.releaseNotes.description","Create structured release notes from git history and code changes."),sessionTitle:o("chat.emptyLauncher.actions.releaseNotes.sessionTitle","Release Notes"),prefill:o("chat.emptyLauncher.actions.releaseNotes.prefill","Generate release notes for the latest changes in this workspace. Categorize into features, fixes, improvements, and breaking changes."),baseSystemPrompt:SC,category:"documentation",recommendWorkspace:!0},{id:"summarizeWork",icon:r.jsx(Tx,{}),title:o("chat.emptyLauncher.actions.summarizeWork.title","Summarize work"),description:o("chat.emptyLauncher.actions.summarizeWork.description","Create a work summary for standups or weekly status reports."),sessionTitle:o("chat.emptyLauncher.actions.summarizeWork.sessionTitle","Work Summary"),prefill:o("chat.emptyLauncher.actions.summarizeWork.prefill","Help me summarize my recent work for a status update. Pull key accomplishments, blockers, and next steps."),baseSystemPrompt:wC,category:"documentation"},{id:"writeDocs",icon:r.jsx(br,{}),title:o("chat.emptyLauncher.actions.writeDocs.title","Write documentation"),description:o("chat.emptyLauncher.actions.writeDocs.description","Create or improve technical documentation from code and context."),sessionTitle:o("chat.emptyLauncher.actions.writeDocs.sessionTitle","Write Documentation"),prefill:o("chat.emptyLauncher.actions.writeDocs.prefill","Help me write technical documentation for this project. Analyze the code and produce clear, well-structured Markdown documentation."),baseSystemPrompt:_C,category:"documentation",recommendWorkspace:!0},{id:"createSchedule",icon:r.jsx(Ys,{}),title:o("chat.emptyLauncher.actions.createSchedule.title","Create scheduled task"),description:o("chat.emptyLauncher.actions.createSchedule.description","Set up a recurring task that runs automatically on a schedule."),sessionTitle:o("chat.emptyLauncher.actions.createSchedule.sessionTitle","Create Schedule"),prefill:o("chat.emptyLauncher.actions.createSchedule.prefill","Help me set up a recurring scheduled task. I'll describe what I want it to do, and you guide me through the configuration."),baseSystemPrompt:TC,category:"operations"},{id:"sessionReview",icon:r.jsx(sa,{}),title:o("chat.emptyLauncher.actions.sessionReview.title","Review session history"),description:o("chat.emptyLauncher.actions.sessionReview.description","Inspect and analyze past sessions for patterns and insights."),sessionTitle:o("chat.emptyLauncher.actions.sessionReview.sessionTitle","Session Review"),prefill:o("chat.emptyLauncher.actions.sessionReview.prefill","Help me review my recent session history. Summarize key decisions, outcomes, and areas that need follow-up."),baseSystemPrompt:kC,category:"operations"}],[o]),w=v.trim().toLowerCase(),k=m.useMemo(()=>w?_.filter(P=>P.title.toLowerCase().includes(w)||P.description.toLowerCase().includes(w)):_,[w,_]),C=m.useMemo(()=>{const P={};for(const S of k)P[S.category]||(P[S.category]=[]),P[S.category].push(S);return P},[k]),E=m.useCallback(P=>{typeof window>"u"||window.setTimeout(()=>{window.dispatchEvent(new CustomEvent(Bc,{detail:{sessionId:P}}))},0)},[]),j=m.useCallback(async P=>{if(!y){f(P.id);try{const S=PC(p,u),L=await d({title:P.sessionTitle,createdAt:Date.now(),messages:[],config:{systemPromptId:S.systemPromptId,baseSystemPrompt:P.baseSystemPrompt??S.baseSystemPrompt,lastUsedEnhancedPrompt:null,...x?{workspacePath:x}:{}},currentInteraction:null});hC(L),P.prefill.trim().length>0&&h(L,P.prefill),E(L)}catch(S){console.error("[EmptyTaskLauncher] Failed to create session",S),i.error(S instanceof Error?S.message:o("chat.emptyLauncher.errors.createFailed","Failed to create session"))}finally{f(null)}}},[d,u,i,y,E,h,p,o,x]),R=m.useMemo(()=>({"--lotus-empty-launcher-border":a.colorBorderSecondary,"--lotus-empty-launcher-border-hover":a.colorPrimaryBorder,"--lotus-empty-launcher-bg":a.colorBgElevated,"--lotus-empty-launcher-icon-bg":a.colorPrimaryBg,"--lotus-empty-launcher-icon-color":a.colorPrimary,"--lotus-empty-launcher-text":a.colorText,"--lotus-empty-launcher-text-secondary":a.colorTextSecondary,"--lotus-empty-launcher-shadow":a.boxShadowSecondary,"--lotus-empty-launcher-shadow-hover":a.boxShadow,"--lotus-empty-launcher-category-border":a.colorBorderSecondary,"--lotus-empty-launcher-search-bg":a.colorBgContainer,"--lotus-empty-launcher-badge-bg":a.colorPrimaryBg,"--lotus-empty-launcher-badge-text":a.colorPrimary}),[a]),M=!!x;return r.jsxs("div",{className:`lotus-empty-task-launcher ${t?"is-embedded":""} ${s?"is-headerless":""} ${n==="staggered"?"is-staggered":""}`,style:R,children:[!s&&r.jsxs("div",{className:"lotus-empty-task-launcher__header",children:[r.jsx(le.Title,{level:t?4:3,style:{margin:0},children:o("chat.emptyLauncher.title","Start with a task")}),r.jsx(le.Paragraph,{type:"secondary",className:"lotus-empty-task-launcher__subtitle",children:o("chat.emptyLauncher.subtitle","Create a focused session in this pane and prefill the first message before you send it.")}),r.jsx(le.Text,{type:"secondary",className:"lotus-empty-task-launcher__hint",children:o("chat.emptyLauncher.hint","Nothing is sent automatically — you can edit the prompt first.")})]}),r.jsx("div",{className:"lotus-empty-task-launcher__search",children:r.jsx(me,{placeholder:o("chat.emptyLauncher.searchPlaceholder","Search templates..."),prefix:r.jsx(sa,{style:{color:a.colorTextQuaternary}}),value:v,onChange:P=>b(P.target.value),allowClear:!0,size:"middle",variant:"filled"})}),r.jsxs("div",{className:"lotus-empty-task-launcher__categories",children:[CC.map(P=>{const S=C[P];if(!S||S.length===0)return null;const L=MC[P];return r.jsxs("div",{className:"lotus-empty-task-launcher__category",children:[r.jsx(le.Text,{type:"secondary",className:"lotus-empty-task-launcher__category-label",children:o(L.titleKey,L.fallback)}),r.jsx("div",{className:"lotus-empty-task-launcher__grid",children:S.map($=>{const I=y===$.id,W=$.recommendWorkspace&&M;return r.jsxs("button",{type:"button",className:"lotus-empty-task-card",onClick:()=>{j($)},disabled:y!==null,"aria-busy":I,"aria-label":$.title,children:[r.jsx("div",{className:"lotus-empty-task-card__icon","aria-hidden":!0,children:I?r.jsx(gr,{}):$.icon}),r.jsxs("div",{className:"lotus-empty-task-card__body",children:[r.jsxs("div",{className:"lotus-empty-task-card__titleRow",children:[r.jsx("span",{className:"lotus-empty-task-card__title",children:$.title}),r.jsx(kx,{className:"lotus-empty-task-card__arrow","aria-hidden":!0})]}),r.jsx("p",{className:"lotus-empty-task-card__description",children:$.description}),W&&r.jsx("div",{className:"lotus-empty-task-card__badges",children:r.jsxs("span",{className:"lotus-empty-task-card__badge",title:x,children:["📂 ",o("chat.emptyLauncher.badges.workspace","workspace")]})})]})]},$.id)})})]},P)}),k.length===0&&r.jsx("div",{className:"lotus-empty-task-launcher__no-results",children:r.jsx(le.Text,{type:"secondary",children:o("chat.emptyLauncher.noResults","No templates match your search. Try a different keyword or start a blank session.")})})]})]})},EC=({sessionId:e,isCenteredLayout:t,maxWidth:s,onWorkflowDraftChange:n,showMessagesView:o,sessionDiffSummary:a,contextUsageIndicator:i})=>r.jsx(G,{justify:"center",className:`chat-view-input-container-wrapper ${o?"messages-view":"centered-view"}`,children:r.jsxs("div",{style:{width:"100%",maxWidth:o?s:"min(100%, 920px)",margin:o?"0 auto":void 0,position:"relative",paddingBottom:o?12:0,display:"flex",flexDirection:"column",gap:o?0:24},children:[o&&r.jsx(mC,{sessionDiffSummary:a,sessionId:e}),!o&&e&&r.jsx(qy,{sessionId:e}),r.jsx(iC,{sessionId:e,isCenteredLayout:t,onWorkflowDraftChange:n,statusIndicator:i})]})});function rr(e,t,s){let n=s.initialDeps??[],o;function a(){var i,l,c,d;let u;s.key&&((i=s.debug)!=null&&i.call(s))&&(u=Date.now());const h=e();if(!(h.length!==n.length||h.some((y,f)=>n[f]!==y)))return o;n=h;let g;if(s.key&&((l=s.debug)!=null&&l.call(s))&&(g=Date.now()),o=t(...h),s.key&&((c=s.debug)!=null&&c.call(s))){const y=Math.round((Date.now()-u)*100)/100,f=Math.round((Date.now()-g)*100)/100,v=f/16,b=(x,_)=>{for(x=String(x);x.length<_;)x=" "+x;return x};console.info(`%c⏱ ${b(f,5)} /${b(y,5)} ms`,`
|
|
174
|
+
`);if(l(k),d(""),c(),o.size>0){const C=Array.from(k.matchAll(/@([^\\s]+)/g));if(C.length>0){const E=[];for(const j of C){const R=j[1],M=o.get(R);M&&E.push(M)}if(E.length>0){const j=JSON.stringify({type:"file_reference",paths:E.map(R=>R.path),display_text:k});await i(j,f,a,w)}else await i(k,f,a,w)}else await i(k,f,a,w)}else await i(k,f,a,w);u(null),h([]),p(new Map)},[e,c,o,n,l,a,s,i,h,d,p,u,t])}),Xj=({currentSessionId:e,currentChat:t,currentMessages:s,reasoningEffort:n,retryLastTurn:o,navigate:a})=>{const i=m.useCallback(async(c="regenerate")=>{if(!e||!t)return;const d=[...s];d.length===0||[...d].reverse().findIndex(h=>h.role==="user")===-1||await o(n,c)},[t,e,s,n,o]),l=m.useCallback((c,d)=>{const u=a(c,d);return u.applied?u.value:null},[a]);return{retryLastMessage:i,handleHistoryNavigate:l}},Vj=({referenceText:e,isToolSpecificMode:t,isRestrictConversation:s,allowedTools:n,autoToolPrefix:o,t:a})=>a(e?"chat.input.placeholderWithReference":"chat.input.placeholderWithWorkflows");function Kj({value:e,onChange:t,disabled:s}){const n=Ee(d=>d.catalog),o=Ee(d=>d.isCatalogFetching),a=m.useMemo(()=>{if(!(n!=null&&n.models))return[];const d={};for(const p of n.models){const g=p.reference.provider;d[g]||(d[g]={display:p.provider_display_name,models:[]}),d[g].models.push(p)}const u=[];return Object.keys(d).forEach((p,g)=>{const y=d[p];g>0&&u.push({type:"divider"}),u.push({type:"group",label:y.display,children:y.models.map(f=>({key:`${f.reference.provider}/${f.reference.model}`,label:r.jsxs(X,{size:4,children:[r.jsx("span",{children:f.display_name}),f.capabilities.supports_vision&&r.jsx(oe,{color:"blue",style:{fontSize:10,lineHeight:"16px",padding:"0 3px"},children:"Vision"})]})}))})}),u},[n]),i=e?`${e.provider}/${e.model}`:void 0,l=m.useCallback(d=>{const[u,...h]=d.key.split("/"),p=h.join("/");u&&p&&t({provider:u,model:p})},[t]),c=m.useCallback(async()=>{await Ee.getState().fetchCatalogModels()},[]);return r.jsxs(X,{size:4,"data-tour-id":"model-picker",children:[r.jsx(zn,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:i?[i]:[],items:a,style:{maxHeight:"50vh",overflowY:"auto"},onClick:l},disabled:s,children:r.jsx(Y,{type:"text",size:"small",disabled:s,style:{minWidth:146,padding:"0 12px",height:36,borderRadius:18},title:e?`${e.provider}/${e.model}`:"Select model",children:r.jsxs(X,{size:4,children:[r.jsx("span",{style:{maxWidth:150,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13},children:e?`${e.provider}/${e.model}`:"Select model"}),r.jsx(Wt,{style:{fontSize:10}})]})})}),r.jsx(Y,{type:"text",size:"small",icon:r.jsx(Ms,{spin:o}),onClick:c,disabled:o,style:{height:36,borderRadius:18},title:"Fetch all provider models"})]})}const Nc="chat-toggle-batch-export-selection",Bc="chat-focus-input",pr="chat-pending-question-resolved",Gj=m.lazy(()=>Dt(()=>import("./index-CYeT_vWc.js"),__vite__mapDeps([8,1,2,3]),import.meta.url)),Jj=m.lazy(()=>Dt(()=>import("./index-33TAS5RK.js"),__vite__mapDeps([9,1,2,3,4,5,6,7,10]),import.meta.url)),Qj=m.lazy(()=>Dt(()=>import("./index-eh17wnlp.js"),__vite__mapDeps([11,1,2,3,4,5,6,7]),import.meta.url)),Zj=m.lazy(()=>Dt(()=>import("./index-B9rhKJTy.js"),__vite__mapDeps([12,1,2,3]),import.meta.url)),{useToken:eC}=he,fh="chat-send-message",gh="reference-text",tC="chat-model-options-cache-v1",sC=24*60*60*1e3,nC=["low","medium","high","xhigh","max"],rC=[],Wy=e=>`${tC}:${e}`,oC=e=>{if(typeof window>"u")return null;try{const t=localStorage.getItem(Wy(e));if(!t)return null;const s=JSON.parse(t);return!s||!Array.isArray(s.options)||Date.now()-s.timestamp>sC?null:s.options.filter(n=>n&&typeof n.value=="string"&&n.value.trim().length>0&&typeof n.label=="string").map(n=>({value:n.value,label:n.label}))}catch{return null}},aC=(e,t)=>{if(!(typeof window>"u"))try{const s={timestamp:Date.now(),options:t};localStorage.setItem(Wy(e),JSON.stringify(s))}catch{}},iC=({sessionId:e,onWorkflowDraftChange:t,statusIndicator:s})=>{var ru,ou;const{t:n}=ne(),o=m.useRef(null),{token:a}=eC(),i=md(),l=Bs(te=>te.open),c=N(te=>e??te.currentSessionId),d=N(te=>te.currentSessionId),u=N(Xn(c)),h=(u==null?void 0:u.messages)||[],p=N(te=>te.addMessage),g=N(te=>te.updateSession),y=N(te=>te.processingChats),f=N(te=>te.setSessionProcessing),v=N(te=>te.pendingQuestionRespond),b=N(te=>te.clearPendingQuestionRespondForSession),x=Hi(c),_=Bd((ru=u==null?void 0:u.config)==null?void 0:ru.model_ref),w=Ee(te=>te.isProviderModelRefEnabled),k=N(te=>c?te.inputStates[c]:void 0),C=N(te=>te.setInputContent),E=N(te=>te.setReferenceText),j=N(te=>te.setInputReasoningEffort),R=Ee(te=>te.currentProvider),M=Ee(te=>te.providerConfig),[T,P]=m.useState([]),[S,L]=m.useState(!1),[$,I]=m.useState(null),[W,A]=m.useState(!1),O=(k==null?void 0:k.content)||"",D=(k==null?void 0:k.referenceText)||null,H=m.useMemo(()=>{var te;return(te=M.providers[R])==null?void 0:te.reasoning_effort},[M,R]),B=m.useMemo(()=>c?bd(c):void 0,[c]),K=((ou=u==null?void 0:u.config)==null?void 0:ou.reasoningEffort)??(k==null?void 0:k.reasoningEffort)??B??H??"medium",F=m.useCallback(te=>{c&&C(c,te)},[c,C]),z=m.useCallback(te=>{c&&E(c,te)},[c,E]),de=m.useCallback(async te=>{if(c&&(j(c,te),!!u))try{await Wn.patchSession(c,{reasoning_effort:te}),g(c,{config:{...u.config,reasoningEffort:te}})}catch(Ne){console.warn("[InputContainer] Failed to persist reasoning effort:",Ne)}},[u,c,j,g]),Te=c?y.has(c):!1,{sendMessage:$e,retryLastTurn:De,cancel:be}=Cy({sessionId:c,addMessage:p,setSessionProcessing:f,updateSession:g});m.useEffect(()=>{if(typeof window>"u")return;const te=at=>at?c===at:c!==null&&c===d,Ne=at=>{const Be=at;if(!Be.detail||typeof Be.detail.text!="string")return;const is=typeof Be.detail.sessionId=="string"?Be.detail.sessionId:null;if(!te(is))return;const ls=Be.detail.text.trim();ls&&(Be.detail.handled=!0,z(ls),requestAnimationFrame(()=>{var bs;(bs=o.current)==null||bs.focus()}))},Ke=at=>{var ls;const Be=at,is=typeof((ls=Be.detail)==null?void 0:ls.sessionId)=="string"?Be.detail.sessionId:null;te(is)&&(Be.detail&&(Be.detail.handled=!0),requestAnimationFrame(()=>{var bs;(bs=o.current)==null||bs.focus()}))};return window.addEventListener(gh,Ne),window.addEventListener(Bc,Ke),()=>{window.removeEventListener(gh,Ne),window.removeEventListener(Bc,Ke)}},[d,c,z]);const ye=Te,{message:je}=Ot.useApp(),Ue=!1,ht=!1,Ge=rC,wt=void 0,{recordEntry:U,navigate:_e,acknowledgeManualInput:Ce}=Nj(c),{attachments:Ve,setAttachments:qe,handleAttachmentsAdded:J,handleAttachmentRemove:re,handleClearAttachments:V}=Hj(),Q=Bj({setContent:F,onWorkflowDraftChange:t,acknowledgeManualInput:Ce,currentSessionId:c,textAreaRef:o,content:O}),se=qj({content:O,setContent:F,currentSessionId:c,currentChat:u,updateSession:g,messageApi:je}),{setShowFileSelector:ce}=se;m.useEffect(()=>{Q.showCommandSelector&&ce(!1)},[Q.showCommandSelector,ce]);const{handleSubmit:Ie}=Yj({attachments:Ve,referenceText:D,selectedWorkflow:Q.selectedCommand,matchesWorkflowToken:Q.matchesCommandToken,fileReferences:se.fileReferences,reasoningEffort:K,sendMessage:$e,recordEntry:U,clearWorkflowDraft:Q.clearCommandDraft,setContent:F,setReferenceText:z,setAttachments:qe,setFileReferences:se.setFileReferences}),Je=v&&v.sessionId===c?v:null,_t=!!Je,jt=(Je==null?void 0:Je.options)||[],Ct=(Je==null?void 0:Je.allowCustom)??!0,Tt=m.useCallback(te=>{if(!te)return!1;const Ne=N.getState().pendingQuestionRespond;return(Ne==null?void 0:Ne.sessionId)===te},[]),hn=m.useCallback(async te=>{const Ne=te.trim();if(!Ne||!c)return;const Ke=N.getState().pendingQuestionRespond,at=(Ke==null?void 0:Ke.sessionId)===c?Ke:null;if(at&&!at.allowCustom&&at.options.length>0&&!at.options.includes(Ne)){je.warning(n("components.questionDialog.selectOptionWarning"));return}try{const Be={response:Ne,reasoning_effort:K};w()&&_&&(Be.model_ref=_,Be.provider=_.provider);const is=await pe.post(`respond/${c}`,Be);je.success(n("components.questionDialog.responseSubmittedContinue")),F(""),b(c),typeof window<"u"&&window.dispatchEvent(new CustomEvent(pr,{detail:{sessionId:c}}));const ls=is==null?void 0:is.auto_resume_status;ls&&["started","already_running"].includes(ls)&&f(c,!0)}catch(Be){console.error("[InputContainer] Failed to submit respond:",Be),je.error(Be instanceof Error?Be.message:n("components.questionDialog.submitFailed"))}},[c,K,_,w,je,F,b,f,n]),Vs=m.useCallback(async(te,Ne)=>{if(Tt(c)){await hn(te);return}await Ie(te,Ne)},[c,Tt,hn,Ie]),Pr=m.useCallback(async(te,Ne)=>{await Vs(te,Ne)},[Vs]);m.useEffect(()=>{if(typeof window>"u")return;const te=Ne=>{var ls,bs,au;const Ke=Ne;if(!Ke.detail)return;const at=typeof Ke.detail.sessionId=="string"?Ke.detail.sessionId:null;if(!(at?c===at:c!==null&&c===d))return;Ke.detail.handled=!0;const is=(ls=Ke.detail)==null?void 0:ls.content;if(typeof is!="string"||is.trim().length===0){(au=(bs=Ke.detail)==null?void 0:bs.reject)==null||au.call(bs,new Error("External send message content is empty"));return}Vs(is,void 0).then(()=>{var Gn,yn;(yn=(Gn=Ke.detail)==null?void 0:Gn.resolve)==null||yn.call(Gn)}).catch(Gn=>{var yn,iu;(iu=(yn=Ke.detail)==null?void 0:yn.reject)==null||iu.call(yn,Gn)})};return window.addEventListener(fh,te),()=>{window.removeEventListener(fh,te)}},[d,c,Vs]);const{retryLastMessage:Vn,handleHistoryNavigate:Ks}=Xj({currentSessionId:c,currentChat:u,currentMessages:h,reasoningEffort:K,retryLastTurn:De,navigate:_e}),Er=()=>z(null),Ps=m.useMemo(()=>M.providers[R],[M,R]),Ut=m.useMemo(()=>!Ps||typeof Ps!="object"?!1:R==="copilot"?Object.keys(Ps).length>0:"api_key"in Ps?typeof Ps.api_key=="string"&&Ps.api_key.trim().length>0:!1,[R,Ps]),pn=m.useCallback(()=>Ut?!1:(l("chat"),je.warning("Please configure provider first"),!0),[Ut,je,l]);m.useEffect(()=>{const te=oC(R);P(te??[]),I(null)},[R]);const fn=m.useCallback(te=>te instanceof Error&&te.message.trim()?te.message:"Unknown error",[]),gn=m.useMemo(()=>({openai:[...ek],anthropic:[...tk],gemini:[...sk],copilot:[...nk],bodhi:[]})[R]||[],[R]),Kn=m.useMemo(()=>{const Ne=[...T.length>0?T:gn];return x&&!Ne.some(Ke=>Ke.value===x)&&Ne.unshift({value:x,label:x}),Ne},[T,gn,x]),Rr=m.useCallback(async(te,Ne)=>{if(!(!(Ne!=null&&Ne.force)&&T.length>0))try{L(!0),I(null);const at=(te==="copilot"?await If.getModels():gn).map(Be=>({value:typeof Be=="string"?Be:Be.value,label:typeof Be=="string"?Be:Be.label}));P(at),aC(te,at)}catch(Ke){I(fn(Ke))}finally{L(!1)}},[gn,fn,T.length]),ka=m.useCallback(te=>{te&&(pn()||S||T.length>0||Rr(R))},[R,Rr,S,T.length,pn]),ae=m.useCallback(async te=>{var Ne,Ke,at;if(!(!te||te===x)&&!W)try{if(pn())return;if(A(!0),!c||!u){c&&g(c,{config:{systemPromptId:((Ne=u==null?void 0:u.config)==null?void 0:Ne.systemPromptId)||"default",baseSystemPrompt:((Ke=u==null?void 0:u.config)==null?void 0:Ke.baseSystemPrompt)||"",lastUsedEnhancedPrompt:((at=u==null?void 0:u.config)==null?void 0:at.lastUsedEnhancedPrompt)??null,...(u==null?void 0:u.config)||{},model:te}});return}await Wn.patchSession(c,{model:te}),g(c,{config:{...u.config,model:te}}),je.success(n("settings.providerTab.modelUpdated"))}catch(Be){je.error(`${n("settings.providerTab.updateModelErrorPrefix")}: ${fn(Be)}`)}finally{A(!1)}},[x,u,fn,W,je,pn,c,n,g]),Me=m.useCallback(te=>{Ee.getState().setSelectedModelRef(te),c&&(u!=null&&u.config)&&g(c,{config:{systemPromptId:u.config.systemPromptId,baseSystemPrompt:u.config.baseSystemPrompt,lastUsedEnhancedPrompt:u.config.lastUsedEnhancedPrompt,model_ref:te}})},[u==null?void 0:u.config,c,g]),Le=m.useMemo(()=>Vj({referenceText:D,isToolSpecificMode:Ue,isRestrictConversation:ht,allowedTools:Ge,autoToolPrefix:wt,t:n}),[D,Ue,ht,Ge,wt,n]),Qe=_t&&Ct?n("chat.respond.customAnswerPlaceholder"):_t?n("components.questionDialog.selectOptionWarning"):Le,Mt=_t?n("chat.respond.submitToolResult","Submit tool result"):void 0,Es=m.useMemo(()=>({low:n("chat.input.reasoning.low"),medium:n("chat.input.reasoning.medium"),high:n("chat.input.reasoning.high"),xhigh:n("chat.input.reasoning.xhigh"),max:n("chat.input.reasoning.max")}),[n]),Rs=m.useMemo(()=>Es[K]??K,[K,Es]),as=r.jsx(zn,{trigger:["click"],placement:"topLeft",disabled:!x||ye,menu:{selectable:!0,selectedKeys:[K],items:nC.map(te=>({key:te,label:Es[te]})),onClick:({key:te})=>{de(te)}},children:r.jsx(Y,{type:"text",size:"small",disabled:!x||ye,style:{minWidth:i?74:88,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:K==="medium"?a.colorTextSecondary:a.colorPrimary},title:n("chat.input.reasoningTitle",{label:Rs}),children:r.jsxs(X,{size:6,children:[r.jsx(xf,{}),r.jsx("span",{children:Rs}),r.jsx(Wt,{style:{fontSize:10}})]})})}),ys=x||n(Ut?"chat.model.selectModel":"chat.model.configureProvider"),As=m.useMemo(()=>Kn.length>0?Kn.map(te=>({key:te.value,label:te.label})):[{key:"__no_models__",label:$||n("chat.model.noModelsAvailable"),disabled:!0}],[Kn,$,n]),Is=r.jsx(Y,{type:"text",size:"small",disabled:ye||W,onClick:()=>{Ut||pn()},style:{minWidth:i?112:146,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:$?a.colorError:a.colorTextSecondary},title:ys,children:r.jsxs(X,{size:6,children:[S?r.jsx(gr,{}):r.jsx(ad,{}),r.jsx("span",{style:{maxWidth:i?84:128,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ys}),r.jsx(Wt,{style:{fontSize:10}})]})}),Kb=w()?r.jsx(Kj,{value:_,onChange:Me,disabled:ye||W}):Ut?r.jsx(zn,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:x?[x]:[],items:As,style:{maxHeight:"50vh",overflowY:"auto"},onClick:({key:te})=>{te!=="__no_models__"&&ae(String(te))}},onOpenChange:ka,disabled:ye||W,children:Is}):Is;return r.jsxs("div",{style:{padding:`${a.paddingXXS}px ${a.paddingXS}px`,background:"transparent",borderTop:"none",boxShadow:"none",width:"100%",position:"relative",overflow:"visible"},children:[!x&&r.jsx(Xe,{type:"warning",showIcon:!0,icon:r.jsx(da,{}),message:n(Ut?"chat.model.noModelSelected":"chat.model.providerNotConfigured"),description:n(Ut?"chat.model.selectModelHint":"chat.model.configureProviderHint"),action:Ut?void 0:r.jsx(X,{children:r.jsx("a",{onClick:()=>l("chat"),children:n("chat.model.openSettings")})}),style:{marginBottom:a.marginSM}}),Ue,D&&r.jsx(zj,{text:D,onClose:Er}),Ve.length>0&&r.jsx(m.Suspense,{fallback:r.jsx(ps,{size:"small"}),children:r.jsx(Gj,{files:Ve,onRemove:re,onClear:V})}),_t&&jt.length>0&&r.jsx("div",{style:{marginBottom:a.marginSM},children:r.jsx(X,{wrap:!0,size:[8,8],children:jt.map(te=>r.jsx(Y,{size:"small",onClick:()=>{hn(te)},disabled:ye,children:te},te))})}),r.jsx(Oj,{value:O,onChange:Q.handleInputChange,onSubmit:Pr,placeholder:Qe,allowImages:!0,disabled:!x||_t&&!Ct&&jt.length>0,statusIndicator:s,submitButtonLabel:Mt,isWorkflowSelectorVisible:Q.showCommandSelector,textAreaRef:o,validateMessage:te=>({isValid:!0}),onAttachmentsAdded:J,onWorkflowCommandChange:Q.handleCommandChange,onFileReferenceChange:se.handleFileReferenceChange,onFileReferenceButtonClick:se.handleFileReferenceButtonClick,leftControlsExtra:r.jsxs(X,{size:0,wrap:!0,children:[Kb,as]}),interaction:{isStreaming:ye,hasMessages:h.some(te=>te.role==="user"),allowRetry:!0,onRetry:Vn,onCancel:be,onHistoryNavigate:Ks}}),r.jsx(m.Suspense,{fallback:null,children:r.jsx(Jj,{visible:Q.showCommandSelector,onSelect:Q.handleCommandSelect,onCancel:Q.handleCommandSelectorCancel,onAutoComplete:Q.handleAutoComplete,searchText:Q.commandSearchText})}),se.showFileSelector&&r.jsx(m.Suspense,{fallback:r.jsx(ps,{size:"small"}),children:r.jsx(Zj,{visible:se.showFileSelector,files:se.workspaceFiles,searchText:se.fileSearchText,loading:se.isWorkspaceLoading,error:se.workspaceError,onSelect:se.handleFileReferenceSelect,onCancel:se.handleFileSelectorCancel,onChangeWorkspace:()=>{se.setWorkspacePathInput((u==null?void 0:u.config.workspacePath)??""),se.setIsWorkspaceModalVisible(!0)}})}),r.jsx(m.Suspense,{fallback:null,children:r.jsx(Qj,{open:se.isWorkspaceModalVisible,initialPath:se.workspacePathInput,loading:se.isSavingWorkspace,onSubmit:se.handleWorkspaceModalSubmit,onCancel:se.handleWorkspaceModalCancel})})]})},{Text:Fs}=le,lC=220,cC="chat-session-diff-collapse:",dC=e=>e.split(/[\\/]/).pop()||e,Uy=e=>`${cC}${e??"default"}`,Al=e=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(Uy(e));if(!t)return null;const s=JSON.parse(t);if(!s||typeof s!="object")return null;const n="isExpanded"in s&&typeof s.isExpanded=="boolean"?s.isExpanded:!0,o="expandedFiles"in s&&Array.isArray(s.expandedFiles)?s.expandedFiles.filter(a=>typeof a=="string"):[];return{isExpanded:n,expandedFiles:o}}catch{return null}},uC=(e,t)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Uy(e),JSON.stringify(t))}catch{}},mC=({sessionDiffSummary:e,sessionId:t})=>{const{token:s}=he.useToken(),n=!!(e&&e.files.length>0),[o,a]=m.useState(n),[i,l]=m.useState(n),[c,d]=m.useState(()=>{var y;return((y=Al(t))==null?void 0:y.isExpanded)??!0}),[u,h]=m.useState(()=>{var y;return new Set(((y=Al(t))==null?void 0:y.expandedFiles)??[])});m.useEffect(()=>{if(n){a(!0);const f=window.setTimeout(()=>l(!0),0);return()=>window.clearTimeout(f)}l(!1);const y=window.setTimeout(()=>a(!1),lC);return()=>window.clearTimeout(y)},[n]);const p=m.useMemo(()=>e?e.files:[],[e]),g=m.useMemo(()=>{const y=new Map;return e&&e.files.forEach(f=>{y.set(f.filePath,Iy(f.unifiedDiff))}),y},[e]);return m.useEffect(()=>{const y=Al(t);d((y==null?void 0:y.isExpanded)??!0),h(new Set((y==null?void 0:y.expandedFiles)??[]))},[t]),m.useEffect(()=>{uC(t,{isExpanded:c,expandedFiles:Array.from(u)})},[t,c,u]),m.useEffect(()=>{if(!e||e.files.length===0)return;const y=new Set(e.files.map(f=>f.filePath));h(f=>{const v=new Set;let b=!1;return f.forEach(x=>{y.has(x)?v.add(x):b=!0}),!b&&v.size===f.size?f:v})},[e]),!o||!e?null:r.jsx("div",{className:`active-tool-card-wrapper ${i?"visible":""}`,"aria-hidden":!i,"data-testid":"session-diff-card",children:r.jsx(ee,{size:"small",style:{width:"100%",borderRadius:s.borderRadiusLG,border:`1px solid ${s.colorBorderSecondary}`,background:s.colorBgContainer,boxShadow:s.boxShadowSecondary},bodyStyle:{padding:`${s.paddingXS}px ${s.paddingSM}px`},children:r.jsxs(X,{direction:"vertical",style:{width:"100%"},size:6,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:s.marginSM,cursor:"pointer"},onClick:()=>d(y=>!y),"data-testid":"session-diff-toggle",children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:s.marginSM,minWidth:0},children:[r.jsx(vf,{style:{color:s.colorPrimary}}),r.jsx(Fs,{strong:!0,style:{whiteSpace:"nowrap"},children:"Session diffs"}),r.jsxs(Fs,{type:"secondary",style:{fontSize:s.fontSizeSM,whiteSpace:"nowrap"},children:["(",e.files.length," files / ",e.changedTools," tools)"]}),r.jsxs(X,{size:4,style:{marginInlineStart:s.marginXS},children:[r.jsxs(Fs,{style:{color:s.colorSuccess,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",e.totalAdded]}),r.jsxs(Fs,{style:{color:s.colorError,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",e.totalRemoved]})]})]}),r.jsx("div",{style:{color:s.colorTextSecondary},children:c?r.jsx(Wt,{}):r.jsx(Ws,{})})]}),c&&r.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr",gap:6,maxHeight:280,overflowY:"auto"},"data-testid":"session-diff-file-list",children:p.map(y=>{const f=u.has(y.filePath),v=g.get(y.filePath)??[];return r.jsxs("div",{style:{border:`1px solid ${s.colorBorderSecondary}`,borderRadius:s.borderRadiusSM,overflow:"hidden",background:s.colorBgContainer},"data-testid":"session-diff-file-item","data-file-path":y.filePath,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:s.marginSM,padding:"4px 8px",borderRadius:s.borderRadiusSM,background:s.colorFillTertiary,cursor:"pointer"},onClick:()=>{h(b=>{const x=new Set(b);return x.has(y.filePath)?x.delete(y.filePath):x.add(y.filePath),x})},"data-testid":"session-diff-file-header","data-file-path":y.filePath,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:s.marginXS,minWidth:0,flex:1},children:[r.jsx("span",{style:{color:s.colorTextSecondary},children:f?r.jsx(Wt,{}):r.jsx(Ws,{})}),r.jsx(Fs,{ellipsis:{tooltip:y.filePath},style:{flex:1,minWidth:0,fontSize:s.fontSizeSM},children:dC(y.filePath)})]}),r.jsxs(X,{size:4,children:[r.jsxs(Fs,{style:{color:s.colorSuccess,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",y.added]}),r.jsxs(Fs,{style:{color:s.colorError,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",y.removed]})]})]}),f&&r.jsxs("div",{style:{borderTop:`1px solid ${s.colorBorderSecondary}`,maxHeight:220,overflow:"auto",background:s.colorBgContainer},"data-testid":"session-diff-file-panel","data-file-path":y.filePath,children:[v.length>0?v.map((b,x)=>{const _={margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:s.fontSizeSM,lineHeight:1.5,padding:"0 8px",fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace"};return b.kind==="add"?_.background=s.colorSuccessBg:b.kind==="remove"?_.background=s.colorErrorBg:b.kind==="modified_add"?(_.background=s.colorWarningBg,_.borderLeft=`3px solid ${s.colorSuccess}`):b.kind==="modified_remove"?(_.background=s.colorWarningBg,_.borderLeft=`3px solid ${s.colorError}`):b.kind==="hunk"?(_.background=s.colorFillSecondary,_.color=s.colorTextSecondary):b.kind==="meta"&&(_.background=s.colorFillTertiary,_.color=s.colorTextSecondary),r.jsx("pre",{style:_,"data-testid":"session-diff-line","data-kind":b.kind,children:b.text||" "},`${y.filePath}-${x}`)}):r.jsx(Fs,{type:"secondary",style:{display:"block",padding:"8px",fontSize:s.fontSizeSM},children:"No diff preview available."}),y.truncated&&r.jsx(Fs,{type:"secondary",style:{display:"block",padding:"6px 8px 8px",fontSize:s.fontSizeSM},children:"Diff truncated for display."})]})]},y.filePath)})})]})})})},hC=e=>{if(!e)return;const{activeLeafId:t,setLeafSessionId:s,setActiveLeafId:n}=Ae.getState();s(t,e),n(t),N.getState().selectSession(e)},pC=["You are Bodhi operating in code review mode.","Review code changes with emphasis on correctness, regressions, security, maintainability, tests, and rollout risk.","Prefer concise findings with severity, rationale, and actionable fixes.","Ask for missing scope or repository context before making strong assumptions."].join(" "),fC=["You are Bodhi operating in bug investigation mode.","Help diagnose issues by analyzing code, logs, stack traces, and runtime behavior.","Trace root causes methodically, suggest targeted fixes, and flag related risks.","Ask for reproduction steps or error messages if not provided."].join(" "),gC=["You are Bodhi operating in feature implementation mode.","Help plan and implement new features step by step, following existing code conventions.","Consider edge cases, testing strategies, and backward compatibility.","Propose an implementation plan before writing code when scope is large."].join(" "),yC=["You are Bodhi operating in architecture analysis mode.","Analyze the repository structure, key abstractions, data flow, and module boundaries.","Identify architectural patterns, coupling hotspots, and potential improvements.","Use diagrams to illustrate relationships when helpful."].join(" "),bC=["You are Bodhi operating in error explanation mode.","Help users understand error messages, stack traces, and unexpected behavior.","Explain the root cause clearly, suggest fixes, and provide prevention tips.","Keep explanations accessible even for less experienced developers."].join(" "),xC=["You are Bodhi operating in file comparison mode.","Compare the given files or code sections, highlighting key differences and their implications.","Focus on functional changes, potential regressions, and design trade-offs."].join(" "),vC=["You are Bodhi operating in refactoring advisor mode.","Suggest targeted refactoring improvements for readability, maintainability, and performance.","Respect existing code style, propose incremental changes, and explain the rationale.","Flag any risks introduced by the refactoring."].join(" "),SC=["You are Bodhi operating in release notes generation mode.","Generate clear, well-structured release notes from git history and code changes.","Categorize changes (features, fixes, improvements, breaking changes).","Write for both technical and non-technical readers."].join(" "),wC=["You are Bodhi operating in work summary mode.","Help summarize recent work activity for standups, weeklies, or status reports.","Pull key accomplishments, blockers, and next steps from session history or code changes.","Keep output concise and actionable."].join(" "),_C=["You are Bodhi operating in documentation writer mode.","Help create or improve technical documentation from code and project context.","Follow good documentation practices: clear structure, examples, and consistent terminology.","Produce Markdown-formatted output by default."].join(" "),TC=["You are Bodhi operating in scheduled task setup mode.","Help the user create a recurring scheduled task in Bamboo.","Clarify the task goal, frequency, workspace, and expected output before proceeding.","Guide the user through configuration and confirm before saving."].join(" "),kC=["You are Bodhi operating in session review mode.","Help inspect and analyze past session history for patterns, insights, or issues.","Summarize key decisions, outcomes, and areas that may need follow-up."].join(" "),jC=["You are Bodhi operating in context diagnostics mode.","Help analyze token usage, prompt bloat, context growth, truncation, and compression behavior.","Quantify likely causes when possible and recommend concrete, prioritized fixes.","Keep the output practical for engineers improving prompt and session efficiency."].join(" "),CC=["development","debugging","analysis","documentation","operations"],MC={development:{titleKey:"chat.emptyLauncher.categories.development",fallback:"Development"},debugging:{titleKey:"chat.emptyLauncher.categories.debugging",fallback:"Debugging"},analysis:{titleKey:"chat.emptyLauncher.categories.analysis",fallback:"Analysis"},documentation:{titleKey:"chat.emptyLauncher.categories.documentation",fallback:"Documentation"},operations:{titleKey:"chat.emptyLauncher.categories.operations",fallback:"Operations"}},PC=(e,t)=>{const s=e.find(o=>o.id===t),n=e.find(o=>o.id==="general_assistant")||e[0];return{systemPromptId:(s==null?void 0:s.id)||(n==null?void 0:n.id)||"",baseSystemPrompt:(s==null?void 0:s.content)||(n==null?void 0:n.content)||""}},qy=({sessionId:e=null,embedded:t=!1,hideHeader:s=!1,layoutMode:n="default"})=>{var T;const{t:o}=ne(),{token:a}=he.useToken(),{message:i}=Ot.useApp(),l=N(P=>e??P.currentSessionId),c=N(Xn(l)),d=N(P=>P.addChat),u=N(P=>P.lastSelectedPromptId),h=N(P=>P.setInputContent),p=N(P=>P.systemPrompts),g=N(P=>P.chats),[y,f]=m.useState(null),[v,b]=m.useState(""),x=(c==null?void 0:c.config.workspacePath)??((T=g.find(P=>P.config.workspacePath))==null?void 0:T.config.workspacePath),_=m.useMemo(()=>[{id:"blank",icon:r.jsx(Us,{}),title:o("chat.emptyLauncher.actions.blank.title","Blank session"),description:o("chat.emptyLauncher.actions.blank.description","Start from scratch with the default assistant and an empty composer."),sessionTitle:o("chat.emptyLauncher.actions.blank.sessionTitle","New Session"),prefill:o("chat.emptyLauncher.actions.blank.prefill",""),category:"development"},{id:"codeReview",icon:r.jsx(Li,{}),title:o("chat.emptyLauncher.actions.codeReview.title","Code review"),description:o("chat.emptyLauncher.actions.codeReview.description","Open a review-focused session with an editable review brief."),sessionTitle:o("chat.emptyLauncher.actions.codeReview.sessionTitle","Code Review"),prefill:o("chat.emptyLauncher.actions.codeReview.prefill","Review the relevant code changes in this workspace or repository. Start with the overall scope, then list risks, notable diffs, and the most important fixes."),baseSystemPrompt:pC,category:"development",recommendWorkspace:!0},{id:"implementFeature",icon:r.jsx(Sr,{}),title:o("chat.emptyLauncher.actions.implementFeature.title","Implement feature"),description:o("chat.emptyLauncher.actions.implementFeature.description","Plan and build a feature step by step following existing code conventions."),sessionTitle:o("chat.emptyLauncher.actions.implementFeature.sessionTitle","Implement Feature"),prefill:o("chat.emptyLauncher.actions.implementFeature.prefill","Help me implement a new feature in this workspace. Start by understanding the codebase structure, then propose an implementation plan before writing code."),baseSystemPrompt:gC,category:"development",recommendWorkspace:!0},{id:"refactor",icon:r.jsx(vf,{}),title:o("chat.emptyLauncher.actions.refactor.title","Refactor code"),description:o("chat.emptyLauncher.actions.refactor.description","Get targeted suggestions for improving code quality and maintainability."),sessionTitle:o("chat.emptyLauncher.actions.refactor.sessionTitle","Refactor Suggestion"),prefill:o("chat.emptyLauncher.actions.refactor.prefill","Suggest refactoring improvements for the code in this workspace. Focus on readability, maintainability, and performance. Propose incremental changes with clear rationale."),baseSystemPrompt:vC,category:"development",recommendWorkspace:!0},{id:"bugInvestigation",icon:r.jsx(bf,{}),title:o("chat.emptyLauncher.actions.bugInvestigation.title","Bug investigation"),description:o("chat.emptyLauncher.actions.bugInvestigation.description","Diagnose issues by analyzing code, logs, and runtime behavior."),sessionTitle:o("chat.emptyLauncher.actions.bugInvestigation.sessionTitle","Bug Investigation"),prefill:o("chat.emptyLauncher.actions.bugInvestigation.prefill","Help me investigate a bug. I'll describe the symptoms and share relevant code or logs. Trace the root cause and suggest targeted fixes."),baseSystemPrompt:fC,category:"debugging",recommendWorkspace:!0},{id:"explainError",icon:r.jsx(nd,{}),title:o("chat.emptyLauncher.actions.explainError.title","Explain error"),description:o("chat.emptyLauncher.actions.explainError.description","Understand what went wrong from an error message or stack trace."),sessionTitle:o("chat.emptyLauncher.actions.explainError.sessionTitle","Explain Error"),prefill:o("chat.emptyLauncher.actions.explainError.prefill","Help me understand the following error. Explain the root cause, suggest fixes, and share prevention tips."),baseSystemPrompt:bC,category:"debugging"},{id:"tokenUsage",icon:r.jsx(Sx,{}),title:o("chat.emptyLauncher.actions.tokenUsage.title","Token usage investigation"),description:o("chat.emptyLauncher.actions.tokenUsage.description","Diagnose context growth, truncation risk, and token budget pressure."),sessionTitle:o("chat.emptyLauncher.actions.tokenUsage.sessionTitle","Token Usage Investigation"),prefill:o("chat.emptyLauncher.actions.tokenUsage.prefill","Help me investigate token usage, context growth, and truncation risk for this session or workflow. Summarize the likely drivers and recommend concrete next fixes."),baseSystemPrompt:jC,category:"debugging"},{id:"architectureReview",icon:r.jsx(wx,{}),title:o("chat.emptyLauncher.actions.architectureReview.title","Read repo architecture"),description:o("chat.emptyLauncher.actions.architectureReview.description","Analyze repository structure, modules, and architectural patterns."),sessionTitle:o("chat.emptyLauncher.actions.architectureReview.sessionTitle","Architecture Review"),prefill:o("chat.emptyLauncher.actions.architectureReview.prefill","Analyze the architecture of this repository. Map the key modules, data flow, abstractions, and dependency patterns. Identify strengths and potential improvements."),baseSystemPrompt:yC,category:"analysis",recommendWorkspace:!0},{id:"compareFiles",icon:r.jsx(_x,{}),title:o("chat.emptyLauncher.actions.compareFiles.title","Compare files"),description:o("chat.emptyLauncher.actions.compareFiles.description","Diff and understand differences between files or code sections."),sessionTitle:o("chat.emptyLauncher.actions.compareFiles.sessionTitle","Compare Files"),prefill:o("chat.emptyLauncher.actions.compareFiles.prefill","Compare the following files or code sections. Highlight key differences, their implications, and any potential risks."),baseSystemPrompt:xC,category:"analysis",recommendWorkspace:!0},{id:"releaseNotes",icon:r.jsx(br,{}),title:o("chat.emptyLauncher.actions.releaseNotes.title","Generate release notes"),description:o("chat.emptyLauncher.actions.releaseNotes.description","Create structured release notes from git history and code changes."),sessionTitle:o("chat.emptyLauncher.actions.releaseNotes.sessionTitle","Release Notes"),prefill:o("chat.emptyLauncher.actions.releaseNotes.prefill","Generate release notes for the latest changes in this workspace. Categorize into features, fixes, improvements, and breaking changes."),baseSystemPrompt:SC,category:"documentation",recommendWorkspace:!0},{id:"summarizeWork",icon:r.jsx(Tx,{}),title:o("chat.emptyLauncher.actions.summarizeWork.title","Summarize work"),description:o("chat.emptyLauncher.actions.summarizeWork.description","Create a work summary for standups or weekly status reports."),sessionTitle:o("chat.emptyLauncher.actions.summarizeWork.sessionTitle","Work Summary"),prefill:o("chat.emptyLauncher.actions.summarizeWork.prefill","Help me summarize my recent work for a status update. Pull key accomplishments, blockers, and next steps."),baseSystemPrompt:wC,category:"documentation"},{id:"writeDocs",icon:r.jsx(br,{}),title:o("chat.emptyLauncher.actions.writeDocs.title","Write documentation"),description:o("chat.emptyLauncher.actions.writeDocs.description","Create or improve technical documentation from code and context."),sessionTitle:o("chat.emptyLauncher.actions.writeDocs.sessionTitle","Write Documentation"),prefill:o("chat.emptyLauncher.actions.writeDocs.prefill","Help me write technical documentation for this project. Analyze the code and produce clear, well-structured Markdown documentation."),baseSystemPrompt:_C,category:"documentation",recommendWorkspace:!0},{id:"createSchedule",icon:r.jsx(Ys,{}),title:o("chat.emptyLauncher.actions.createSchedule.title","Create scheduled task"),description:o("chat.emptyLauncher.actions.createSchedule.description","Set up a recurring task that runs automatically on a schedule."),sessionTitle:o("chat.emptyLauncher.actions.createSchedule.sessionTitle","Create Schedule"),prefill:o("chat.emptyLauncher.actions.createSchedule.prefill","Help me set up a recurring scheduled task. I'll describe what I want it to do, and you guide me through the configuration."),baseSystemPrompt:TC,category:"operations"},{id:"sessionReview",icon:r.jsx(sa,{}),title:o("chat.emptyLauncher.actions.sessionReview.title","Review session history"),description:o("chat.emptyLauncher.actions.sessionReview.description","Inspect and analyze past sessions for patterns and insights."),sessionTitle:o("chat.emptyLauncher.actions.sessionReview.sessionTitle","Session Review"),prefill:o("chat.emptyLauncher.actions.sessionReview.prefill","Help me review my recent session history. Summarize key decisions, outcomes, and areas that need follow-up."),baseSystemPrompt:kC,category:"operations"}],[o]),w=v.trim().toLowerCase(),k=m.useMemo(()=>w?_.filter(P=>P.title.toLowerCase().includes(w)||P.description.toLowerCase().includes(w)):_,[w,_]),C=m.useMemo(()=>{const P={};for(const S of k)P[S.category]||(P[S.category]=[]),P[S.category].push(S);return P},[k]),E=m.useCallback(P=>{typeof window>"u"||window.setTimeout(()=>{window.dispatchEvent(new CustomEvent(Bc,{detail:{sessionId:P}}))},0)},[]),j=m.useCallback(async P=>{if(!y){f(P.id);try{const S=PC(p,u),L=await d({title:P.sessionTitle,createdAt:Date.now(),messages:[],config:{systemPromptId:S.systemPromptId,baseSystemPrompt:P.baseSystemPrompt??S.baseSystemPrompt,lastUsedEnhancedPrompt:null,...x?{workspacePath:x}:{}},currentInteraction:null});hC(L),P.prefill.trim().length>0&&h(L,P.prefill),E(L)}catch(S){console.error("[EmptyTaskLauncher] Failed to create session",S),i.error(S instanceof Error?S.message:o("chat.emptyLauncher.errors.createFailed","Failed to create session"))}finally{f(null)}}},[d,u,i,y,E,h,p,o,x]),R=m.useMemo(()=>({"--lotus-empty-launcher-border":a.colorBorderSecondary,"--lotus-empty-launcher-border-hover":a.colorPrimaryBorder,"--lotus-empty-launcher-bg":a.colorBgElevated,"--lotus-empty-launcher-icon-bg":a.colorPrimaryBg,"--lotus-empty-launcher-icon-color":a.colorPrimary,"--lotus-empty-launcher-text":a.colorText,"--lotus-empty-launcher-text-secondary":a.colorTextSecondary,"--lotus-empty-launcher-shadow":a.boxShadowSecondary,"--lotus-empty-launcher-shadow-hover":a.boxShadow,"--lotus-empty-launcher-category-border":a.colorBorderSecondary,"--lotus-empty-launcher-search-bg":a.colorBgContainer,"--lotus-empty-launcher-badge-bg":a.colorPrimaryBg,"--lotus-empty-launcher-badge-text":a.colorPrimary}),[a]),M=!!x;return r.jsxs("div",{className:`lotus-empty-task-launcher ${t?"is-embedded":""} ${s?"is-headerless":""} ${n==="staggered"?"is-staggered":""}`,style:R,children:[!s&&r.jsxs("div",{className:"lotus-empty-task-launcher__header",children:[r.jsx(le.Title,{level:t?4:3,style:{margin:0},children:o("chat.emptyLauncher.title","Start with a task")}),r.jsx(le.Paragraph,{type:"secondary",className:"lotus-empty-task-launcher__subtitle",children:o("chat.emptyLauncher.subtitle","Create a focused session in this pane and prefill the first message before you send it.")}),r.jsx(le.Text,{type:"secondary",className:"lotus-empty-task-launcher__hint",children:o("chat.emptyLauncher.hint","Nothing is sent automatically — you can edit the prompt first.")})]}),r.jsx("div",{className:"lotus-empty-task-launcher__search",children:r.jsx(me,{placeholder:o("chat.emptyLauncher.searchPlaceholder","Search templates..."),prefix:r.jsx(sa,{style:{color:a.colorTextQuaternary}}),value:v,onChange:P=>b(P.target.value),allowClear:!0,size:"middle",variant:"filled"})}),r.jsxs("div",{className:"lotus-empty-task-launcher__categories",children:[CC.map(P=>{const S=C[P];if(!S||S.length===0)return null;const L=MC[P];return r.jsxs("div",{className:"lotus-empty-task-launcher__category",children:[r.jsx(le.Text,{type:"secondary",className:"lotus-empty-task-launcher__category-label",children:o(L.titleKey,L.fallback)}),r.jsx("div",{className:"lotus-empty-task-launcher__grid",children:S.map($=>{const I=y===$.id,W=$.recommendWorkspace&&M;return r.jsxs("button",{type:"button",className:"lotus-empty-task-card",onClick:()=>{j($)},disabled:y!==null,"aria-busy":I,"aria-label":$.title,children:[r.jsx("div",{className:"lotus-empty-task-card__icon","aria-hidden":!0,children:I?r.jsx(gr,{}):$.icon}),r.jsxs("div",{className:"lotus-empty-task-card__body",children:[r.jsxs("div",{className:"lotus-empty-task-card__titleRow",children:[r.jsx("span",{className:"lotus-empty-task-card__title",children:$.title}),r.jsx(kx,{className:"lotus-empty-task-card__arrow","aria-hidden":!0})]}),r.jsx("p",{className:"lotus-empty-task-card__description",children:$.description}),W&&r.jsx("div",{className:"lotus-empty-task-card__badges",children:r.jsxs("span",{className:"lotus-empty-task-card__badge",title:x,children:["📂 ",o("chat.emptyLauncher.badges.workspace","workspace")]})})]})]},$.id)})})]},P)}),k.length===0&&r.jsx("div",{className:"lotus-empty-task-launcher__no-results",children:r.jsx(le.Text,{type:"secondary",children:o("chat.emptyLauncher.noResults","No templates match your search. Try a different keyword or start a blank session.")})})]})]})},EC=({sessionId:e,isCenteredLayout:t,maxWidth:s,onWorkflowDraftChange:n,showMessagesView:o,sessionDiffSummary:a,contextUsageIndicator:i})=>r.jsx(G,{justify:"center",className:`chat-view-input-container-wrapper ${o?"messages-view":"centered-view"}`,children:r.jsxs("div",{style:{width:"100%",maxWidth:o?s:"min(100%, 920px)",margin:o?"0 auto":void 0,position:"relative",paddingBottom:o?12:0,display:"flex",flexDirection:"column",gap:o?0:24},children:[o&&r.jsx(mC,{sessionDiffSummary:a,sessionId:e}),!o&&e&&r.jsx(qy,{sessionId:e}),r.jsx(iC,{sessionId:e,isCenteredLayout:t,onWorkflowDraftChange:n,statusIndicator:i})]})});function rr(e,t,s){let n=s.initialDeps??[],o;function a(){var i,l,c,d;let u;s.key&&((i=s.debug)!=null&&i.call(s))&&(u=Date.now());const h=e();if(!(h.length!==n.length||h.some((y,f)=>n[f]!==y)))return o;n=h;let g;if(s.key&&((l=s.debug)!=null&&l.call(s))&&(g=Date.now()),o=t(...h),s.key&&((c=s.debug)!=null&&c.call(s))){const y=Math.round((Date.now()-u)*100)/100,f=Math.round((Date.now()-g)*100)/100,v=f/16,b=(x,_)=>{for(x=String(x);x.length<_;)x=" "+x;return x};console.info(`%c⏱ ${b(f,5)} /${b(y,5)} ms`,`
|
|
175
175
|
font-size: .6rem;
|
|
176
176
|
font-weight: bold;
|
|
177
177
|
color: hsl(${Math.max(0,Math.min(120-120*v,120))}deg 100% 31%);`,s==null?void 0:s.key)}return(d=s==null?void 0:s.onChange)==null||d.call(s,o),o}return a.updateDeps=i=>{n=i},a}function yh(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const RC=(e,t)=>Math.abs(e-t)<1.01,AC=(e,t,s)=>{let n;return function(...o){e.clearTimeout(n),n=e.setTimeout(()=>t.apply(this,o),s)}},bh=e=>{const{offsetWidth:t,offsetHeight:s}=e;return{width:t,height:s}},IC=e=>e,$C=e=>{const t=Math.max(e.startIndex-e.overscan,0),s=Math.min(e.endIndex+e.overscan,e.count-1),n=[];for(let o=t;o<=s;o++)n.push(o);return n},DC=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;const o=i=>{const{width:l,height:c}=i;t({width:Math.round(l),height:Math.round(c)})};if(o(bh(s)),!n.ResizeObserver)return()=>{};const a=new n.ResizeObserver(i=>{const l=()=>{const c=i[0];if(c!=null&&c.borderBoxSize){const d=c.borderBoxSize[0];if(d){o({width:d.inlineSize,height:d.blockSize});return}}o(bh(s))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return a.observe(s,{box:"border-box"}),()=>{a.unobserve(s)}},xh={passive:!0},vh=typeof window>"u"?!0:"onscrollend"in window,LC=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;let o=0;const a=e.options.useScrollendEvent&&vh?()=>{}:AC(n,()=>{t(o,!1)},e.options.isScrollingResetDelay),i=u=>()=>{const{horizontal:h,isRtl:p}=e.options;o=h?s.scrollLeft*(p&&-1||1):s.scrollTop,a(),t(o,u)},l=i(!0),c=i(!1);c(),s.addEventListener("scroll",l,xh);const d=e.options.useScrollendEvent&&vh;return d&&s.addEventListener("scrollend",c,xh),()=>{s.removeEventListener("scroll",l),d&&s.removeEventListener("scrollend",c)}},OC=(e,t,s)=>{if(t!=null&&t.borderBoxSize){const n=t.borderBoxSize[0];if(n)return Math.round(n[s.options.horizontal?"inlineSize":"blockSize"])}return e[s.options.horizontal?"offsetWidth":"offsetHeight"]},FC=(e,{adjustments:t=0,behavior:s},n)=>{var o,a;const i=e+t;(a=(o=n.scrollElement)==null?void 0:o.scrollTo)==null||a.call(o,{[n.options.horizontal?"left":"top"]:i,behavior:s})};class zC{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.measurementsCache=[],this.itemSizeCache=new Map,this.pendingMeasuredCacheIndexes=[],this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.observer=(()=>{let s=null;const n=()=>s||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:s=new this.targetWindow.ResizeObserver(o=>{o.forEach(a=>{const i=()=>{this._measureElement(a.target,a)};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var o;(o=n())==null||o.disconnect(),s=null},observe:o=>{var a;return(a=n())==null?void 0:a.observe(o,{box:"border-box"})},unobserve:o=>{var a;return(a=n())==null?void 0:a.unobserve(o)}}})(),this.range=null,this.setOptions=s=>{Object.entries(s).forEach(([n,o])=>{typeof o>"u"&&delete s[n]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:IC,rangeExtractor:$C,onChange:()=>{},measureElement:OC,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,...s}},this.notify=s=>{var n,o;(o=(n=this.options).onChange)==null||o.call(n,this,s)},this.maybeNotify=rr(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),s=>{this.notify(s)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(s=>s()),this.unsubs=[],this.observer.disconnect(),this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var s;const n=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==n){if(this.cleanup(),!n){this.maybeNotify();return}this.scrollElement=n,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((s=this.scrollElement)==null?void 0:s.window)??null,this.elementsCache.forEach(o=>{this.observer.observe(o)}),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0}),this.unsubs.push(this.options.observeElementRect(this,o=>{this.scrollRect=o,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(o,a)=>{this.scrollAdjustments=0,this.scrollDirection=a?this.getScrollOffset()<o?"forward":"backward":null,this.scrollOffset=o,this.isScrolling=a,this.maybeNotify()}))}},this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(s,n)=>{const o=new Map,a=new Map;for(let i=n-1;i>=0;i--){const l=s[i];if(o.has(l.lane))continue;const c=a.get(l.lane);if(c==null||l.end>c.end?a.set(l.lane,l):l.end<c.end&&o.set(l.lane,!0),o.size===this.options.lanes)break}return a.size===this.options.lanes?Array.from(a.values()).sort((i,l)=>i.end===l.end?i.index-l.index:i.end-l.end)[0]:void 0},this.getMeasurementOptions=rr(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled],(s,n,o,a,i)=>(this.pendingMeasuredCacheIndexes=[],{count:s,paddingStart:n,scrollMargin:o,getItemKey:a,enabled:i}),{key:!1}),this.getMeasurements=rr(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:s,paddingStart:n,scrollMargin:o,getItemKey:a,enabled:i},l)=>{if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),[];this.measurementsCache.length===0&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(u=>{this.itemSizeCache.set(u.key,u.size)}));const c=this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[];const d=this.measurementsCache.slice(0,c);for(let u=c;u<s;u++){const h=a(u),p=this.options.lanes===1?d[u-1]:this.getFurthestMeasurement(d,u),g=p?p.end+this.options.gap:n+o,y=l.get(h),f=typeof y=="number"?y:this.options.estimateSize(u),v=g+f,b=p?p.lane:u%this.options.lanes;d[u]={index:u,start:g,size:f,end:v,key:h,lane:b}}return this.measurementsCache=d,d},{key:!1,debug:()=>this.options.debug}),this.calculateRange=rr(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(s,n,o,a)=>this.range=s.length>0&&n>0?NC({measurements:s,outerSize:n,scrollOffset:o,lanes:a}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=rr(()=>{let s=null,n=null;const o=this.calculateRange();return o&&(s=o.startIndex,n=o.endIndex),this.maybeNotify.updateDeps([this.isScrolling,s,n]),[this.options.rangeExtractor,this.options.overscan,this.options.count,s,n]},(s,n,o,a,i)=>a===null||i===null?[]:s({startIndex:a,endIndex:i,overscan:n,count:o}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=s=>{const n=this.options.indexAttribute,o=s.getAttribute(n);return o?parseInt(o,10):(console.warn(`Missing attribute name '${n}={index}' on measured element.`),-1)},this._measureElement=(s,n)=>{const o=this.indexFromElement(s),a=this.measurementsCache[o];if(!a)return;const i=a.key,l=this.elementsCache.get(i);l!==s&&(l&&this.observer.unobserve(l),this.observer.observe(s),this.elementsCache.set(i,s)),s.isConnected&&this.resizeItem(o,this.options.measureElement(s,n,this))},this.resizeItem=(s,n)=>{const o=this.measurementsCache[s];if(!o)return;const a=this.itemSizeCache.get(o.key)??o.size,i=n-a;i!==0&&((this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(o,i,this):o.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=i,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(o.index),this.itemSizeCache=new Map(this.itemSizeCache.set(o.key,n)),this.notify(!1))},this.measureElement=s=>{if(!s){this.elementsCache.forEach((n,o)=>{n.isConnected||(this.observer.unobserve(n),this.elementsCache.delete(o))});return}this._measureElement(s,void 0)},this.getVirtualItems=rr(()=>[this.getVirtualIndexes(),this.getMeasurements()],(s,n)=>{const o=[];for(let a=0,i=s.length;a<i;a++){const l=s[a],c=n[l];o.push(c)}return o},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=s=>{const n=this.getMeasurements();if(n.length!==0)return yh(n[Hy(0,n.length-1,o=>yh(n[o]).start,s)])},this.getOffsetForAlignment=(s,n,o=0)=>{const a=this.getSize(),i=this.getScrollOffset();n==="auto"&&(n=s>=i+a?"end":"start"),n==="center"?s+=(o-a)/2:n==="end"&&(s-=a);const l=this.getTotalSize()+this.options.scrollMargin-a;return Math.max(Math.min(l,s),0)},this.getOffsetForIndex=(s,n="auto")=>{s=Math.max(0,Math.min(s,this.options.count-1));const o=this.measurementsCache[s];if(!o)return;const a=this.getSize(),i=this.getScrollOffset();if(n==="auto")if(o.end>=i+a-this.options.scrollPaddingEnd)n="end";else if(o.start<=i+this.options.scrollPaddingStart)n="start";else return[i,n];const l=n==="end"?o.end+this.options.scrollPaddingEnd:o.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(l,n,o.size),n]},this.isDynamicMode=()=>this.elementsCache.size>0,this.scrollToOffset=(s,{align:n="start",behavior:o}={})=>{o==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),this._scrollToOffset(this.getOffsetForAlignment(s,n),{adjustments:void 0,behavior:o})},this.scrollToIndex=(s,{align:n="auto",behavior:o}={})=>{o==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),s=Math.max(0,Math.min(s,this.options.count-1));let a=0;const i=10,l=d=>{if(!this.targetWindow)return;const u=this.getOffsetForIndex(s,d);if(!u){console.warn("Failed to get offset for index:",s);return}const[h,p]=u;this._scrollToOffset(h,{adjustments:void 0,behavior:o}),this.targetWindow.requestAnimationFrame(()=>{const g=this.getScrollOffset(),y=this.getOffsetForIndex(s,p);if(!y){console.warn("Failed to get offset for index:",s);return}RC(y[0],g)||c(p)})},c=d=>{this.targetWindow&&(a++,a<i?this.targetWindow.requestAnimationFrame(()=>l(d)):console.warn(`Failed to scroll to index ${s} after ${i} attempts.`))};l(n)},this.scrollBy=(s,{behavior:n}={})=>{n==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),this._scrollToOffset(this.getScrollOffset()+s,{adjustments:void 0,behavior:n})},this.getTotalSize=()=>{var s;const n=this.getMeasurements();let o;if(n.length===0)o=this.options.paddingStart;else if(this.options.lanes===1)o=((s=n[n.length-1])==null?void 0:s.end)??0;else{const a=Array(this.options.lanes).fill(null);let i=n.length-1;for(;i>=0&&a.some(l=>l===null);){const l=n[i];a[l.lane]===null&&(a[l.lane]=l.end),i--}o=Math.max(...a.filter(l=>l!==null))}return Math.max(o-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(s,{adjustments:n,behavior:o})=>{this.options.scrollToFn(s,{behavior:o,adjustments:n},this)},this.measure=()=>{this.itemSizeCache=new Map,this.notify(!1)},this.setOptions(t)}}const Hy=(e,t,s,n)=>{for(;e<=t;){const o=(e+t)/2|0,a=s(o);if(a<n)e=o+1;else if(a>n)t=o-1;else return o}return e>0?e-1:0};function NC({measurements:e,outerSize:t,scrollOffset:s,lanes:n}){const o=e.length-1,a=c=>e[c].start;if(e.length<=n)return{startIndex:0,endIndex:o};let i=Hy(0,o,a,s),l=i;if(n===1)for(;l<o&&e[l].end<s+t;)l++;else if(n>1){const c=Array(n).fill(0);for(;l<o&&c.some(u=>u<s+t);){const u=e[l];c[u.lane]=u.end,l++}const d=Array(n).fill(s+t);for(;i>=0&&d.some(u=>u>=s);){const u=e[i];d[u.lane]=u.start,i--}i=Math.max(0,i-i%n),l=Math.min(o,l+(n-1-l%n))}return{startIndex:i,endIndex:l}}const Sh=typeof document<"u"?m.useLayoutEffect:m.useEffect;function BC(e){const t=m.useReducer(()=>({}),{})[1],s={...e,onChange:(o,a)=>{var i;a?jx.flushSync(t):t(),(i=e.onChange)==null||i.call(e,o,a)}},[n]=m.useState(()=>new zC(s));return n.setOptions(s),Sh(()=>n._didMount(),[]),Sh(()=>n._willUpdate()),n}function WC(e){return BC({observeElementRect:DC,observeElementOffset:LC,scrollToFn:FC,...e})}const{Text:wh,Paragraph:UC}=le,qC=({content:e,token:t,headingColor:s})=>r.jsx(hs,{components:{p:({children:n})=>r.jsx(UC,{style:{marginBottom:t.marginSM},children:n}),ol:({children:n})=>r.jsx("ol",{style:{marginBottom:t.marginSM,paddingLeft:20},children:n}),ul:({children:n})=>r.jsx("ul",{style:{marginBottom:t.marginSM,paddingLeft:20},children:n}),li:({children:n})=>r.jsx("li",{style:{marginBottom:t.marginXS},children:n}),h1:({children:n})=>r.jsx(wh,{strong:!0,style:{fontSize:t.fontSizeHeading3,marginBottom:t.marginSM,display:"block",color:s},children:n}),h2:({children:n})=>r.jsx(wh,{strong:!0,style:{fontSize:t.fontSizeHeading4,marginBottom:t.marginSM,display:"block",color:s},children:n})},children:e}),_h=m.memo(qC),HC=e=>{if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null},YC=e=>e?[["base",e.base_system_prompt],["enhancement",e.enhancement_prompt],["workspace",e.workspace_context],["instruction",e.instruction_context],["env",e.env_context],["skills",e.skill_context],["toolGuide",e.tool_guide_context],["dream",e.dream_notebook],["sessionMemory",e.session_memory_note],["externalMemory",e.external_memory],["taskList",e.task_list],["effective",e.effective_system_prompt]].flatMap(([s,n])=>{const o=HC(n);return o?[{key:s,content:o}]:[]}):[],XC=({currentChat:e,message:t,systemPrompts:s})=>{var M;const[n,o]=m.useState(null),[a,i]=m.useState(null),[l,c]=m.useState(null),[d,u]=m.useState(!1),[h,p]=m.useState(!1),g=m.useMemo(()=>yi.getInstance(),[]),y=m.useMemo(()=>rs.getInstance(),[]),f=t.role==="system"&&typeof t.content=="string"?t.content:"",v=t.role==="system"&&!t.id.startsWith("system-prompt-")&&f.trim().length>0;m.useEffect(()=>{t.role==="system"&&(i(null),c(null),p(!1))},[t.id,t.role,f]);const b=(e==null?void 0:e.id)??null,x=((M=e==null?void 0:e.config)==null?void 0:M.systemPromptId)??null,_=m.useMemo(()=>x?s.find(T=>T.id===x)??null:null,[x,s]),w=(_==null?void 0:_.content)??(n==null?void 0:n.content)??"",k=(_==null?void 0:_.description)??(n==null?void 0:n.description)??"",C=m.useRef(null);m.useEffect(()=>{o(null),C.current=null},[b,x]),m.useEffect(()=>{if(!x)return;const T=x;if(_!=null&&_.content)return;const P=`${b??"no-chat"}:${T}`;if(C.current===P)return;C.current=P;let S=!1;return(async()=>{try{const $=await g.findPresetById(T);if(S)return;const I=$?{content:$.content,description:$.description}:null;o(W=>!W&&!I||W&&I&&W.content===I.content&&W.description===I.description?W:I)}catch($){console.error("Failed to load preset prompt:",$)}})(),()=>{S=!0}},[b,x,g,_==null?void 0:_.content]);const E=m.useCallback(async()=>{var T;if(!d){u(!0);try{if(b)try{const P=await y.getSessionSystemPrompt(b);c(P);const S=(T=P.effective_system_prompt)==null?void 0:T.trim();if(S){i(S),p(!0);return}}catch(P){console.warn("Failed to load backend prompt snapshot:",P)}if(v){c(null),i(f),p(!0);return}console.warn("Enhanced prompt snapshot unavailable; keeping base prompt view.")}catch(P){console.error("Failed to load enhanced prompt:",P)}finally{u(!1)}}},[y,b,v,d,f]),j=m.useMemo(()=>h&&a?a:w||k||(t.role==="system"?f:"System prompt is being prepared..."),[h,a,w,k,t.role,f]),R=m.useMemo(()=>YC(l),[l]);return{basePrompt:w,categoryDescription:k,enhancedPrompt:a,loadingEnhanced:d,loadEnhancedPrompt:E,promptSnapshot:l,promptToDisplay:j,showEnhanced:h,setShowEnhanced:p,snapshotSections:R,systemMessageContent:f}},{Text:Th}=le,{useToken:VC}=he,KC=(e,t)=>({base:e("chat.prompt.systemCard.sections.base"),enhancement:e("chat.prompt.systemCard.sections.enhancement"),workspace:e("chat.prompt.systemCard.sections.workspace"),instruction:e("chat.prompt.systemCard.sections.instruction"),env:e("chat.prompt.systemCard.sections.env"),skills:e("chat.prompt.systemCard.sections.skills"),toolGuide:e("chat.prompt.systemCard.sections.toolGuide"),dream:e("chat.prompt.systemCard.sections.dream"),sessionMemory:e("chat.prompt.systemCard.sections.sessionMemory"),externalMemory:e("chat.prompt.systemCard.sections.externalMemory"),taskList:e("chat.prompt.systemCard.sections.taskList"),effective:e("chat.prompt.systemCard.sections.effective")})[t],GC=({currentChat:e,message:t})=>{const{token:s}=VC(),{t:n}=ne(),o=N(y=>y.systemPrompts),{basePrompt:a,loadingEnhanced:i,loadEnhancedPrompt:l,promptSnapshot:c,promptToDisplay:d,showEnhanced:u,setShowEnhanced:h,snapshotSections:p}=XC({currentChat:e,message:t,systemPrompts:o}),g=m.useCallback(async y=>{try{await os(y)}catch(f){console.error("Failed to copy text:",f)}},[]);return r.jsx(ee,{style:{width:"100%",maxWidth:"100%",background:s.colorBgContainer,borderRadius:s.borderRadiusLG,boxShadow:"none"},children:r.jsxs(X,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[r.jsxs(G,{justify:"space-between",align:"center",children:[r.jsx(G,{align:"center",gap:s.marginXS,children:r.jsx(Th,{type:"secondary",strong:!0,style:{fontSize:s.fontSizeSM},children:n("chat.prompt.systemCard.title")})}),r.jsxs(X,{children:[a&&!u?r.jsx(Y,{type:"text",size:"small",icon:r.jsx(td,{}),onClick:l,loading:i,children:n("chat.prompt.systemCard.viewEnhanced")}):null,a&&u?r.jsx(Y,{type:"text",size:"small",onClick:()=>h(!1),children:n("chat.prompt.systemCard.viewBase")}):null,r.jsx(Y,{type:"text",size:"small",icon:r.jsx(ss,{}),onClick:()=>g(d),children:n("chat.prompt.systemCard.copy")})]})]}),r.jsx(G,{vertical:!0,style:{maxHeight:u?400:300,overflowY:"auto",paddingRight:s.paddingXS},children:r.jsx(_h,{content:d,token:s,headingColor:s.colorPrimary})}),c&&p.length>0?r.jsxs(r.Fragment,{children:[r.jsx(Rt,{style:{margin:`${s.marginXS}px 0`}}),r.jsxs(X,{direction:"vertical",size:s.marginXS,style:{width:"100%"},children:[r.jsx(Th,{type:"secondary",strong:!0,style:{fontSize:s.fontSizeSM},children:n("chat.prompt.systemCard.snapshotTitle")}),r.jsx(ns,{defaultActiveKey:p.map(y=>y.key),items:p.map(y=>({key:y.key,label:KC(n,y.key),children:r.jsx(_h,{content:y.content,token:s,headingColor:s.colorPrimary})}))})]})]}):null]})})},Yy=m.memo(GC);Yy.displayName="SystemMessageCard";const Xy=6048e5,JC=864e5,kh=Symbol.for("constructDateFrom");function ln(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&kh in e?e[kh](t):e instanceof Date?new e.constructor(t):new Date(t)}function gs(e,t){return ln(t||e,e)}let QC={};function Ki(){return QC}function la(e,t){var l,c,d,u;const s=Ki(),n=(t==null?void 0:t.weekStartsOn)??((c=(l=t==null?void 0:t.locale)==null?void 0:l.options)==null?void 0:c.weekStartsOn)??s.weekStartsOn??((u=(d=s.locale)==null?void 0:d.options)==null?void 0:u.weekStartsOn)??0,o=gs(e,t==null?void 0:t.in),a=o.getDay(),i=(a<n?7:0)+a-n;return o.setDate(o.getDate()-i),o.setHours(0,0,0,0),o}function Ei(e,t){return la(e,{...t,weekStartsOn:1})}function Vy(e,t){const s=gs(e,t==null?void 0:t.in),n=s.getFullYear(),o=ln(s,0);o.setFullYear(n+1,0,4),o.setHours(0,0,0,0);const a=Ei(o),i=ln(s,0);i.setFullYear(n,0,4),i.setHours(0,0,0,0);const l=Ei(i);return s.getTime()>=a.getTime()?n+1:s.getTime()>=l.getTime()?n:n-1}function jh(e){const t=gs(e),s=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return s.setUTCFullYear(t.getFullYear()),+e-+s}function ZC(e,...t){const s=ln.bind(null,t.find(n=>typeof n=="object"));return t.map(s)}function Ch(e,t){const s=gs(e,t==null?void 0:t.in);return s.setHours(0,0,0,0),s}function eM(e,t,s){const[n,o]=ZC(s==null?void 0:s.in,e,t),a=Ch(n),i=Ch(o),l=+a-jh(a),c=+i-jh(i);return Math.round((l-c)/JC)}function tM(e,t){const s=Vy(e,t),n=ln(e,0);return n.setFullYear(s,0,4),n.setHours(0,0,0,0),Ei(n)}function sM(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function nM(e){return!(!sM(e)&&typeof e!="number"||isNaN(+gs(e)))}function rM(e,t){const s=gs(e,t==null?void 0:t.in);return s.setFullYear(s.getFullYear(),0,1),s.setHours(0,0,0,0),s}const oM={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},aM=(e,t,s)=>{let n;const o=oM[e];return typeof o=="string"?n=o:t===1?n=o.one:n=o.other.replace("{{count}}",t.toString()),s!=null&&s.addSuffix?s.comparison&&s.comparison>0?"in "+n:n+" ago":n};function Il(e){return(t={})=>{const s=t.width?String(t.width):e.defaultWidth;return e.formats[s]||e.formats[e.defaultWidth]}}const iM={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},lM={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},cM={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},dM={date:Il({formats:iM,defaultWidth:"full"}),time:Il({formats:lM,defaultWidth:"full"}),dateTime:Il({formats:cM,defaultWidth:"full"})},uM={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},mM=(e,t,s,n)=>uM[e];function Xr(e){return(t,s)=>{const n=s!=null&&s.context?String(s.context):"standalone";let o;if(n==="formatting"&&e.formattingValues){const i=e.defaultFormattingWidth||e.defaultWidth,l=s!=null&&s.width?String(s.width):i;o=e.formattingValues[l]||e.formattingValues[i]}else{const i=e.defaultWidth,l=s!=null&&s.width?String(s.width):e.defaultWidth;o=e.values[l]||e.values[i]}const a=e.argumentCallback?e.argumentCallback(t):t;return o[a]}}const hM={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},pM={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},fM={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},gM={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},yM={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},bM={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},xM=(e,t)=>{const s=Number(e),n=s%100;if(n>20||n<10)switch(n%10){case 1:return s+"st";case 2:return s+"nd";case 3:return s+"rd"}return s+"th"},vM={ordinalNumber:xM,era:Xr({values:hM,defaultWidth:"wide"}),quarter:Xr({values:pM,defaultWidth:"wide",argumentCallback:e=>e-1}),month:Xr({values:fM,defaultWidth:"wide"}),day:Xr({values:gM,defaultWidth:"wide"}),dayPeriod:Xr({values:yM,defaultWidth:"wide",formattingValues:bM,defaultFormattingWidth:"wide"})};function Vr(e){return(t,s={})=>{const n=s.width,o=n&&e.matchPatterns[n]||e.matchPatterns[e.defaultMatchWidth],a=t.match(o);if(!a)return null;const i=a[0],l=n&&e.parsePatterns[n]||e.parsePatterns[e.defaultParseWidth],c=Array.isArray(l)?wM(l,h=>h.test(i)):SM(l,h=>h.test(i));let d;d=e.valueCallback?e.valueCallback(c):c,d=s.valueCallback?s.valueCallback(d):d;const u=t.slice(i.length);return{value:d,rest:u}}}function SM(e,t){for(const s in e)if(Object.prototype.hasOwnProperty.call(e,s)&&t(e[s]))return s}function wM(e,t){for(let s=0;s<e.length;s++)if(t(e[s]))return s}function _M(e){return(t,s={})=>{const n=t.match(e.matchPattern);if(!n)return null;const o=n[0],a=t.match(e.parsePattern);if(!a)return null;let i=e.valueCallback?e.valueCallback(a[0]):a[0];i=s.valueCallback?s.valueCallback(i):i;const l=t.slice(o.length);return{value:i,rest:l}}}const TM=/^(\d+)(th|st|nd|rd)?/i,kM=/\d+/i,jM={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},CM={any:[/^b/i,/^(a|c)/i]},MM={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},PM={any:[/1/i,/2/i,/3/i,/4/i]},EM={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},RM={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},AM={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},IM={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},$M={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},DM={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},LM={ordinalNumber:_M({matchPattern:TM,parsePattern:kM,valueCallback:e=>parseInt(e,10)}),era:Vr({matchPatterns:jM,defaultMatchWidth:"wide",parsePatterns:CM,defaultParseWidth:"any"}),quarter:Vr({matchPatterns:MM,defaultMatchWidth:"wide",parsePatterns:PM,defaultParseWidth:"any",valueCallback:e=>e+1}),month:Vr({matchPatterns:EM,defaultMatchWidth:"wide",parsePatterns:RM,defaultParseWidth:"any"}),day:Vr({matchPatterns:AM,defaultMatchWidth:"wide",parsePatterns:IM,defaultParseWidth:"any"}),dayPeriod:Vr({matchPatterns:$M,defaultMatchWidth:"any",parsePatterns:DM,defaultParseWidth:"any"})},OM={code:"en-US",formatDistance:aM,formatLong:dM,formatRelative:mM,localize:vM,match:LM,options:{weekStartsOn:0,firstWeekContainsDate:1}};function FM(e,t){const s=gs(e,t==null?void 0:t.in);return eM(s,rM(s))+1}function zM(e,t){const s=gs(e,t==null?void 0:t.in),n=+Ei(s)-+tM(s);return Math.round(n/Xy)+1}function Ky(e,t){var u,h,p,g;const s=gs(e,t==null?void 0:t.in),n=s.getFullYear(),o=Ki(),a=(t==null?void 0:t.firstWeekContainsDate)??((h=(u=t==null?void 0:t.locale)==null?void 0:u.options)==null?void 0:h.firstWeekContainsDate)??o.firstWeekContainsDate??((g=(p=o.locale)==null?void 0:p.options)==null?void 0:g.firstWeekContainsDate)??1,i=ln((t==null?void 0:t.in)||e,0);i.setFullYear(n+1,0,a),i.setHours(0,0,0,0);const l=la(i,t),c=ln((t==null?void 0:t.in)||e,0);c.setFullYear(n,0,a),c.setHours(0,0,0,0);const d=la(c,t);return+s>=+l?n+1:+s>=+d?n:n-1}function NM(e,t){var l,c,d,u;const s=Ki(),n=(t==null?void 0:t.firstWeekContainsDate)??((c=(l=t==null?void 0:t.locale)==null?void 0:l.options)==null?void 0:c.firstWeekContainsDate)??s.firstWeekContainsDate??((u=(d=s.locale)==null?void 0:d.options)==null?void 0:u.firstWeekContainsDate)??1,o=Ky(e,t),a=ln((t==null?void 0:t.in)||e,0);return a.setFullYear(o,0,n),a.setHours(0,0,0,0),la(a,t)}function BM(e,t){const s=gs(e,t==null?void 0:t.in),n=+la(s,t)-+NM(s,t);return Math.round(n/Xy)+1}function We(e,t){const s=e<0?"-":"",n=Math.abs(e).toString().padStart(t,"0");return s+n}const en={y(e,t){const s=e.getFullYear(),n=s>0?s:1-s;return We(t==="yy"?n%100:n,t.length)},M(e,t){const s=e.getMonth();return t==="M"?String(s+1):We(s+1,2)},d(e,t){return We(e.getDate(),t.length)},a(e,t){const s=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return s.toUpperCase();case"aaa":return s;case"aaaaa":return s[0];case"aaaa":default:return s==="am"?"a.m.":"p.m."}},h(e,t){return We(e.getHours()%12||12,t.length)},H(e,t){return We(e.getHours(),t.length)},m(e,t){return We(e.getMinutes(),t.length)},s(e,t){return We(e.getSeconds(),t.length)},S(e,t){const s=t.length,n=e.getMilliseconds(),o=Math.trunc(n*Math.pow(10,s-3));return We(o,t.length)}},or={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Mh={G:function(e,t,s){const n=e.getFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return s.era(n,{width:"abbreviated"});case"GGGGG":return s.era(n,{width:"narrow"});case"GGGG":default:return s.era(n,{width:"wide"})}},y:function(e,t,s){if(t==="yo"){const n=e.getFullYear(),o=n>0?n:1-n;return s.ordinalNumber(o,{unit:"year"})}return en.y(e,t)},Y:function(e,t,s,n){const o=Ky(e,n),a=o>0?o:1-o;if(t==="YY"){const i=a%100;return We(i,2)}return t==="Yo"?s.ordinalNumber(a,{unit:"year"}):We(a,t.length)},R:function(e,t){const s=Vy(e);return We(s,t.length)},u:function(e,t){const s=e.getFullYear();return We(s,t.length)},Q:function(e,t,s){const n=Math.ceil((e.getMonth()+1)/3);switch(t){case"Q":return String(n);case"QQ":return We(n,2);case"Qo":return s.ordinalNumber(n,{unit:"quarter"});case"QQQ":return s.quarter(n,{width:"abbreviated",context:"formatting"});case"QQQQQ":return s.quarter(n,{width:"narrow",context:"formatting"});case"QQQQ":default:return s.quarter(n,{width:"wide",context:"formatting"})}},q:function(e,t,s){const n=Math.ceil((e.getMonth()+1)/3);switch(t){case"q":return String(n);case"qq":return We(n,2);case"qo":return s.ordinalNumber(n,{unit:"quarter"});case"qqq":return s.quarter(n,{width:"abbreviated",context:"standalone"});case"qqqqq":return s.quarter(n,{width:"narrow",context:"standalone"});case"qqqq":default:return s.quarter(n,{width:"wide",context:"standalone"})}},M:function(e,t,s){const n=e.getMonth();switch(t){case"M":case"MM":return en.M(e,t);case"Mo":return s.ordinalNumber(n+1,{unit:"month"});case"MMM":return s.month(n,{width:"abbreviated",context:"formatting"});case"MMMMM":return s.month(n,{width:"narrow",context:"formatting"});case"MMMM":default:return s.month(n,{width:"wide",context:"formatting"})}},L:function(e,t,s){const n=e.getMonth();switch(t){case"L":return String(n+1);case"LL":return We(n+1,2);case"Lo":return s.ordinalNumber(n+1,{unit:"month"});case"LLL":return s.month(n,{width:"abbreviated",context:"standalone"});case"LLLLL":return s.month(n,{width:"narrow",context:"standalone"});case"LLLL":default:return s.month(n,{width:"wide",context:"standalone"})}},w:function(e,t,s,n){const o=BM(e,n);return t==="wo"?s.ordinalNumber(o,{unit:"week"}):We(o,t.length)},I:function(e,t,s){const n=zM(e);return t==="Io"?s.ordinalNumber(n,{unit:"week"}):We(n,t.length)},d:function(e,t,s){return t==="do"?s.ordinalNumber(e.getDate(),{unit:"date"}):en.d(e,t)},D:function(e,t,s){const n=FM(e);return t==="Do"?s.ordinalNumber(n,{unit:"dayOfYear"}):We(n,t.length)},E:function(e,t,s){const n=e.getDay();switch(t){case"E":case"EE":case"EEE":return s.day(n,{width:"abbreviated",context:"formatting"});case"EEEEE":return s.day(n,{width:"narrow",context:"formatting"});case"EEEEEE":return s.day(n,{width:"short",context:"formatting"});case"EEEE":default:return s.day(n,{width:"wide",context:"formatting"})}},e:function(e,t,s,n){const o=e.getDay(),a=(o-n.weekStartsOn+8)%7||7;switch(t){case"e":return String(a);case"ee":return We(a,2);case"eo":return s.ordinalNumber(a,{unit:"day"});case"eee":return s.day(o,{width:"abbreviated",context:"formatting"});case"eeeee":return s.day(o,{width:"narrow",context:"formatting"});case"eeeeee":return s.day(o,{width:"short",context:"formatting"});case"eeee":default:return s.day(o,{width:"wide",context:"formatting"})}},c:function(e,t,s,n){const o=e.getDay(),a=(o-n.weekStartsOn+8)%7||7;switch(t){case"c":return String(a);case"cc":return We(a,t.length);case"co":return s.ordinalNumber(a,{unit:"day"});case"ccc":return s.day(o,{width:"abbreviated",context:"standalone"});case"ccccc":return s.day(o,{width:"narrow",context:"standalone"});case"cccccc":return s.day(o,{width:"short",context:"standalone"});case"cccc":default:return s.day(o,{width:"wide",context:"standalone"})}},i:function(e,t,s){const n=e.getDay(),o=n===0?7:n;switch(t){case"i":return String(o);case"ii":return We(o,t.length);case"io":return s.ordinalNumber(o,{unit:"day"});case"iii":return s.day(n,{width:"abbreviated",context:"formatting"});case"iiiii":return s.day(n,{width:"narrow",context:"formatting"});case"iiiiii":return s.day(n,{width:"short",context:"formatting"});case"iiii":default:return s.day(n,{width:"wide",context:"formatting"})}},a:function(e,t,s){const o=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return s.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"aaa":return s.dayPeriod(o,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return s.dayPeriod(o,{width:"narrow",context:"formatting"});case"aaaa":default:return s.dayPeriod(o,{width:"wide",context:"formatting"})}},b:function(e,t,s){const n=e.getHours();let o;switch(n===12?o=or.noon:n===0?o=or.midnight:o=n/12>=1?"pm":"am",t){case"b":case"bb":return s.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"bbb":return s.dayPeriod(o,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return s.dayPeriod(o,{width:"narrow",context:"formatting"});case"bbbb":default:return s.dayPeriod(o,{width:"wide",context:"formatting"})}},B:function(e,t,s){const n=e.getHours();let o;switch(n>=17?o=or.evening:n>=12?o=or.afternoon:n>=4?o=or.morning:o=or.night,t){case"B":case"BB":case"BBB":return s.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"BBBBB":return s.dayPeriod(o,{width:"narrow",context:"formatting"});case"BBBB":default:return s.dayPeriod(o,{width:"wide",context:"formatting"})}},h:function(e,t,s){if(t==="ho"){let n=e.getHours()%12;return n===0&&(n=12),s.ordinalNumber(n,{unit:"hour"})}return en.h(e,t)},H:function(e,t,s){return t==="Ho"?s.ordinalNumber(e.getHours(),{unit:"hour"}):en.H(e,t)},K:function(e,t,s){const n=e.getHours()%12;return t==="Ko"?s.ordinalNumber(n,{unit:"hour"}):We(n,t.length)},k:function(e,t,s){let n=e.getHours();return n===0&&(n=24),t==="ko"?s.ordinalNumber(n,{unit:"hour"}):We(n,t.length)},m:function(e,t,s){return t==="mo"?s.ordinalNumber(e.getMinutes(),{unit:"minute"}):en.m(e,t)},s:function(e,t,s){return t==="so"?s.ordinalNumber(e.getSeconds(),{unit:"second"}):en.s(e,t)},S:function(e,t){return en.S(e,t)},X:function(e,t,s){const n=e.getTimezoneOffset();if(n===0)return"Z";switch(t){case"X":return Eh(n);case"XXXX":case"XX":return Tn(n);case"XXXXX":case"XXX":default:return Tn(n,":")}},x:function(e,t,s){const n=e.getTimezoneOffset();switch(t){case"x":return Eh(n);case"xxxx":case"xx":return Tn(n);case"xxxxx":case"xxx":default:return Tn(n,":")}},O:function(e,t,s){const n=e.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+Ph(n,":");case"OOOO":default:return"GMT"+Tn(n,":")}},z:function(e,t,s){const n=e.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+Ph(n,":");case"zzzz":default:return"GMT"+Tn(n,":")}},t:function(e,t,s){const n=Math.trunc(+e/1e3);return We(n,t.length)},T:function(e,t,s){return We(+e,t.length)}};function Ph(e,t=""){const s=e>0?"-":"+",n=Math.abs(e),o=Math.trunc(n/60),a=n%60;return a===0?s+String(o):s+String(o)+t+We(a,2)}function Eh(e,t){return e%60===0?(e>0?"-":"+")+We(Math.abs(e)/60,2):Tn(e,t)}function Tn(e,t=""){const s=e>0?"-":"+",n=Math.abs(e),o=We(Math.trunc(n/60),2),a=We(n%60,2);return s+o+t+a}const Rh=(e,t)=>{switch(e){case"P":return t.date({width:"short"});case"PP":return t.date({width:"medium"});case"PPP":return t.date({width:"long"});case"PPPP":default:return t.date({width:"full"})}},Gy=(e,t)=>{switch(e){case"p":return t.time({width:"short"});case"pp":return t.time({width:"medium"});case"ppp":return t.time({width:"long"});case"pppp":default:return t.time({width:"full"})}},WM=(e,t)=>{const s=e.match(/(P+)(p+)?/)||[],n=s[1],o=s[2];if(!o)return Rh(e,t);let a;switch(n){case"P":a=t.dateTime({width:"short"});break;case"PP":a=t.dateTime({width:"medium"});break;case"PPP":a=t.dateTime({width:"long"});break;case"PPPP":default:a=t.dateTime({width:"full"});break}return a.replace("{{date}}",Rh(n,t)).replace("{{time}}",Gy(o,t))},UM={p:Gy,P:WM},qM=/^D+$/,HM=/^Y+$/,YM=["D","DD","YY","YYYY"];function XM(e){return qM.test(e)}function VM(e){return HM.test(e)}function KM(e,t,s){const n=GM(e,t,s);if(console.warn(n),YM.includes(e))throw new RangeError(n)}function GM(e,t,s){const n=e[0]==="Y"?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${t}\`) for formatting ${n} to the input \`${s}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const JM=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,QM=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,ZM=/^'([^]*?)'?$/,eP=/''/g,tP=/[a-zA-Z]/;function sP(e,t,s){var u,h,p,g;const n=Ki(),o=n.locale??OM,a=n.firstWeekContainsDate??((h=(u=n.locale)==null?void 0:u.options)==null?void 0:h.firstWeekContainsDate)??1,i=n.weekStartsOn??((g=(p=n.locale)==null?void 0:p.options)==null?void 0:g.weekStartsOn)??0,l=gs(e,s==null?void 0:s.in);if(!nM(l))throw new RangeError("Invalid time value");let c=t.match(QM).map(y=>{const f=y[0];if(f==="p"||f==="P"){const v=UM[f];return v(y,o.formatLong)}return y}).join("").match(JM).map(y=>{if(y==="''")return{isToken:!1,value:"'"};const f=y[0];if(f==="'")return{isToken:!1,value:nP(y)};if(Mh[f])return{isToken:!0,value:y};if(f.match(tP))throw new RangeError("Format string contains an unescaped latin alphabet character `"+f+"`");return{isToken:!1,value:y}});o.localize.preprocessor&&(c=o.localize.preprocessor(l,c));const d={firstWeekContainsDate:a,weekStartsOn:i,locale:o};return c.map(y=>{if(!y.isToken)return y.value;const f=y.value;(VM(f)||XM(f))&&KM(f,t,String(e));const v=Mh[f[0]];return v(l,f,o.localize,d)}).join("")}function nP(e){const t=e.match(ZM);return t?t[1].replace(eP,"'"):e}const{useToken:rP}=he,{Text:Ua}=le,oP=({images:e,className:t,style:s,maxHeight:n={single:400,multiple:200}})=>{const{token:o}=rP(),{t:a}=ne();return!e||e.length===0?null:r.jsx(ee,{className:t,style:{marginBottom:o.marginMD,...s},styles:{body:{padding:0}},variant:"borderless",children:r.jsx(G,{wrap:"wrap",gap:o.marginSM,style:{width:"100%"},children:e.map(i=>r.jsxs(ee,{size:"small",style:{flex:e.length===1?"1 1 100%":"1 1 200px",overflow:"hidden",borderRadius:o.borderRadius,border:`1px solid ${o.colorBorderSecondary}`,backgroundColor:o.colorBgLayout},styles:{body:{padding:0}},children:[r.jsxs("div",{style:{position:"relative"},children:[r.jsx(Cx,{src:i.url||i.base64,alt:i.name,style:{width:"100%",height:"auto",maxHeight:e.length===1?n.single:n.multiple,objectFit:"cover"},preview:{mask:r.jsxs(G,{align:"center",justify:"center",gap:o.marginXS,style:{color:o.colorTextLightSolid},children:[r.jsx(td,{}),r.jsx(Ua,{style:{color:o.colorTextLightSolid},children:a("components.imageGrid.preview")})]})}}),r.jsxs(G,{vertical:!0,style:{position:"absolute",bottom:0,left:0,right:0,background:"linear-gradient(transparent, rgba(0,0,0,0.7))",color:o.colorTextLightSolid,padding:`${o.paddingXS}px ${o.paddingSM}px`,fontSize:o.fontSizeSM},children:[r.jsx(Ua,{style:{color:o.colorTextLightSolid},strong:!0,children:i.name}),i.size&&r.jsxs(Ua,{style:{fontSize:o.fontSizeSM*.85,opacity:.8,color:o.colorTextLightSolid},children:[(i.size/1024).toFixed(1)," KB",i.width&&i.height&&` • ${i.width}×${i.height}`]})]})]}),(i.ocrText||i.ocrError)&&r.jsx("div",{style:{padding:o.paddingSM},children:r.jsx(ns,{ghost:!0,size:"small",items:[{key:"ocr",label:a("components.imageGrid.ocr"),children:r.jsxs(r.Fragment,{children:[i.ocrError&&r.jsx(Ua,{type:"danger",children:i.ocrError}),i.ocrText&&r.jsx(le.Paragraph,{style:{marginTop:i.ocrError?o.marginXS:0,marginBottom:0,whiteSpace:"pre-wrap"},children:i.ocrText})]})}]})})]},i.id))})})},{useToken:aP}=he,{useBreakpoint:iP}=$i,lP=({buttons:e,isVisible:t,className:s,style:n,position:o={bottom:"8px",right:"8px"}})=>{const{token:a}=aP(),i=iP(),l=()=>(i.xs,"small");return r.jsx(G,{justify:"flex-end",gap:a.marginXS,className:s,style:{marginTop:a.marginXS,position:"absolute",bottom:o.bottom,right:o.right,top:o.top,left:o.left,background:"transparent",zIndex:1,opacity:t?1:0,transition:"opacity 0.2s ease",pointerEvents:t?"auto":"none",...n},children:e.map(c=>r.jsx(ke,{title:c.title,children:r.jsx(Y,{"data-testid":c["data-testid"]||c.key,icon:c.icon,size:l(),type:"text",onClick:c.onClick,disabled:c.disabled,style:{background:a.colorBgElevated,borderRadius:a.borderRadiusSM}})},c.key))})},cP=(e,t)=>({key:"copy","data-testid":"copy-message",icon:r.jsx(ss,{}),title:t||"Copy message",onClick:e}),dP=(e,t)=>({key:"reference",icon:r.jsx(Sf,{}),title:t||"Reference message",onClick:e}),{Title:Ah,Text:Yt,Paragraph:Ih}=le,{useToken:uP}=he,mP=({plan:e,contextId:t,onExecute:s,onRefine:n,timestamp:o})=>{const{t:a}=ne(),{token:i}=uP(),[l,c]=m.useState(!1),[d,u]=m.useState(""),h=()=>{d.trim()&&(n(d),u(""),c(!1))};return r.jsxs(ee,{style:{marginBottom:i.marginMD,borderColor:i.colorPrimary,borderWidth:2,backgroundColor:i.colorPrimaryBg},title:r.jsxs(X,{children:[r.jsx(Hs,{style:{color:i.colorPrimary}}),r.jsx(Yt,{strong:!0,style:{color:i.colorPrimary},children:a("components.plan.executionPlan")})]}),extra:o?r.jsx(Yt,{type:"secondary",style:{fontSize:i.fontSizeSM},children:o}):void 0,children:[r.jsxs(G,{vertical:!0,style:{marginBottom:i.marginLG},children:[r.jsx(Ah,{level:5,style:{marginBottom:i.marginXS},children:a("components.plan.goal")}),r.jsx(Ih,{style:{fontSize:15,marginBottom:0},children:e.goal})]}),r.jsxs(G,{vertical:!0,style:{marginBottom:i.marginLG},children:[r.jsx(Ah,{level:5,style:{marginBottom:i.marginMD},children:a("components.plan.steps")}),r.jsx(Mx,{direction:"vertical",current:-1,items:e.steps.map(p=>({title:r.jsxs(Yt,{strong:!0,children:[a("components.plan.stepTitle",{number:p.step_number}),": ",p.action]}),description:r.jsxs(G,{vertical:!0,children:[r.jsxs(Ih,{style:{marginBottom:i.marginXS},children:[r.jsxs(Yt,{type:"secondary",children:[a("components.plan.reason"),":"]})," ",p.reason]}),r.jsxs(X,{wrap:!0,children:[r.jsxs(Yt,{type:"secondary",children:[r.jsx(Sr,{})," ",a("components.plan.tools"),":"]}),p.tools_needed.map((g,y)=>r.jsx(oe,{color:"processing",children:g},y))]}),r.jsx(G,{style:{marginTop:i.marginXS},children:r.jsxs(Yt,{type:"secondary",children:[r.jsx(Ys,{})," ",a("components.plan.estimated"),": ",p.estimated_time]})})]}),icon:r.jsx(Yt,{children:p.step_number})}))})]}),r.jsxs(X,{direction:"vertical",style:{width:"100%",marginBottom:i.marginLG},children:[r.jsxs(G,{align:"center",gap:i.marginXS,wrap:"wrap",children:[r.jsxs(Yt,{type:"secondary",children:[r.jsx(Ys,{})," ",a("components.plan.totalEstimatedTime")," "]}),r.jsx(oe,{color:"processing",children:e.estimated_total_time})]}),e.prerequisites&&e.prerequisites.length>0&&r.jsxs(G,{vertical:!0,children:[r.jsxs(Yt,{type:"secondary",children:[a("components.plan.prerequisites"),":"]}),r.jsx(nt,{size:"small",dataSource:e.prerequisites,renderItem:(p,g)=>r.jsx(nt.Item,{style:{padding:0},children:r.jsx(Yt,{children:p})},`${p}-${g}`)})]})]}),e.risks&&e.risks.length>0&&r.jsx(ns,{ghost:!0,style:{marginBottom:i.marginLG},items:[{key:"risks",label:r.jsxs(X,{children:[r.jsx(ua,{style:{color:i.colorWarning}}),r.jsx(Yt,{strong:!0,children:a("components.plan.potentialRisks",{count:e.risks.length})})]}),children:r.jsx(nt,{size:"small",dataSource:e.risks,renderItem:(p,g)=>r.jsx(nt.Item,{style:{padding:0},children:r.jsx(Yt,{children:p})},`${p}-${g}`)})}]}),r.jsx(X,{style:{width:"100%",justifyContent:"flex-end"},children:l?r.jsxs(r.Fragment,{children:[r.jsx(Y,{onClick:()=>c(!1),children:a("common.cancel")}),r.jsx(Y,{type:"primary",onClick:h,disabled:!d.trim(),children:a("components.plan.sendFeedback")})]}):r.jsxs(r.Fragment,{children:[r.jsx(Y,{onClick:()=>c(!0),children:a("components.plan.refinePlan")}),r.jsx(Y,{type:"primary",icon:r.jsx(wf,{}),onClick:s,children:a("components.plan.executePlan")})]})}),l&&r.jsx(G,{vertical:!0,style:{marginTop:i.marginMD},children:r.jsx(me.TextArea,{value:d,onChange:p=>u(p.target.value),placeholder:a("components.plan.feedbackPlaceholder"),autoSize:{minRows:4,maxRows:10}})})]})},Jy=m.memo(mP);Jy.displayName="PlanMessageCard";const{Title:hP,Text:ar,Paragraph:pP}=le,{useToken:fP}=he,gP=({question:e,contextId:t,onAnswer:s,disabled:n=!1,timestamp:o})=>{const{t:a}=ne(),{token:i}=fP(),[l,c]=m.useState(e.default),[d,u]=m.useState(!1),h=async()=>{if(l){u(!0);try{await s(l)}catch(f){console.error("Failed to submit answer:",f)}finally{u(!1)}}},p=()=>{switch(e.severity){case"critical":return r.jsx(Oi,{style:{color:i.colorError}});case"major":return r.jsx(ua,{style:{color:i.colorWarning}});case"minor":return r.jsx(At,{style:{color:i.colorInfo}});default:return r.jsx(nd,{style:{color:i.colorPrimary}})}},g=()=>{switch(e.severity){case"critical":return i.colorErrorBg;case"major":return i.colorWarningBg;case"minor":return i.colorInfoBg;default:return i.colorPrimaryBg}},y=()=>{switch(e.severity){case"critical":return i.colorError;case"major":return i.colorWarning;case"minor":return i.colorInfo;default:return i.colorPrimary}};return r.jsxs(ee,{style:{marginBottom:i.marginMD,borderColor:y(),borderWidth:2,backgroundColor:g()},title:r.jsxs(X,{children:[p(),r.jsx(ar,{strong:!0,style:{color:y()},children:a("components.question.agentQuestion")}),r.jsxs(ar,{type:"secondary",style:{fontSize:12},children:["(",e.severity,")"]})]}),extra:o?r.jsx(ar,{type:"secondary",style:{fontSize:i.fontSizeSM},children:o}):void 0,children:[r.jsx(G,{vertical:!0,style:{marginBottom:i.marginLG},children:r.jsx(hP,{level:5,style:{marginBottom:i.marginXS},children:e.question})}),e.context&&r.jsx(Xe,{message:a("components.question.context"),description:e.context,type:"info",showIcon:!0,style:{marginBottom:i.marginLG}}),r.jsxs(G,{vertical:!0,style:{marginBottom:i.marginLG},children:[r.jsx(ar,{strong:!0,style:{display:"block",marginBottom:i.marginSM},children:a("components.question.chooseOption")}),r.jsx(ts.Group,{value:l,onChange:f=>c(f.target.value),disabled:n||d,style:{width:"100%"},children:r.jsx(X,{direction:"vertical",style:{width:"100%"},children:e.options.map(f=>r.jsx(ee,{size:"small",hoverable:!n&&!d,style:{borderColor:l===f.value?i.colorPrimary:i.colorBorder,backgroundColor:l===f.value?i.colorPrimaryBg:i.colorBgContainer,cursor:n||d?"not-allowed":"pointer"},onClick:()=>!n&&!d&&c(f.value),children:r.jsx(ts,{value:f.value,style:{width:"100%"},children:r.jsxs(G,{vertical:!0,children:[r.jsxs(G,{align:"center",gap:i.marginXS,wrap:"wrap",children:[r.jsx(ar,{strong:!0,children:f.label}),f.value===e.default&&r.jsx(oe,{color:"processing",style:{marginLeft:i.marginXS},children:a("components.question.recommended")})]}),r.jsx(pP,{type:"secondary",style:{marginTop:i.marginXXS,marginBottom:0},children:f.description})]})})},f.value))})})]}),e.allow_custom&&r.jsxs(G,{vertical:!0,style:{marginBottom:i.marginMD},children:[r.jsx(ar,{type:"secondary",style:{fontSize:12},children:a("components.question.customAnswerHint")}),r.jsx(me.TextArea,{value:l&&!e.options.find(f=>f.value===l)?l:"",onChange:f=>c(f.target.value),placeholder:a("components.question.customAnswerPlaceholder"),disabled:n||d,autoSize:{minRows:3,maxRows:8},style:{marginTop:i.marginXS}})]}),r.jsx(G,{justify:"flex-end",children:r.jsx(Y,{type:"primary",icon:r.jsx(Hs,{}),onClick:h,loading:d,disabled:n||!l,children:a("components.question.submitAnswer")})})]})},Qy=m.memo(gP);Qy.displayName="QuestionMessageCard";const{Text:$h}=le,yP=({paths:e,displayText:t})=>{const{token:s}=he.useToken(),n=t.replace(/@[^\s]+/g,"").trim();return r.jsxs(ee,{size:"small",styles:{body:{padding:`${s.paddingSM}px ${s.paddingMD}px`}},style:{maxWidth:"100%"},children:[r.jsx(X,{direction:"vertical",size:s.marginXXS,children:e.map((o,a)=>{const i=o.split("/").pop()||o,l=o.substring(0,o.lastIndexOf("/"))||"",c=!i.includes(".");return r.jsxs(G,{vertical:!0,children:[r.jsxs(X,{size:s.marginXS,align:"center",wrap:!0,children:[c?r.jsx(hi,{style:{color:s.colorWarning,fontSize:s.fontSizeLG}}):r.jsx(br,{style:{color:s.colorPrimary,fontSize:s.fontSizeLG}}),r.jsx(oe,{color:c?"warning":"processing",style:{margin:0,fontFamily:s.fontFamilyCode,fontSize:s.fontSize},children:i})]}),l&&r.jsx(ke,{title:o,children:r.jsxs(X,{size:4,align:"center",style:{marginTop:4},children:[r.jsx(hi,{style:{color:s.colorTextTertiary,fontSize:s.fontSizeSM}}),r.jsx($h,{type:"secondary",style:{fontSize:s.fontSizeSM,fontFamily:s.fontFamilyCode,maxWidth:"400px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},copyable:{text:o},children:l})]})})]},a)})}),n&&r.jsx($h,{style:{fontSize:s.fontSize,color:s.colorText,marginTop:s.marginXS,paddingTop:s.marginXS,borderTop:`1px solid ${s.colorBorderSecondary}`},children:n})]})},Zy=m.memo(yP);Zy.displayName="FileReferenceCard";const bP=({taskList:e})=>{const{token:t}=he.useToken(),{Text:s}=le,n=l=>{switch(l){case"pending":return r.jsx(oe,{icon:r.jsx(Ys,{}),color:"default",children:"Pending"});case"in_progress":return r.jsx(oe,{icon:r.jsx(gr,{spin:!0}),color:"processing",children:"In Progress"});case"completed":return r.jsx(oe,{icon:r.jsx(Hs,{}),color:"success",children:"Completed"});case"skipped":return r.jsx(oe,{icon:r.jsx(nc,{}),color:"default",children:"Skipped"});case"failed":return r.jsx(oe,{icon:r.jsx(rc,{}),color:"error",children:"Failed"});default:return null}},o=()=>{switch(e.status){case"active":return r.jsx(oe,{color:"processing",children:"Active"});case"completed":return r.jsx(oe,{color:"success",children:"Completed"});case"abandoned":return r.jsx(oe,{color:"error",children:"Abandoned"});default:return null}},a=ut.useMemo(()=>{if(e.items.length===0)return 0;const l=e.items.filter(c=>c.status==="completed").length;return Math.round(l/e.items.length*100)},[e.items]),i=ut.useMemo(()=>e.items.find(l=>l.status==="in_progress"),[e.items]);return r.jsx(ee,{size:"small",styles:{body:{padding:t.paddingSM}},style:{borderRadius:t.borderRadiusLG},children:r.jsxs(G,{vertical:!0,gap:t.marginSM,children:[r.jsxs(G,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[r.jsxs(X,{direction:"vertical",size:2,children:[r.jsx(s,{strong:!0,children:e.title}),e.description?r.jsx(s,{type:"secondary",children:e.description}):null]}),o()]}),r.jsxs(X,{direction:"vertical",size:4,children:[r.jsx(id,{percent:a,status:e.status==="completed"?"success":e.status==="abandoned"?"exception":"active",showInfo:!0}),r.jsxs(s,{type:"secondary",children:[a,"% Complete"]})]}),r.jsx(nt,{size:"small",dataSource:e.items,renderItem:l=>{var d;const c=(i==null?void 0:i.id)===l.id;return r.jsx(nt.Item,{style:{borderRadius:t.borderRadius,padding:t.paddingXS,background:c?t.colorPrimaryBg:"transparent",border:"1px solid",borderColor:c?t.colorPrimaryBorder:t.colorBorderSecondary},children:r.jsxs(G,{vertical:!0,style:{width:"100%"},gap:4,children:[r.jsxs(G,{align:"center",justify:"space-between",wrap:"wrap",gap:8,children:[r.jsx(s,{children:l.description}),n(l.status)]}),l.status==="failed"&&((d=l.metadata)!=null&&d.error)?r.jsx(s,{type:"danger",style:{fontSize:12},children:l.metadata.error}):null]})})}}),r.jsxs(G,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[r.jsxs(s,{type:"secondary",style:{fontSize:12},children:[e.items.filter(l=>l.status==="completed").length," /"," ",e.items.length," tasks completed"]}),i?r.jsxs(s,{type:"secondary",style:{fontSize:12},children:["Current: ",i.description]}):null]})]})})},xP=100,kn=new Set;function vP(e){if(kn.has(e)&&kn.delete(e),kn.add(e),kn.size>xP){const t=kn.values().next().value;t&&kn.delete(t)}}function SP(e){let t=2166136261;for(let s=0;s<e.length;s++)t=(t^e.charCodeAt(s))*16777619;return(t>>>0).toString(36)}const wP=e=>{const{t}=ne(),s=SP(e.chart),[n,o]=m.useState(()=>kn.has(s)),a=m.useRef(null);return m.useEffect(()=>{if(n)return;const i=a.current;if(!i)return;const l=new IntersectionObserver(c=>{c.some(d=>d.isIntersecting)&&(vP(s),o(!0),l.disconnect())},{rootMargin:"50px",threshold:.01});return l.observe(i),()=>l.disconnect()},[n,s]),r.jsx("div",{ref:a,style:{minHeight:n?"auto":"200px"},children:n?r.jsx(ut.Suspense,{fallback:r.jsx(ps,{size:"small",tip:t("components.mermaid.loadingDiagram")}),children:r.jsx(_P,{...e})}):r.jsx("div",{style:{minHeight:"200px"}})})},_P=e=>{const{t}=ne(),[s,n]=m.useState(null);return m.useEffect(()=>{let o=!1;return Dt(()=>Promise.resolve().then(()=>GE),void 0,import.meta.url).then(a=>{o||n(()=>a.MermaidChart)}),()=>{o=!0}},[]),s?r.jsx(s,{...e}):r.jsx(ps,{size:"small",tip:t("components.mermaid.loadingDiagram")})},TP=ut.memo(wP),kP=({error:e,className:t,style:s,token:n,onFix:o,isFixing:a,fixError:i})=>{const{t:l}=ne(),c=e.split(`
|
|
@@ -218,7 +218,7 @@ ${o}`:`${n}
|
|
|
218
218
|
${t}`},o1=(e,t)=>{const s=t1[e];if(!s)return null;const n=t.trim();if(!n)return"";if(e==="mermaid")return n;const o=n1(n);return s1.test(o)?n:r1(n,s)},yb=(e,t,s,n,o="lazy")=>{try{if(!t||typeof t!="string")return console.warn("Invalid codeString provided to renderCodeBlock:",t),null;const a=e.toLowerCase().trim(),i=o1(a,t);if(i!==null){const l=i.trim();return l?o==="eager"?r.jsx(Ri,{chart:l,onFix:n}):r.jsx(TP,{chart:l,onFix:n}):(console.warn("Empty Mermaid chart content"),null)}return r.jsx(ZE,{language:a,codeString:t,token:s})}catch(a){return console.warn("Syntax highlighting failed:",a),r.jsx(e1,{codeString:t,token:s})}},Uh=(e,t)=>{if(typeof window>"u")return;const s=window.open(e,"_blank","noopener,noreferrer");if(s){s.opener=null;return}((t==null?void 0:t.allowLocationFallback)??!0)&&window.location.assign(e)},bb=async e=>{const t=e.trim();if(!t)return;if(pb()){const n=window.__TAURI_INTERNALS__,o=n==null?void 0:n.invoke;if(typeof o=="function")try{await o("plugin:shell|open",{path:t});return}catch(a){console.warn("[openExternalLink] Failed to open via Tauri shell plugin, falling back to browser open.",a)}Uh(t,{allowLocationFallback:!1});return}Uh(t)},{Text:qh}=le,xb=(e,t)=>({p:({children:s})=>r.jsx(qh,{style:{marginBottom:e.marginSM,display:"block"},children:s}),ol:({children:s})=>r.jsx("ol",{style:{marginBottom:e.marginSM,paddingLeft:20},children:s}),ul:({children:s})=>r.jsx("ul",{style:{marginBottom:e.marginSM,paddingLeft:20},children:s}),li:({children:s})=>r.jsx("li",{style:{marginBottom:e.marginXS},children:s}),code({className:s,children:n,inline:o,...a}){const i=/language-([^\s]+)/i.exec(s||""),l=i?i[1]:"",c=o??(!i&&!s),d=n?String(n).replace(/\n$/,""):"";return c?r.jsx(qh,{code:!0,className:s,...a,children:n}):d.trim()?yb(l,d,e,t==null?void 0:t.onFixMermaid,t==null?void 0:t.mermaidRenderMode):null},blockquote:({children:s})=>r.jsx(ee,{size:"small",styles:{body:{padding:`${e.paddingXS}px ${e.padding}px`}},style:{borderLeft:`3px solid ${e.colorPrimary}`,background:e.colorPrimaryBg,margin:`${e.marginXS}px 0`,color:e.colorTextSecondary,fontStyle:"italic"},children:s}),a:({children:s,href:n})=>{const o=typeof n=="string"?n.trim():"";return o?r.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer",onClick:a=>{a.preventDefault(),a.stopPropagation(),bb(o)},style:{color:e.colorLink,textDecoration:"underline",overflowWrap:"anywhere"},children:s}):r.jsx(r.Fragment,{children:s})},table:({children:s})=>r.jsx(ee,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${e.marginSM}px 0`},children:r.jsx("table",{style:{width:"100%",borderCollapse:"collapse",border:`1px solid ${e.colorBorder}`},children:s})}),thead:({children:s})=>r.jsx("thead",{style:{backgroundColor:e.colorFillTertiary,color:e.colorText},children:s}),tbody:({children:s})=>r.jsx("tbody",{children:s}),tr:({children:s})=>r.jsx("tr",{style:{borderBottom:`1px solid ${e.colorBorder}`},children:s}),th:({children:s})=>r.jsx("th",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,textAlign:"left",fontWeight:"bold",borderRight:`1px solid ${e.colorBorder}`},children:s}),td:({children:s})=>r.jsx("td",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,borderRight:`1px solid ${e.colorBorder}`},children:s}),input:({type:s,checked:n,disabled:o})=>s==="checkbox"?r.jsx("input",{type:"checkbox",checked:n,disabled:o,style:{marginRight:e.marginXS,accentColor:e.colorPrimary},readOnly:!0}):r.jsx("input",{type:s,checked:n,disabled:o})}),{Text:Fe}=le,Hh=e=>{if(!e)return;const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},a1=({content:e,toolName:t,status:s="success",timestamp:n,defaultCollapsed:o=!0,isLoading:a,errorMessage:i})=>{var b;const{t:l}=ne(),{token:c}=he.useToken(),d=m.useMemo(()=>Oc(e),[e]),u=m.useMemo(()=>typeof a=="boolean"?a:d.formattedText.trim().length===0,[d.formattedText,a]),h=m.useMemo(()=>D0(d.formattedText),[d.formattedText]),p=m.useMemo(()=>wa(e),[e]),g=m.useMemo(()=>Ay(e),[e]),y=m.useMemo(()=>p?Iy(p.diff.unified):[],[p]),f=async()=>{try{const x=d.isJson?xr(d.parsedJson):d.formattedText;await os(x)}catch(x){console.error("[ToolResultCard] Failed to copy result:",x)}},v=m.useMemo(()=>{const x=e?e.slice(0,50).replace(/[^a-zA-Z0-9]/g,""):"empty";return`tool-result-${t}-${x}`},[t,e]);return r.jsx(ns,{defaultActiveKey:o?[]:[v],style:{backgroundColor:c.colorBgContainer,borderColor:c.colorBorderSecondary,borderWidth:1,borderStyle:"solid",borderRadius:c.borderRadiusLG},items:[{key:v,label:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:c.marginSM,width:"100%"},children:[r.jsx(ad,{style:{color:c.colorPrimary,flexShrink:0}}),r.jsx(Fe,{strong:!0,style:{color:c.colorText,flexShrink:0},children:t}),r.jsx(Fe,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:c.fontSizeSM},children:u?l("components.toolResult.waiting"):h}),r.jsx(oe,{color:$y(s),style:{flexShrink:0,margin:0},children:s})]}),children:r.jsxs(X,{direction:"vertical",style:{width:"100%"},size:c.marginSM,children:[n&&r.jsx(Fe,{type:"secondary",style:{fontSize:c.fontSizeSM},children:new Date(n).toLocaleString()}),i&&r.jsx(Xe,{type:"error",message:l("components.toolResult.executionFailed"),description:i,showIcon:!0}),r.jsxs("div",{style:{position:"relative"},children:[r.jsx(ke,{title:l("components.toolResult.copyResult"),children:r.jsx(Y,{type:"text",size:"small",icon:r.jsx(ss,{}),"aria-label":l("components.toolResult.copyResult"),onClick:x=>{x.stopPropagation(),f()},style:{position:"absolute",top:8,right:8,zIndex:1}})}),u?r.jsx(Fe,{type:"secondary",children:l("components.toolResult.waitingForResult")}):g?r.jsxs(X,{direction:"vertical",style:{width:"100%"},size:10,children:[r.jsxs(X,{wrap:!0,children:[r.jsx(oe,{color:g.action==="rebuild"?"gold":"blue",children:l(`components.toolResult.memory.action.${g.action}`)}),r.jsx(oe,{children:g.data.scope}),g.data.project_key?r.jsx(oe,{children:g.data.project_key}):null,r.jsx(oe,{color:"green",children:l("components.toolResult.memory.totalMemories",{count:g.data.total_memories})}),r.jsx(oe,{color:g.data.stale_candidate_count>0?"orange":"default",children:l("components.toolResult.memory.staleCandidates",{count:g.data.stale_candidate_count})})]}),r.jsxs("div",{children:[r.jsx(Fe,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.coverage")}),r.jsxs("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:[Object.entries(g.data.by_type).map(([x,_])=>r.jsx(oe,{children:`${x}: ${_}`},`type-${x}`)),Object.entries(g.data.by_status).map(([x,_])=>r.jsx(oe,{color:"processing",children:`${x}: ${_}`},`status-${x}`))]})]}),r.jsx(Rt,{style:{margin:`${c.marginXS}px 0`}}),r.jsxs("div",{style:{display:"grid",gap:c.marginXS},children:[r.jsxs(Fe,{style:{fontSize:c.fontSizeSM},children:[r.jsx(Fe,{strong:!0,children:l("components.toolResult.memory.viewsLabel")})," ",g.data.view_files.length]}),r.jsxs(Fe,{style:{fontSize:c.fontSizeSM},children:[r.jsx(Fe,{strong:!0,children:l("components.toolResult.memory.indexesLabel")})," ",g.data.index_files.length]}),r.jsxs(Fe,{style:{fontSize:c.fontSizeSM},children:[r.jsx(Fe,{strong:!0,children:l("components.toolResult.memory.stateFilesLabel")})," ",g.data.state_files.length]}),g.data.last_reindex_at?r.jsxs(Fe,{style:{fontSize:c.fontSizeSM},children:[r.jsx(Fe,{strong:!0,children:l("components.toolResult.memory.lastReindexLabel")})," ",Hh(g.data.last_reindex_at)]}):null,g.data.last_dream_at?r.jsxs(Fe,{style:{fontSize:c.fontSizeSM},children:[r.jsx(Fe,{strong:!0,children:l("components.toolResult.memory.lastDreamLabel")})," ",Hh(g.data.last_dream_at)]}):null]}),g.data.view_files.length>0?r.jsxs("div",{children:[r.jsx(Fe,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.viewFiles")}),r.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:g.data.view_files.map(x=>r.jsx(oe,{children:x},`view-${x}`))})]}):null,g.data.index_files.length>0?r.jsxs("div",{children:[r.jsx(Fe,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.indexFiles")}),r.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:g.data.index_files.map(x=>r.jsx(oe,{children:x},`index-${x}`))})]}):null,g.data.state_files.length>0?r.jsxs("div",{children:[r.jsx(Fe,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.stateFiles")}),r.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:g.data.state_files.map(x=>r.jsx(oe,{children:x},`state-${x}`))})]}):null,g.data.topic_paths.length>0?r.jsxs("div",{children:[r.jsx(Fe,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.topicPaths")}),r.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:g.data.topic_paths.map(x=>r.jsx(oe,{children:x},`topic-${x}`))})]}):null,g.data.recent_ids.length>0?r.jsxs("div",{children:[r.jsx(Fe,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.recentMemories")}),r.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:g.data.recent_ids.map(x=>r.jsx(oe,{color:"default",children:x},`recent-${x}`))})]}):null]}):p?r.jsxs(X,{direction:"vertical",style:{width:"100%"},size:8,children:[p.message&&r.jsx(Fe,{style:{fontSize:c.fontSizeSM},children:p.message}),r.jsxs(Fe,{style:{fontSize:c.fontSizeSM},children:[r.jsxs(Fe,{strong:!0,children:[l("common.file"),":"]})," ",r.jsx(Fe,{code:!0,children:p.file_path})]}),p.workspace&&r.jsxs(Fe,{style:{fontSize:c.fontSizeSM},children:[r.jsxs(Fe,{strong:!0,children:[l("common.workspace"),":"]})," ",r.jsx(Fe,{code:!0,children:p.workspace})]}),(b=p.checkpoint)!=null&&b.created?r.jsxs(Fe,{style:{fontSize:c.fontSizeSM},children:[r.jsxs(Fe,{strong:!0,children:[l("components.toolResult.checkpoint"),":"]})," ",r.jsx(Fe,{code:!0,children:p.checkpoint.path})]}):r.jsx(Fe,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l("components.toolResult.checkpointNone")}),r.jsx("div",{style:{border:`1px solid ${c.colorBorderSecondary}`,borderRadius:c.borderRadiusSM,maxHeight:400,overflow:"auto",background:c.colorBgContainer},children:y.map((x,_)=>{const w={margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:c.fontSizeSM,lineHeight:1.5,padding:"0 8px",fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace"};return x.kind==="add"?w.background=c.colorSuccessBg:x.kind==="remove"?w.background=c.colorErrorBg:x.kind==="modified_add"?(w.background=c.colorWarningBg,w.borderLeft=`3px solid ${c.colorSuccess}`):x.kind==="modified_remove"?(w.background=c.colorWarningBg,w.borderLeft=`3px solid ${c.colorError}`):x.kind==="hunk"?(w.background=c.colorFillSecondary,w.color=c.colorTextSecondary):x.kind==="meta"&&(w.background=c.colorFillTertiary,w.color=c.colorTextSecondary),r.jsx("pre",{style:w,children:x.text||" "},`${_}-${x.kind}`)})}),p.diff.truncated&&r.jsx(Fe,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l("components.toolResult.diffTruncated")})]}):d.isJson?r.jsx(fr,{language:"json",style:Un,wrapLongLines:!0,customStyle:{margin:0,borderRadius:c.borderRadiusSM,backgroundColor:c.colorBgContainer,fontSize:c.fontSizeSM,maxHeight:400,overflow:"auto"},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"}},children:d.formattedText}):r.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:c.fontSizeSM,backgroundColor:c.colorBgContainer,padding:c.paddingSM,borderRadius:c.borderRadiusSM,margin:0,maxHeight:400,overflow:"auto"},children:d.formattedText})]})]})}]})},eu=m.memo(a1);eu.displayName="ToolResultCard";const{Text:ws}=le;function i1(e,t){const s=Yn(e);if(s)return`MCP ${s.serverId}: ${s.toolName}`;const n=(i,l)=>{const c=typeof i=="string"?i:String(i??"");return!c||c.length<=l?c:c.substring(0,l).trimEnd()+"…"},o={file_read:i=>`Reading: ${n(i.path||i.file_path||"file",40)}`,file_write:i=>`Writing to: ${n(i.path||i.file_path||"file",35)}`,file_edit:i=>`Editing: ${n(i.path||i.file_path||"file",40)}`,bash:i=>`Executing: ${n(i.command,40)}`,grep:i=>`Searching: "${n(i.pattern,30)}"`,glob:i=>`Finding files: "${i.pattern}"`,conclusion:i=>`Presenting conclusion: "${n(i.conclusion||i.title||"",30)}"`,read:i=>`Reading: ${i.file_path||"file"}`,write:i=>`Writing: ${i.file_path||"file"}`,edit:i=>`Editing: ${i.file_path||"file"}`,search:i=>`Searching: "${n(i.query||i.pattern,30)}"`,default:()=>`Calling ${e}`};return(o[e]||o.default)(t)}const l1=({toolName:e,parameters:t,toolCallId:s,streamingOutput:n,defaultExpanded:o=!1,metadata:a})=>{const{t:i}=ne(),{token:l}=he.useToken(),c=m.useMemo(()=>Yn(e),[e]),[d,u]=m.useState(o?[s]:[]),h=m.useRef(!1),p=m.useRef(null);m.useEffect(()=>{h.current||!n||n.trim().length===0||(u(b=>b.includes(s)?b:[s]),h.current=!0)},[n,s]),m.useEffect(()=>{if(!n||n.trim().length===0||!d.includes(s))return;const b=p.current;b&&(b.scrollTop=b.scrollHeight)},[n,d,s]);const g=m.useMemo(()=>i1(e,t),[e,t]),y=m.useMemo(()=>xr(t,2),[t]),f=async()=>{try{await os(y)}catch(b){console.error("[ToolCallCard] Failed to copy parameters:",b)}},v=m.useMemo(()=>{const b=["path","file_path","command","pattern","query","limit"];return Object.entries(t).sort((w,k)=>{const C=b.indexOf(w[0]),E=b.indexOf(k[0]);return C!==-1&&E!==-1?C-E:C!==-1?-1:E!==-1?1:0}).slice(0,3)},[t]);return r.jsx(ns,{activeKey:d,onChange:b=>{const x=Array.isArray(b)?b.map(String):b==null?[]:[String(b)];u(x),x.includes(s)&&(h.current=!0)},style:{background:"var(--lotus-tool-card-bg)",borderColor:"var(--lotus-tool-card-border)",borderWidth:1,borderStyle:"solid",borderRadius:l.borderRadiusLG,boxShadow:"var(--lotus-tool-card-shadow)",transition:"all 0.3s ease",overflow:"hidden"},className:"tool-call-card-collapse",items:[{key:s,label:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:l.marginSM,width:"100%"},children:[r.jsx("div",{style:{width:34,height:34,borderRadius:12,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,background:"var(--lotus-tool-badge-bg)",border:"var(--lotus-tool-badge-border)",boxShadow:"var(--lotus-tool-badge-shadow)"},children:r.jsx(Sr,{style:{color:l.colorPrimary,flexShrink:0}})}),c?r.jsxs(X,{size:"small",wrap:!1,children:[r.jsx(oe,{color:"purple",style:{marginInlineEnd:0,borderRadius:999,paddingInline:8,fontWeight:700,boxShadow:"var(--lotus-purple-shadow)"},children:"MCP"}),r.jsx(ws,{strong:!0,style:{color:l.colorText},children:c.toolName}),r.jsx(ws,{type:"secondary",style:{fontSize:l.fontSizeSM},children:r.jsx(ws,{code:!0,style:{fontSize:l.fontSizeSM},children:c.serverId})})]}):r.jsx(ws,{strong:!0,style:{color:l.colorText,flexShrink:0},children:e}),r.jsx(ws,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:l.fontSizeSM},children:g}),(a==null?void 0:a.elapsed_ms)!=null&&r.jsx(ke,{title:a.is_mutating?"Mutating tool":"Read-only tool",children:r.jsx(oe,{color:a.is_mutating?"orange":"green",style:{marginInlineEnd:0,borderRadius:999,paddingInline:6,fontSize:l.fontSizeSM-1,lineHeight:"18px",flexShrink:0},children:a.elapsed_ms<1e3?`${a.elapsed_ms}ms`:`${(a.elapsed_ms/1e3).toFixed(1)}s`})})]}),children:r.jsxs(X,{direction:"vertical",style:{width:"100%"},size:l.marginSM,children:[n&&n.trim().length>0&&r.jsxs("div",{children:[r.jsx(ws,{strong:!0,style:{fontSize:l.fontSizeSM},children:i("components.toolCall.liveOutput")}),r.jsx("div",{ref:p,className:"lotus-code-surface",style:{marginTop:l.marginXS,borderRadius:l.borderRadiusSM,backgroundColor:l.colorBgContainer,maxHeight:240,overflow:"auto"},children:r.jsx(fr,{language:"text",style:Un,wrapLongLines:!0,customStyle:{margin:0,backgroundColor:"transparent",fontSize:l.fontSizeSM},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"}},children:n})})]}),v.length>0&&r.jsxs("div",{children:[r.jsx(ws,{strong:!0,style:{fontSize:l.fontSizeSM,marginBottom:l.marginXS,display:"block"},children:i("components.toolCall.keyParameters")}),r.jsx("ul",{style:{margin:0,paddingLeft:l.paddingLG,fontSize:l.fontSizeSM},children:v.map(([b,x])=>r.jsxs("li",{children:[r.jsx(ws,{code:!0,style:{fontSize:l.fontSizeSM},children:b}),r.jsxs(ws,{style:{fontSize:l.fontSizeSM},children:[": ",typeof x=="string"?x:JSON.stringify(x)]})]},b))})]}),r.jsxs("div",{children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:l.marginXS},children:[r.jsx(ws,{strong:!0,style:{fontSize:l.fontSizeSM},children:i("components.toolCall.fullParameters")}),r.jsx(ke,{title:i("components.toolCall.copyParameters"),children:r.jsx(Y,{type:"text",size:"small",icon:r.jsx(ss,{}),"aria-label":i("components.toolCall.copyParameters"),onClick:b=>{b.stopPropagation(),f()}})})]}),r.jsx(fr,{language:"json",style:Un,wrapLongLines:!0,customStyle:{margin:0,borderRadius:l.borderRadiusSM,backgroundColor:l.colorBgContainer,fontSize:l.fontSizeSM,maxHeight:400,overflow:"auto"},className:"lotus-code-surface",codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"}},children:y})]})]})}]})},tu=m.memo(l1);tu.displayName="ToolCallCard";const{Text:Ll}=le,c1=({content:e,workflowName:t,parameters:s,status:n="success",timestamp:o,onRetry:a,isLoading:i,errorMessage:l})=>{const{t:c}=ne(),{token:d}=he.useToken(),[u,h]=m.useState(!1),p=m.useMemo(()=>Oc(e),[e]),g=m.useMemo(()=>typeof i=="boolean"?i:p.formattedText.trim().length===0,[p.formattedText,i]),y=m.useMemo(()=>I0(p.formattedText),[p.formattedText]),f=p.isJson||y,v=!f||u,b=m.useMemo(()=>$0(p.formattedText),[p.formattedText]),x=m.useMemo(()=>{if(s==null)return null;if(typeof s=="string")return Oc(s);try{return{isJson:!0,formattedText:JSON.stringify(s,null,2),parsedJson:s}}catch(k){return console.error("[WorkflowResultCard] Failed to stringify parameters:",k),{isJson:!1,formattedText:String(s)}}},[s]),_=async()=>{try{const k=p.isJson?xr(p.parsedJson):p.formattedText;await os(k)}catch(k){console.error("[WorkflowResultCard] Failed to copy content:",k)}},w=async()=>{if(x)try{const k=x.isJson?xr(x.parsedJson):x.formattedText;await os(k)}catch(k){console.error("[WorkflowResultCard] Failed to copy parameters:",k)}};return r.jsx(ee,{size:"small",variant:"outlined",style:{borderRadius:d.borderRadiusLG,borderColor:d.colorBorderSecondary,backgroundColor:d.colorBgContainer},bodyStyle:{padding:d.paddingMD},children:r.jsxs(X,{direction:"vertical",style:{width:"100%"},size:d.marginSM,children:[r.jsxs(G,{align:"center",justify:"space-between",children:[r.jsxs(X,{size:d.marginXS,align:"center",children:[r.jsx(Px,{style:{color:d.colorWarning}}),r.jsx(Ll,{strong:!0,children:c("components.workflowResult.userWorkflow")}),r.jsx(oe,{color:d.colorWarning,children:t}),r.jsx(oe,{color:$y(n),children:n})]}),r.jsxs(X,{size:"small",children:[r.jsx(ke,{title:c(u?"components.workflowResult.collapseResult":"components.workflowResult.expandResult"),children:f&&r.jsx(Y,{type:"text",size:"small",icon:u?r.jsx(Ex,{}):r.jsx(Rx,{}),onClick:()=>h(k=>!k)})}),r.jsx(ke,{title:c("components.workflowResult.copyResult"),children:r.jsx(Y,{type:"text",size:"small",icon:r.jsx(ss,{}),onClick:_,"aria-label":c("components.workflowResult.copyContent")})}),a&&r.jsx(ke,{title:c("components.workflowResult.retryWorkflow"),children:r.jsx(Y,{type:"text",size:"small",icon:r.jsx(Ms,{}),onClick:a,"aria-label":c("components.workflowResult.retryWorkflow")})})]})]}),o&&r.jsx(Ll,{type:"secondary",style:{fontSize:d.fontSizeSM},children:new Date(o).toLocaleString()}),r.jsx(Rt,{style:{margin:`${d.marginXS}px 0`}}),l&&r.jsx(Xe,{type:"error",message:c("components.workflowResult.executionFailed"),description:l,showIcon:!0,style:{marginBottom:d.marginXS}}),r.jsx(G,{vertical:!0,style:{width:"100%"},children:g?r.jsx(ps,{tip:c("components.workflowResult.waitingForResult")}):p.isJson?r.jsx(fr,{language:"json",style:Un,wrapLongLines:!0,customStyle:{margin:0,borderRadius:d.borderRadiusSM,backgroundColor:d.colorBgContainer,fontSize:d.fontSizeSM,maxHeight:v?"none":280,overflow:v?"auto":"hidden"},children:p.formattedText}):r.jsxs("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:d.fontSizeSM,maxHeight:v?"none":280,overflow:v?"visible":"hidden",marginBottom:0},children:[v?p.formattedText:b.preview,!v&&b.isTruncated&&`
|
|
219
219
|
…`]})}),x&&r.jsxs(G,{vertical:!0,style:{width:"100%"},children:[r.jsx(Rt,{style:{margin:`${d.marginXS}px 0`},children:r.jsxs(X,{size:"small",children:[r.jsx(Ll,{strong:!0,children:c("common.parameters")}),r.jsx(ke,{title:c("components.workflowResult.copyParameters"),children:r.jsx(Y,{type:"text",size:"small",icon:r.jsx(ss,{}),onClick:w,"aria-label":c("components.workflowResult.copyParameters")})})]})}),x.isJson?r.jsx(fr,{language:"json",style:Un,wrapLongLines:!0,customStyle:{margin:0,borderRadius:d.borderRadiusSM,backgroundColor:d.colorBgContainer,fontSize:d.fontSizeSM,maxHeight:220,overflow:"auto"},children:x.formattedText}):r.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:d.fontSizeSM,marginBottom:0},children:x.formattedText})]})]})})},vb=m.memo(c1);vb.displayName="WorkflowResultCard";const{Text:Ol}=le,d1=({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:o,conclusionMarkdown:a,markdownComponents:i,markdownPlugins:l,rehypePlugins:c})=>{const{t:d}=ne(),[u,h]=m.useState(null),p=m.useMemo(()=>Ka({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:o}),[e,t,s,n,o]),g=u===p,y=N(v=>v.setPendingQuestionRespond),f=N(v=>v.clearPendingQuestionRespondForSession);return m.useEffect(()=>{if(typeof window>"u")return;const v=b=>{var w;const _=((w=b.detail)==null?void 0:w.sessionId)??null;!e||_!==e||(h(p),f(e))};return window.addEventListener(pr,v),()=>{window.removeEventListener(pr,v)}},[e,p,f]),m.useEffect(()=>{!e||g||y({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:o??null})},[e,g,p,t,s,n,o,y]),m.useEffect(()=>()=>{e&&f(e)},[e,f]),r.jsxs(X,{direction:"vertical",size:"middle",style:{width:"100%"},children:[a?r.jsx(hs,{remarkPlugins:l,rehypePlugins:c,components:i,children:a}):null,r.jsxs("div",{children:[r.jsx(Ol,{strong:!0,children:d("components.questionDialog.questionLabel","Question")}),r.jsx("div",{style:{marginTop:8},children:r.jsx(hs,{remarkPlugins:l,rehypePlugins:c,components:i,children:t})})]}),g?r.jsx(Ol,{type:"secondary",children:d("components.questionDialog.responseSubmittedContinue","Response submitted. Continuing...")}):r.jsx(Ol,{type:"secondary",children:n?d("components.questionDialog.responseInInputHint","Use the options or input box below to respond."):d("components.questionDialog.responseByOptionHint","Please respond using the options below the input box.")})]})},{Text:cs}=le,u1=e=>{var a;if(!e)return{cleanText:e,hints:[]};const t=e.split(`
|
|
220
220
|
`),s=[],n=[];for(const i of t){const l=i.trim(),c=l.match(/^\[User explicitly selected MCP tool:\s*(.+?)\s*\]$/);if(c){const u=c[1]??"",h=Yn(u);s.push({type:"mcp",label:u,serverId:h==null?void 0:h.serverId,toolName:h==null?void 0:h.toolName});continue}const d=l.match(/^\[User explicitly selected skill:\s*(.+?)\s*\]$/);if(d){const u=d[1]??"",h=u.match(/\(ID:\s*([^)]+)\)\s*$/i),p=(a=h==null?void 0:h[1])==null?void 0:a.trim(),g=h?u.replace(/\(ID:\s*([^)]+)\)\s*$/i,"").trim():u;s.push({type:"skill",label:g||u,skillId:p});continue}n.push(i)}return{cleanText:n.join(`
|
|
221
|
-
`).trimStart(),hints:s}},m1=({sessionId:e,message:t,messageText:s,isUserToolCall:n,formatUserToolCall:o,markdownComponents:a,markdownPlugins:i,rehypePlugins:l})=>{var y;const{t:c}=ne(),d=f=>(f??"").trim().toLowerCase()==="conclusion";if(zy(t)){const f=t.result.result??"",v=t.isError?f||c("components.toolResult.executionFailed"):void 0,b=!v&&f.trim().length===0;if(t.result.display_preference==="Hidden")return null;const x=(t.toolName??"").trim().toLowerCase(),_=x==="conclusion",w=E0(f),k=(x==="conclusion_with_options"||x==="exitplanmode"||x==="request_permissions")&&!t.isError&&w,C=x==="conclusion"?Ry(f):null;return k&&w?r.jsx(d1,{sessionId:e,question:w.question,options:w.options,allowCustom:w.allow_custom,toolCallId:t.toolCallId,conclusionMarkdown:R0(w.conclusion),markdownComponents:a,markdownPlugins:i,rehypePlugins:l}):C?r.jsx(X,{direction:"vertical",style:{width:"100%"},size:"small",children:r.jsx(hs,{remarkPlugins:i,rehypePlugins:l,components:a,children:C})}):r.jsx(eu,{content:f,toolName:t.toolName,status:t.isError?"error":b?"warning":"success",timestamp:t.createdAt,defaultCollapsed:!_,isLoading:b,errorMessage:v})}if(zk(t)){const f=t.content??"",v=t.status==="error"?f||c("components.workflowResult.executionFailed"):void 0,b=!v&&f.trim().length===0;return r.jsx(vb,{content:f,workflowName:t.workflowName,parameters:t.parameters,status:b?"warning":t.status??"success",timestamp:t.createdAt,isLoading:b,errorMessage:v})}if(Fk(t)){const f=t.toolCalls.filter(v=>!d(v.toolName));return f.length===0?null:r.jsx(X,{direction:"vertical",style:{width:"100%"},children:f.map(v=>r.jsx(tu,{toolName:v.toolName,parameters:v.parameters,toolCallId:v.toolCallId,streamingOutput:v.streamingOutput,defaultExpanded:!1,metadata:t.metadata},v.toolCallId))})}if(t.isAuthError)return r.jsxs(X,{direction:"vertical",style:{width:"100%"},size:"middle",children:[r.jsx(Xe,{message:c("chat.messageCard.authRequired"),description:r.jsx(hs,{remarkPlugins:i,rehypePlugins:l,components:a,children:s}),type:"error",showIcon:!0}),r.jsx(Y,{type:"primary",icon:r.jsx(da,{}),onClick:()=>{window.location.hash="/settings"},children:c("chat.messageCard.goToSettings")})]});const{cleanText:u,hints:h}=t.role==="user"?u1(s):{cleanText:s,hints:[]},p=t.role==="assistant"&&"type"in t&&t.type==="text"&&"metadata"in t&&typeof((y=t.metadata)==null?void 0:y.reasoning)=="string"?t.metadata.reasoning:"",g=p.trim().length>0;return t.role==="assistant"&&!s&&!g?r.jsx(cs,{italic:!0,children:c("chat.messageCard.assistantThinking")}):r.jsxs(X,{direction:"vertical",style:{width:"100%"},size:"small",children:[g?r.jsx(ns,{size:"small",defaultActiveKey:["reasoning"],items:[{key:"reasoning",label:r.jsx(cs,{strong:!0,children:c("chat.messageCard.reasoning")}),children:r.jsx(hs,{remarkPlugins:i,rehypePlugins:l,components:a,children:p})}]}):null,h.map((f,v)=>f.type==="mcp"?r.jsx(Xe,{type:"info",showIcon:!1,message:r.jsxs(X,{wrap:!0,size:"small",children:[r.jsx(oe,{color:"purple",children:"MCP"}),r.jsx(cs,{strong:!0,children:c("chat.messageCard.selectedTool")}),f.serverId&&r.jsx(cs,{type:"secondary",children:r.jsx(cs,{code:!0,children:f.serverId})}),f.toolName&&r.jsx(cs,{type:"secondary",children:r.jsx(cs,{code:!0,children:f.toolName})})]}),style:{marginBottom:0}},`hint-mcp-${v}`):r.jsx(Xe,{type:"success",showIcon:!1,message:r.jsxs(X,{wrap:!0,size:"small",children:[r.jsx(oe,{color:"success",children:"Skill"}),r.jsx(cs,{strong:!0,children:c("chat.messageCard.selected")}),f.label&&r.jsx(cs,{children:f.label}),f.skillId&&r.jsx(cs,{type:"secondary",children:r.jsx(cs,{code:!0,children:f.skillId})})]}),style:{marginBottom:0}},`hint-skill-${v}`)),u?r.jsx(hs,{remarkPlugins:i,rehypePlugins:l,components:a,children:n?o(u):u}):null]})},h1=m.memo(m1),{Text:Fl}=le,p1=({role:e,formattedTimestamp:t,token:s})=>{const n=e==="user",o=e==="assistant",a=n?"You":o?"Bodhi":e,i=n?"Y":o?"B":e.slice(0,1).toUpperCase();return r.jsxs(G,{align:"center",justify:"space-between",gap:s.marginXS,style:{marginBottom:s.marginXS},children:[r.jsxs(G,{align:"center",gap:10,children:[r.jsx("div",{style:{width:30,height:30,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:700,letterSpacing:"0.3px",background:n?"var(--lotus-avatar-user-bg)":o?"var(--lotus-avatar-assistant-bg)":"var(--lotus-avatar-system-bg)",color:"white",boxShadow:n?"var(--lotus-avatar-user-shadow)":o?"var(--lotus-avatar-assistant-shadow)":"var(--lotus-avatar-system-shadow)",border:"var(--lotus-avatar-border)"},children:i}),r.jsxs(G,{vertical:!0,gap:0,children:[r.jsx(Fl,{strong:!0,style:{fontSize:13,color:n?"var(--lotus-primary)":s.colorText,letterSpacing:"0.2px",lineHeight:1.1},children:a}),r.jsx(Fl,{type:"secondary",style:{fontSize:11,lineHeight:1.1},children:n?"Prompt":o?"Assistant":"System"})]})]}),t&&r.jsx(Fl,{type:"secondary",style:{fontSize:11,whiteSpace:"nowrap",opacity:.92,padding:"4px 8px",borderRadius:999,background:"var(--lotus-timestamp-bg)",border:"1px solid var(--lotus-timestamp-border)"},children:t})]})},su=e=>{if(e.includes("```json")){const t=e.indexOf("```json")+7,s=e.indexOf("```",t);if(s>t)return e.substring(t,s).trim()}else if(e.includes("{")){const t=e.indexOf("{"),s=e.lastIndexOf("}");if(s>t)return e.substring(t,s+1).trim()}return null},f1=e=>e==="text"||e==="plan"||e==="question"||e==="tool_call"||e==="tool_result",g1=(e,t)=>{if(t)return t;if("message_type"in e&&e.message_type){const s=e.message_type;if(f1(s))return s}if(e.role==="assistant"&&e.type==="text"){const s=typeof e.content=="string"?e.content:"";try{const n=su(s);if(n){const o=JSON.parse(n);if(o.goal&&o.steps&&Array.isArray(o.steps))return"plan";if(o.type==="question"&&o.question)return"question"}}catch{return"text"}}return"text"},y1=(e,t)=>{if(t!=="plan"||e.role!=="assistant"||e.type!=="text")return null;const s=e.content??"";try{const n=su(s);if(n){const o=JSON.parse(n);if(o.goal&&o.steps)return{goal:o.goal,steps:o.steps.map(a=>({step_number:a.step_number||a.stepNumber||0,action:a.action||"",reason:a.reason||a.rationale||"",tools_needed:a.tools_needed||a.tools||[],estimated_time:a.estimated_time||a.estimatedTime||""})),estimated_total_time:o.estimated_total_time||o.estimatedTotalTime||"",risks:o.risks||[],prerequisites:o.prerequisites||[]}}}catch(n){console.error("Failed to parse plan:",n)}return null},b1=(e,t)=>{if(t!=="question"||e.role!=="assistant"||e.type!=="text")return null;const s=e.content??"";try{const n=su(s);if(n){const o=JSON.parse(n);if(o.type==="question"&&o.question)return{type:"question",question:o.question,context:o.context||"",severity:o.severity||"minor",options:o.options||[],default:o.default,allow_custom:o.allow_custom||!1}}}catch(n){console.error("Failed to parse question:",n)}return null},Sb=e=>{if(e.role==="system")return typeof e.content=="string"?e.content:"";if(e.role==="user")return"type"in e&&e.type==="file_reference"?"":typeof e.content=="string"?e.content:"";if(e.role==="assistant"){if(e.type==="text")return typeof e.content=="string"?e.content:"";if(e.type==="tool_result")return(e.toolName??"").trim().toLowerCase()==="conclusion"?Ry(e.result.result)??e.result.result:`Tool ${e.toolName} Result: ${e.result.result}`;if(e.type==="tool_call")return`Requesting to call ${e.toolCalls.map(t=>t.toolName).join(", ")}`;if(e.type==="workflow_result")return e.content}return""},x1=e=>{if(!e.startsWith("/"))return e;const t=e.split(" "),s=t[0].substring(1),n=t.slice(1).join(" ");if(s.startsWith("mcp__")){const a=s.slice(5),i=a.indexOf("__");if(i>0){const l=a.slice(0,i),c=a.slice(i+2);if(l&&c)return`🔌 MCP ${l}/${c}: ${n}`}}return`🔧 ${s.replace(/_/g," ").replace(/\b\w/g,a=>a.toUpperCase())}: ${n}`},Yh=e=>e.map(t=>({name:t.name,extensions:[...t.extensions]})),Xh=e=>e.trim().slice(0,64).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-")||"message",v1={marginSM:12,marginXS:6,paddingXS:6,paddingSM:10,padding:12,borderRadiusSM:8,fontSizeSM:12,colorPrimary:"#0d9488",colorPrimaryBg:"#e6f4ff",colorTextSecondary:"#595959",colorText:"#1f1f1f",colorLink:"#0d9488",colorBgContainer:"#ffffff",colorBorder:"#d9d9d9",boxShadowSecondary:"none"},S1='[data-mermaid-loading="true"]';class wb{static async exportMessageText(t){const{format:s,content:n,sessionId:o=null,messageId:a=null,filenamePrefix:i}=t,l=i||["chat-message",o?Xh(o.slice(0,8)):null,a?Xh(a.slice(0,8)):null].filter(Boolean).join("-"),c=s==="markdown"?ks.generateTimestampedFilename(l,"md"):ks.generateTimestampedFilename(l,"pdf");if(s==="markdown"){const d=await ks.saveTextFile(n,Yh(ks.FILTERS.MARKDOWN),c);return d.success?{success:!0,filename:d.filename}:{success:!1,error:d.error}}try{const d=await this.generatePdfFromText(n),u=await ks.saveBinaryFile(d,Yh(ks.FILTERS.PDF),c);return u.success?{success:!0,filename:u.filename}:{success:!1,error:u.error}}catch(d){return{success:!1,error:d instanceof Error?d.message:es.t("chat.messageActions.exportFailed")}}}static async generatePdfFromText(t){if(typeof document>"u")throw new Error(es.t("chat.messageActions.pdfUnavailable"));const s=(await Dt(async()=>{const{default:g}=await import("./vendor-pdf-DrBG_eov.js").then(y=>y.h);return{default:g}},__vite__mapDeps([16,1,2,3]),import.meta.url)).default,{jsPDF:n}=await Dt(async()=>{const{jsPDF:g}=await import("./vendor-pdf-DrBG_eov.js").then(y=>y.j);return{jsPDF:g}},__vite__mapDeps([16,1,2,3]),import.meta.url),{createRoot:o}=await Dt(async()=>{const{createRoot:g}=await import("./main-CehMQ1Uh.js").then(y=>y.c);return{createRoot:g}},__vite__mapDeps([4,1,2,3,5]),import.meta.url),{flushSync:a}=await Dt(async()=>{const{flushSync:g}=await import("./vendor-antd-DzhFcYgt.js").then(y=>y.R);return{flushSync:g}},__vite__mapDeps([3,2]),import.meta.url),i=xb(v1,{mermaidRenderMode:"eager"}),l=document.createElement("div");l.style.position="fixed",l.style.left="0",l.style.top="0",l.style.right="0",l.style.bottom="0",l.style.zIndex="2147483647",l.style.background="rgba(0,0,0,0.15)",l.style.display="flex",l.style.alignItems="center",l.style.justifyContent="center",l.style.fontFamily="system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",l.style.fontSize="14px",l.style.color="#111";const c=document.createElement("div");c.style.background="#fff",c.style.border="1px solid rgba(0,0,0,0.12)",c.style.borderRadius="10px",c.style.padding="12px 14px",c.style.boxShadow="0 8px 24px rgba(0,0,0,0.12)",c.textContent=es.t("chat.messageActions.exportingPdf"),l.appendChild(c);const d=document.createElement("div");d.style.position="fixed",d.style.left="0",d.style.top="0",d.style.zIndex="2147483646",d.style.pointerEvents="none",d.style.width="794px",d.style.background="#fff",d.style.color="#111",d.style.padding="24px",d.style.boxSizing="border-box",d.style.fontFamily="system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",d.style.fontSize="14px",d.style.lineHeight="1.35";const u=document.createElement("style");u.textContent=`
|
|
221
|
+
`).trimStart(),hints:s}},m1=({sessionId:e,message:t,messageText:s,isUserToolCall:n,formatUserToolCall:o,markdownComponents:a,markdownPlugins:i,rehypePlugins:l})=>{var y;const{t:c}=ne(),d=f=>(f??"").trim().toLowerCase()==="conclusion";if(zy(t)){const f=t.result.result??"",v=t.isError?f||c("components.toolResult.executionFailed"):void 0,b=!v&&f.trim().length===0;if(t.result.display_preference==="Hidden")return null;const x=(t.toolName??"").trim().toLowerCase(),_=x==="conclusion",w=E0(f),k=(x==="conclusion_with_options"||x==="exitplanmode"||x==="request_permissions")&&!t.isError&&w,C=x==="conclusion"?Ry(f):null;return k&&w?r.jsx(d1,{sessionId:e,question:w.question,options:w.options,allowCustom:w.allow_custom,toolCallId:t.toolCallId,conclusionMarkdown:R0(w.conclusion),markdownComponents:a,markdownPlugins:i,rehypePlugins:l}):C?r.jsx(X,{direction:"vertical",style:{width:"100%"},size:"small",children:r.jsx(hs,{remarkPlugins:i,rehypePlugins:l,components:a,children:C})}):r.jsx(eu,{content:f,toolName:t.toolName,status:t.isError?"error":b?"warning":"success",timestamp:t.createdAt,defaultCollapsed:!_,isLoading:b,errorMessage:v})}if(zk(t)){const f=t.content??"",v=t.status==="error"?f||c("components.workflowResult.executionFailed"):void 0,b=!v&&f.trim().length===0;return r.jsx(vb,{content:f,workflowName:t.workflowName,parameters:t.parameters,status:b?"warning":t.status??"success",timestamp:t.createdAt,isLoading:b,errorMessage:v})}if(Fk(t)){const f=t.toolCalls.filter(v=>!d(v.toolName));return f.length===0?null:r.jsx(X,{direction:"vertical",style:{width:"100%"},children:f.map(v=>r.jsx(tu,{toolName:v.toolName,parameters:v.parameters,toolCallId:v.toolCallId,streamingOutput:v.streamingOutput,defaultExpanded:!1,metadata:t.metadata},v.toolCallId))})}if(t.isAuthError)return r.jsxs(X,{direction:"vertical",style:{width:"100%"},size:"middle",children:[r.jsx(Xe,{message:c("chat.messageCard.authRequired"),description:r.jsx(hs,{remarkPlugins:i,rehypePlugins:l,components:a,children:s}),type:"error",showIcon:!0}),r.jsx(Y,{type:"primary",icon:r.jsx(da,{}),onClick:()=>{window.location.hash="/settings"},children:c("chat.messageCard.goToSettings")})]});const{cleanText:u,hints:h}=t.role==="user"?u1(s):{cleanText:s,hints:[]},p=t.role==="assistant"&&"type"in t&&t.type==="text"&&"metadata"in t&&typeof((y=t.metadata)==null?void 0:y.reasoning)=="string"?t.metadata.reasoning:"",g=p.trim().length>0;return t.role==="assistant"&&!s&&!g?r.jsx(cs,{italic:!0,children:c("chat.messageCard.assistantThinking")}):r.jsxs(X,{direction:"vertical",style:{width:"100%"},size:"small",children:[g?r.jsx(ns,{size:"small",defaultActiveKey:["reasoning"],items:[{key:"reasoning",label:r.jsx(cs,{strong:!0,children:c("chat.messageCard.reasoning")}),children:r.jsx(hs,{remarkPlugins:i,rehypePlugins:l,components:a,children:p})}]}):null,h.map((f,v)=>f.type==="mcp"?r.jsx(Xe,{type:"info",showIcon:!1,message:r.jsxs(X,{wrap:!0,size:"small",children:[r.jsx(oe,{color:"purple",children:"MCP"}),r.jsx(cs,{strong:!0,children:c("chat.messageCard.selectedTool")}),f.serverId&&r.jsx(cs,{type:"secondary",children:r.jsx(cs,{code:!0,children:f.serverId})}),f.toolName&&r.jsx(cs,{type:"secondary",children:r.jsx(cs,{code:!0,children:f.toolName})})]}),style:{marginBottom:0}},`hint-mcp-${v}`):r.jsx(Xe,{type:"success",showIcon:!1,message:r.jsxs(X,{wrap:!0,size:"small",children:[r.jsx(oe,{color:"success",children:"Skill"}),r.jsx(cs,{strong:!0,children:c("chat.messageCard.selected")}),f.label&&r.jsx(cs,{children:f.label}),f.skillId&&r.jsx(cs,{type:"secondary",children:r.jsx(cs,{code:!0,children:f.skillId})})]}),style:{marginBottom:0}},`hint-skill-${v}`)),u?r.jsx(hs,{remarkPlugins:i,rehypePlugins:l,components:a,children:n?o(u):u}):null]})},h1=m.memo(m1),{Text:Fl}=le,p1=({role:e,formattedTimestamp:t,token:s})=>{const n=e==="user",o=e==="assistant",a=n?"You":o?"Bodhi":e,i=n?"Y":o?"B":e.slice(0,1).toUpperCase();return r.jsxs(G,{align:"center",justify:"space-between",gap:s.marginXS,style:{marginBottom:s.marginXS},children:[r.jsxs(G,{align:"center",gap:10,children:[r.jsx("div",{style:{width:30,height:30,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:700,letterSpacing:"0.3px",background:n?"var(--lotus-avatar-user-bg)":o?"var(--lotus-avatar-assistant-bg)":"var(--lotus-avatar-system-bg)",color:"white",boxShadow:n?"var(--lotus-avatar-user-shadow)":o?"var(--lotus-avatar-assistant-shadow)":"var(--lotus-avatar-system-shadow)",border:"var(--lotus-avatar-border)"},children:i}),r.jsxs(G,{vertical:!0,gap:0,children:[r.jsx(Fl,{strong:!0,style:{fontSize:13,color:n?"var(--lotus-primary)":s.colorText,letterSpacing:"0.2px",lineHeight:1.1},children:a}),r.jsx(Fl,{type:"secondary",style:{fontSize:11,lineHeight:1.1},children:n?"Prompt":o?"Assistant":"System"})]})]}),t&&r.jsx(Fl,{type:"secondary",style:{fontSize:11,whiteSpace:"nowrap",opacity:.92,padding:"4px 8px",borderRadius:999,background:"var(--lotus-timestamp-bg)",border:"1px solid var(--lotus-timestamp-border)"},children:t})]})},su=e=>{if(e.includes("```json")){const t=e.indexOf("```json")+7,s=e.indexOf("```",t);if(s>t)return e.substring(t,s).trim()}else if(e.includes("{")){const t=e.indexOf("{"),s=e.lastIndexOf("}");if(s>t)return e.substring(t,s+1).trim()}return null},f1=e=>e==="text"||e==="plan"||e==="question"||e==="tool_call"||e==="tool_result",g1=(e,t)=>{if(t)return t;if("message_type"in e&&e.message_type){const s=e.message_type;if(f1(s))return s}if(e.role==="assistant"&&e.type==="text"){const s=typeof e.content=="string"?e.content:"";try{const n=su(s);if(n){const o=JSON.parse(n);if(o.goal&&o.steps&&Array.isArray(o.steps))return"plan";if(o.type==="question"&&o.question)return"question"}}catch{return"text"}}return"text"},y1=(e,t)=>{if(t!=="plan"||e.role!=="assistant"||e.type!=="text")return null;const s=e.content??"";try{const n=su(s);if(n){const o=JSON.parse(n);if(o.goal&&o.steps)return{goal:o.goal,steps:o.steps.map(a=>({step_number:a.step_number||a.stepNumber||0,action:a.action||"",reason:a.reason||a.rationale||"",tools_needed:a.tools_needed||a.tools||[],estimated_time:a.estimated_time||a.estimatedTime||""})),estimated_total_time:o.estimated_total_time||o.estimatedTotalTime||"",risks:o.risks||[],prerequisites:o.prerequisites||[]}}}catch(n){console.error("Failed to parse plan:",n)}return null},b1=(e,t)=>{if(t!=="question"||e.role!=="assistant"||e.type!=="text")return null;const s=e.content??"";try{const n=su(s);if(n){const o=JSON.parse(n);if(o.type==="question"&&o.question)return{type:"question",question:o.question,context:o.context||"",severity:o.severity||"minor",options:o.options||[],default:o.default,allow_custom:o.allow_custom||!1}}}catch(n){console.error("Failed to parse question:",n)}return null},Sb=e=>{if(e.role==="system")return typeof e.content=="string"?e.content:"";if(e.role==="user")return"type"in e&&e.type==="file_reference"?"":typeof e.content=="string"?e.content:"";if(e.role==="assistant"){if(e.type==="text")return typeof e.content=="string"?e.content:"";if(e.type==="tool_result")return(e.toolName??"").trim().toLowerCase()==="conclusion"?Ry(e.result.result)??e.result.result:`Tool ${e.toolName} Result: ${e.result.result}`;if(e.type==="tool_call")return`Requesting to call ${e.toolCalls.map(t=>t.toolName).join(", ")}`;if(e.type==="workflow_result")return e.content}return""},x1=e=>{if(!e.startsWith("/"))return e;const t=e.split(" "),s=t[0].substring(1),n=t.slice(1).join(" ");if(s.startsWith("mcp__")){const a=s.slice(5),i=a.indexOf("__");if(i>0){const l=a.slice(0,i),c=a.slice(i+2);if(l&&c)return`🔌 MCP ${l}/${c}: ${n}`}}return`🔧 ${s.replace(/_/g," ").replace(/\b\w/g,a=>a.toUpperCase())}: ${n}`},Yh=e=>e.map(t=>({name:t.name,extensions:[...t.extensions]})),Xh=e=>e.trim().slice(0,64).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-")||"message",v1={marginSM:12,marginXS:6,paddingXS:6,paddingSM:10,padding:12,borderRadiusSM:8,fontSizeSM:12,colorPrimary:"#0d9488",colorPrimaryBg:"#e6f4ff",colorTextSecondary:"#595959",colorText:"#1f1f1f",colorLink:"#0d9488",colorBgContainer:"#ffffff",colorBorder:"#d9d9d9",boxShadowSecondary:"none"},S1='[data-mermaid-loading="true"]';class wb{static async exportMessageText(t){const{format:s,content:n,sessionId:o=null,messageId:a=null,filenamePrefix:i}=t,l=i||["chat-message",o?Xh(o.slice(0,8)):null,a?Xh(a.slice(0,8)):null].filter(Boolean).join("-"),c=s==="markdown"?ks.generateTimestampedFilename(l,"md"):ks.generateTimestampedFilename(l,"pdf");if(s==="markdown"){const d=await ks.saveTextFile(n,Yh(ks.FILTERS.MARKDOWN),c);return d.success?{success:!0,filename:d.filename}:{success:!1,error:d.error}}try{const d=await this.generatePdfFromText(n),u=await ks.saveBinaryFile(d,Yh(ks.FILTERS.PDF),c);return u.success?{success:!0,filename:u.filename}:{success:!1,error:u.error}}catch(d){return{success:!1,error:d instanceof Error?d.message:es.t("chat.messageActions.exportFailed")}}}static async generatePdfFromText(t){if(typeof document>"u")throw new Error(es.t("chat.messageActions.pdfUnavailable"));const s=(await Dt(async()=>{const{default:g}=await import("./vendor-pdf-CQWTPgH8.js").then(y=>y.h);return{default:g}},__vite__mapDeps([16,1,2,3]),import.meta.url)).default,{jsPDF:n}=await Dt(async()=>{const{jsPDF:g}=await import("./vendor-pdf-CQWTPgH8.js").then(y=>y.j);return{jsPDF:g}},__vite__mapDeps([16,1,2,3]),import.meta.url),{createRoot:o}=await Dt(async()=>{const{createRoot:g}=await import("./main-YQiM0LtA.js").then(y=>y.c);return{createRoot:g}},__vite__mapDeps([4,1,2,3,5]),import.meta.url),{flushSync:a}=await Dt(async()=>{const{flushSync:g}=await import("./vendor-antd-DzhFcYgt.js").then(y=>y.R);return{flushSync:g}},__vite__mapDeps([3,2]),import.meta.url),i=xb(v1,{mermaidRenderMode:"eager"}),l=document.createElement("div");l.style.position="fixed",l.style.left="0",l.style.top="0",l.style.right="0",l.style.bottom="0",l.style.zIndex="2147483647",l.style.background="rgba(0,0,0,0.15)",l.style.display="flex",l.style.alignItems="center",l.style.justifyContent="center",l.style.fontFamily="system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",l.style.fontSize="14px",l.style.color="#111";const c=document.createElement("div");c.style.background="#fff",c.style.border="1px solid rgba(0,0,0,0.12)",c.style.borderRadius="10px",c.style.padding="12px 14px",c.style.boxShadow="0 8px 24px rgba(0,0,0,0.12)",c.textContent=es.t("chat.messageActions.exportingPdf"),l.appendChild(c);const d=document.createElement("div");d.style.position="fixed",d.style.left="0",d.style.top="0",d.style.zIndex="2147483646",d.style.pointerEvents="none",d.style.width="794px",d.style.background="#fff",d.style.color="#111",d.style.padding="24px",d.style.boxSizing="border-box",d.style.fontFamily="system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",d.style.fontSize="14px",d.style.lineHeight="1.35";const u=document.createElement("style");u.textContent=`
|
|
222
222
|
.md-export { color: #111; }
|
|
223
223
|
.md-export h1 { font-size: 24px; margin: 0 0 16px; }
|
|
224
224
|
.md-export h2 { font-size: 18px; margin: 18px 0 12px; }
|