@bigduu/lotus 2026.4.30 → 2026.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-v1C2DQLr.js","./vendor-markdown-DrUBuQ-c.js","./vendor-i18n-BNURlJ23.js","./vendor-antd-Dvkx9eba.js","./main-BgGBpmTu.js","./main-B6snAd4S.css","./vendor-charts-DHCOhRb3.js","./vendor-mermaid-BAz0MwVj.js","./index-BAibvIVz.js","./index-yMJRRs89.js","./index-Bi-vGirQ.css","./index-C9mV36Y0.js","./index-BNcuFl0J.js","./index-BmjFP0ha.js","./core-Cfh-QHsP.js","./index-_XI0Qq6F.js","./vendor-pdf-wx1tMujY.js"])))=>i.map(i=>d[i]);
2
- var tx=Object.defineProperty;var sx=(e,t,s)=>t in e?tx(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var Je=(e,t,s)=>sx(e,typeof t!="symbol"?t+"":t,s);import{j as r,M as xs,r as Ii,h as br,_ as Dt,S as St,a as uf,t as mf,p as hf,b as nx,c as Zc,d as rx,m as pf,s as ox,y as ff,e as gf,f as ed,g as td,i as yf}from"./vendor-markdown-DrUBuQ-c.js";import{a as m,R as xt,i as is,u as ie,g as _r}from"./vendor-i18n-BNURlJ23.js";import{r as ax,A as ix}from"./main-BgGBpmTu.js";import{S as U,B,C as te,m as pe,L as lt,Y as ls,T as ue,Z as lx,$ as sd,a0 as cs,a1 as fn,M as Bt,E as Pt,a2 as Tr,t as xe,a3 as sc,a4 as nd,j as ca,O as xr,a5 as bf,a6 as cx,k as gn,H as dx,o as kr,a7 as qn,a8 as ux,I as be,K as V,a9 as Xt,aa as Vs,i as Ks,ab as da,n as Re,ac as mx,ad as hx,A as ut,ae as xf,af as sa,ag as px,ah as $i,p as tt,F as ne,v as Ss,ai as ui,aj as Le,ak as ft,al as ns,am as Be,an as Ft,ao as dt,ap as fx,V as $t,aq as ws,ar as gx,as as rd,P as mi,at as ua,au as Sf,av as Di,aw as uu,ax as Gs,u as Zs,ay as yx,az as Li,aA as nc,aB as At,aC as bx,aD as en,aE as ht,aF as od,aG as mu,Q as Js,aH as Qs,aI as rc,aJ as ka,aK as xx,aL as Sx,G as vx,aM as Nn,aN as vf,aO as hu,aP as Sr,aQ as wx,aR as _x,l as vr,aS as ad,U as Oi,aT as Tx,aU as kx,aV as wf,aW as id,aX as _f,aY as jx,aZ as Cx,a_ as Mx,a$ as Px,b0 as Ex,b1 as Rx,b2 as Ax,b3 as Tf,b4 as Ix,x as kf,q as hi,b5 as ld,w as $x,b6 as Dx,b7 as Lx,N as Ox,b8 as Fx,b9 as zx,ba as Nx,bb as Bx,bc as jf,bd as Wx,be as Ux,bf as qx,bg as cd,bh as Hx,bi as Yx,bj as pi,bk as pu,bl as Cf,bm as fu,bn as Xx,bo as Vx,bp as Kx,bq as Gx,br as Mf,bs as Jx,bt as Qx,bu as Zx,bv as gu,bw as yu}from"./vendor-antd-Dvkx9eba.js";import{Z as jr,_ as dd,$ as ma,a0 as ha,a1 as pa,a2 as Cr,a3 as ud,a4 as fi,a5 as Pf,a6 as pr,a7 as eS,a8 as tS,a9 as sS}from"./vendor-charts-DHCOhRb3.js";import{bc as md}from"./vendor-mermaid-BAz0MwVj.js";function Ef(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 hd(){return Ef("(max-width: 768px)")}const nS=({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(U,{...a,children:e.map(i=>r.jsx(B,{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))})},rS=(e,t)=>({key:"cancel",text:t||"Cancel",type:"default",onClick:e}),oS=(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}),bu=e=>{let t;const s=new Set,n=(u,d)=>{const h=typeof u=="function"?u(t):u;if(!Object.is(h,t)){const p=t;t=d??(typeof h!="object"||h===null)?h:Object.assign({},t,h),s.forEach(f=>f(t,p))}},o=()=>t,l={setState:n,getState:o,getInitialState:()=>c,subscribe:u=>(s.add(u),()=>s.delete(u))},c=t=e(n,o,l);return l},aS=e=>e?bu(e):bu,iS=e=>e;function lS(e,t=iS){const s=xt.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return xt.useDebugValue(s),s}const xu=e=>{const t=aS(e),s=n=>lS(t,n);return Object.assign(s,t),s},yn=e=>e?xu(e):xu,Su={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1},na=new Map,ja=e=>{const t=na.get(e);return t?Object.fromEntries(Object.entries(t.stores).map(([s,n])=>[s,n.getState()])):{}},cS=(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}},dS=(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))},uS=e=>{var t,s;if(!e)return;const n=e.split(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-D839lRZb.js","./vendor-markdown-DrUBuQ-c.js","./vendor-i18n-BNURlJ23.js","./vendor-antd-Dvkx9eba.js","./main-tzCacohH.js","./main-B6snAd4S.css","./vendor-charts-DHCOhRb3.js","./vendor-mermaid-BAz0MwVj.js","./index-BAibvIVz.js","./index-DjUMzvjR.js","./index-Bi-vGirQ.css","./index-BrpQmT5J.js","./index-BNcuFl0J.js","./index-BmjFP0ha.js","./core-Cfh-QHsP.js","./index-_XI0Qq6F.js","./vendor-pdf-wx1tMujY.js"])))=>i.map(i=>d[i]);
2
+ var tx=Object.defineProperty;var sx=(e,t,s)=>t in e?tx(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var Je=(e,t,s)=>sx(e,typeof t!="symbol"?t+"":t,s);import{j as r,M as xs,r as Ii,h as br,_ as Dt,S as St,a as uf,t as mf,p as hf,b as nx,c as Zc,d as rx,m as pf,s as ox,y as ff,e as gf,f as ed,g as td,i as yf}from"./vendor-markdown-DrUBuQ-c.js";import{a as m,R as xt,i as is,u as ie,g as _r}from"./vendor-i18n-BNURlJ23.js";import{r as ax,A as ix}from"./main-tzCacohH.js";import{S as U,B,C as te,m as pe,L as lt,Y as ls,T as ue,Z as lx,$ as sd,a0 as cs,a1 as fn,M as Bt,E as Pt,a2 as Tr,t as xe,a3 as sc,a4 as nd,j as ca,O as xr,a5 as bf,a6 as cx,k as gn,H as dx,o as kr,a7 as qn,a8 as ux,I as be,K as V,a9 as Xt,aa as Vs,i as Ks,ab as da,n as Re,ac as mx,ad as hx,A as ut,ae as xf,af as sa,ag as px,ah as $i,p as tt,F as ne,v as Ss,ai as ui,aj as Le,ak as ft,al as ns,am as Be,an as Ft,ao as dt,ap as fx,V as $t,aq as ws,ar as gx,as as rd,P as mi,at as ua,au as Sf,av as Di,aw as uu,ax as Gs,u as Zs,ay as yx,az as Li,aA as nc,aB as At,aC as bx,aD as en,aE as ht,aF as od,aG as mu,Q as Js,aH as Qs,aI as rc,aJ as ka,aK as xx,aL as Sx,G as vx,aM as Nn,aN as vf,aO as hu,aP as Sr,aQ as wx,aR as _x,l as vr,aS as ad,U as Oi,aT as Tx,aU as kx,aV as wf,aW as id,aX as _f,aY as jx,aZ as Cx,a_ as Mx,a$ as Px,b0 as Ex,b1 as Rx,b2 as Ax,b3 as Tf,b4 as Ix,x as kf,q as hi,b5 as ld,w as $x,b6 as Dx,b7 as Lx,N as Ox,b8 as Fx,b9 as zx,ba as Nx,bb as Bx,bc as jf,bd as Wx,be as Ux,bf as qx,bg as cd,bh as Hx,bi as Yx,bj as pi,bk as pu,bl as Cf,bm as fu,bn as Xx,bo as Vx,bp as Kx,bq as Gx,br as Mf,bs as Jx,bt as Qx,bu as Zx,bv as gu,bw as yu}from"./vendor-antd-Dvkx9eba.js";import{Z as jr,_ as dd,$ as ma,a0 as ha,a1 as pa,a2 as Cr,a3 as ud,a4 as fi,a5 as Pf,a6 as pr,a7 as eS,a8 as tS,a9 as sS}from"./vendor-charts-DHCOhRb3.js";import{bc as md}from"./vendor-mermaid-BAz0MwVj.js";function Ef(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 hd(){return Ef("(max-width: 768px)")}const nS=({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(U,{...a,children:e.map(i=>r.jsx(B,{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))})},rS=(e,t)=>({key:"cancel",text:t||"Cancel",type:"default",onClick:e}),oS=(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}),bu=e=>{let t;const s=new Set,n=(u,d)=>{const h=typeof u=="function"?u(t):u;if(!Object.is(h,t)){const p=t;t=d??(typeof h!="object"||h===null)?h:Object.assign({},t,h),s.forEach(f=>f(t,p))}},o=()=>t,l={setState:n,getState:o,getInitialState:()=>c,subscribe:u=>(s.add(u),()=>s.delete(u))},c=t=e(n,o,l);return l},aS=e=>e?bu(e):bu,iS=e=>e;function lS(e,t=iS){const s=xt.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return xt.useDebugValue(s),s}const xu=e=>{const t=aS(e),s=n=>lS(t,n);return Object.assign(s,t),s},yn=e=>e?xu(e):xu,Su={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1},na=new Map,ja=e=>{const t=na.get(e);return t?Object.fromEntries(Object.entries(t.stores).map(([s,n])=>[s,n.getState()])):{}},cS=(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}},dS=(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))},uS=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]},mS=(e,t={})=>(s,n,o)=>{const{enabled:a,anonymousActionType:i,store:l,...c}=t;let u;try{u=(a??(Su?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!u)return e(s,n,o);const{connection:d,...h}=cS(l,u,c);let p=!0;o.setState=(g,S,v)=>{const x=s(g,S);if(!p)return x;const T=v===void 0?{type:i||uS(new Error().stack)||"anonymous"}:typeof v=="string"?{type:v}:v;return l===void 0?(d==null||d.send(T,n()),x):(d==null||d.send({...T,type:`${l}/${T.type}`},{...ja(c.name),[l]:o.getState()}),x)},o.devtools={cleanup:()=>{d&&typeof d.unsubscribe=="function"&&d.unsubscribe(),dS(c.name,l)}};const f=(...g)=>{const S=p;p=!1,s(...g),p=S},y=e(o.setState,n,o);if(h.type==="untracked"?d==null||d.init(y):(h.stores[h.store]=o,d==null||d.init(Object.fromEntries(Object.entries(h.stores).map(([g,S])=>[g,g===h.store?y:S.getState()])))),o.dispatchFromDevtools&&typeof o.dispatch=="function"){let g=!1;const S=o.dispatch;o.dispatch=(...v)=>{(Su?"production":void 0)!=="production"&&v[0].type==="__setState"&&!g&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),g=!0),S(...v)}}return d.subscribe(g=>{var S;switch(g.type){case"ACTION":if(typeof g.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return Zi(g.payload,v=>{if(v.type==="__setState"){if(l===void 0){f(v.state);return}Object.keys(v.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 tx=Object.defineProperty;var sx=(e,t,s)=>t in e?tx(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=()=>[RS()];class AS{async getProviderConfig(){return je.get("/bamboo/settings/provider")}async saveProviderConfig(t){return je.post("/bamboo/settings/provider",t)}async reloadConfig(){return je.post("/bamboo/settings/reload")}async getCopilotAuthStatus(){return je.post("/bamboo/copilot/auth/status")}async startCopilotAuth(){return je.post("/bamboo/copilot/auth/start")}async completeCopilotAuth(t){return je.post("/bamboo/copilot/auth/complete",t)}async authenticateCopilot(){return je.post("/bamboo/copilot/authenticate")}async logoutCopilot(){return je.post("/bamboo/copilot/logout")}async fetchProviderModels(t){return(await je.post("/bamboo/settings/provider/models",{provider:t})).models}async getProviderCatalog(){return je.get("/bamboo/provider-catalog")}async fetchCatalogModels(t){const s=t?{provider:t}:{};return je.post("/bamboo/provider-catalog/fetch-models",s)}async getEnvVars(){return je.get("/bamboo/env-vars")}async upsertEnvVar(t){return je.post("/bamboo/env-vars",t)}async deleteEnvVar(t){return je.delete(`/bamboo/env-vars/${encodeURIComponent(t)}`)}async replaceEnvVars(t){return je.post("/bamboo/env-vars/replace",{entries:t})}}const zt=new AS,ze=yn((e,t)=>({currentProvider:"copilot",providerConfig:{provider:"copilot",defaults:void 0,providers:{}},isLoading:!1,error:null,selectedModelRef:null,catalog:null,isCatalogFetching:!1,loadProviderConfig:async()=>{var s,n;e({isLoading:!0,error:null});try{const o=await zt.getProviderConfig();if(!((n=(s=o.defaults)==null?void 0:s.chat)!=null&&n.model)&&o.provider&&o.providers){const a=o.provider,i=o.providers[a],l=i==null?void 0:i.model;l&&(o.defaults={chat:{provider:a,model:l}})}e({providerConfig:o,currentProvider:o.provider,isLoading:!1})}catch(o){console.error("Failed to load provider config:",o),e({error:o instanceof Error?o.message:"Failed to load provider config",isLoading:!1})}},setCurrentProvider:s=>{e({currentProvider:s})},updateProviderConfig:s=>{e(n=>({providerConfig:{...n.providerConfig,...s}}))},getActiveModel:()=>{var o,a,i;return((i=(a=(o=t().providerConfig.defaults)==null?void 0:o.chat)==null?void 0:a.model)==null?void 0:i.trim())||void 0},getFastModel:()=>{var o,a,i;const s=t();return((i=(a=(o=s.providerConfig.defaults)==null?void 0:o.fast)==null?void 0:a.model)==null?void 0:i.trim())||s.getActiveModel()},getVisionModel:()=>{var o,a,i;const s=t();return((i=(a=(o=s.providerConfig.defaults)==null?void 0:o.vision)==null?void 0:a.model)==null?void 0:i.trim())||s.getActiveModel()},isProviderModelRefEnabled:()=>!0,setSelectedModelRef:s=>{e({selectedModelRef:s})},loadCatalog:async()=>{try{const s=await zt.getProviderCatalog();e({catalog:s})}catch{}},fetchCatalogModels:async s=>{e({isCatalogFetching:!0});try{await zt.fetchCatalogModels(s),await t().loadCatalog()}catch{}finally{e({isCatalogFetching:!1})}},getFastModelRef:()=>{var a,i,l,c;const s=t(),n=(a=s.providerConfig.defaults)==null?void 0:a.fast;if((i=n==null?void 0:n.model)!=null&&i.trim())return n;const o=(l=s.providerConfig.defaults)==null?void 0:l.chat;return(c=o==null?void 0:o.model)!=null&&c.trim()?o:null},getVisionModelRef:()=>{var a,i,l,c;const s=t(),n=(a=s.providerConfig.defaults)==null?void 0:a.vision;if((i=n==null?void 0:n.model)!=null&&i.trim())return n;const o=(l=s.providerConfig.defaults)==null?void 0:l.chat;return(c=o==null?void 0:o.model)!=null&&c.trim()?o:null},getModelsForProvider:s=>{const{catalog:n}=t();return n!=null&&n.models?n.models.filter(o=>o.reference.provider===s):[]}})),IS=Object.freeze(Object.defineProperty({__proto__:null,useProviderStore:ze},Symbol.toStringTag,{value:"Module"})),vu="copilot_auto_generate_titles",qs=ds.getInstance(),gr=gi()[0],$S=(gr==null?void 0:gr.id)||"general_assistant";var df;const $f=((df=gr==null?void 0:gr.content)==null?void 0:df.trim())||"",sl="tool",wu=e=>{if(typeof e!="string"||!e.trim())return null;const t=Date.parse(e);return Number.isFinite(t)?t:null},DS=()=>{try{const e=globalThis.crypto;if(e!=null&&e.randomUUID)return e.randomUUID()}catch{}return`id_${Date.now()}_${Math.random().toString(16).slice(2)}`},LS=()=>{let e=Mr().trim().replace(/\/+$/,"");return e.endsWith("/v1")&&(e=e.slice(0,-3)),`${e}/api/v1`},Df=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}},OS=e=>{const t=Df(e);return t?`${LS()}/sessions/${encodeURIComponent(t.sessionId)}/attachments/${encodeURIComponent(t.attachmentId)}`:e},Rn=e=>{if(typeof e!="string")return;const t=e.trim();if(t&&t.toLowerCase()!=="unknown")return t},FS=e=>{const t=(e||"").trim();if(!t)return;const s=t.match(/tool policy blocked ['"`]([^'"`]+)['"`]/i);if(s!=null&&s[1])return Rn(s[1]);try{const n=JSON.parse(t);if(typeof(n==null?void 0:n.tool_name)=="string")return Rn(n.tool_name)}catch{}},ac=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,subagentType:e.subagent_type??null,title:e.title||is.t("chat.session.defaultTitle"),createdAt:t,pinned:e.pinned,messages:[],config:{systemPromptId:$S,baseSystemPrompt:$f,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}},zS=(e,t)=>{var a,i,l,c,u;const s=new Map,n=new Map;for(const d of t)d.role==="tool"&&d.tool_call_id&&d.metadata&&n.set(d.tool_call_id,d.metadata);const o=[];for(const d of t){const h=d.created_at||new Date().toISOString();if(d.role==="system"){const p={role:"system",id:d.id,createdAt:h,content:d.content||"",isCompressed:!!d.compressed,compressedEventId:d.compressed_by_event_id};o.push(p);continue}if(d.role==="user"){const p=new Map;for(const g of d.image_ocr||[]){const S=(a=g.image_url)==null?void 0:a.trim();if(!S)continue;const x=(g.lines||[]).map(T=>((T==null?void 0:T.text)||"").trim()).filter(Boolean);p.set(S,{ocrText:x.length?x.join(`
12
- `):void 0,ocrError:g.error?String(g.error):void 0})}const f=[];for(const g of d.content_parts||[]){if(g.type!=="image_url")continue;const S=((i=g.image_url)==null?void 0:i.url)||"";if(!S)continue;const v=OS(S),x=Df(S),T=p.get(S.trim());f.push({id:DS(),url:v,ocrText:T==null?void 0:T.ocrText,ocrError:T==null?void 0:T.ocrError,name:x?`attachment-${x.attachmentId}`:"image",size:0,type:"image/*"})}const y={role:"user",id:d.id,createdAt:h,content:d.content||"",images:f.length?f:void 0,isCompressed:!!d.compressed,compressedEventId:d.compressed_by_event_id};o.push(y);continue}if(d.role==="assistant"){const p=d.tool_calls||[];if(p.length>0){const g=(d.content||"").trim(),S=typeof d.reasoning=="string"&&d.reasoning.trim().length>0;if(g||S){const _=S?{reasoning:d.reasoning,backendMessageId:d.id}:{backendMessageId:d.id},j={role:"assistant",type:"text",id:`${d.id}_text`,createdAt:h,content:d.content||"",metadata:_,isCompressed:!!d.compressed,compressedEventId:d.compressed_by_event_id};o.push(j)}for(const _ of p)_.id&&s.set(_.id,Rn((l=_.function)==null?void 0:l.name)||sl);const v=(c=p[0])==null?void 0:c.id,x=v?n.get(v):void 0,T={role:"assistant",type:"tool_call",id:d.id,createdAt:h,toolCalls:p.map(_=>{var j;return{toolCallId:_.id,toolName:Rn((j=_.function)==null?void 0:j.name)||sl,parameters:(()=>{var P,M;try{return JSON.parse(((P=_.function)==null?void 0:P.arguments)||"{}")}catch{return{raw:((M=_.function)==null?void 0:M.arguments)||""}}})(),streamingOutput:""}}),...x?{metadata:x}:{},isCompressed:!!d.compressed,compressedEventId:d.compressed_by_event_id};o.push(T);continue}const f=typeof d.reasoning=="string"&&d.reasoning.trim().length>0?{reasoning:d.reasoning}:{},y={role:"assistant",type:"text",id:d.id,createdAt:h,content:d.content||"",metadata:f,isCompressed:!!d.compressed,compressedEventId:d.compressed_by_event_id};o.push(y);continue}if(d.role==="tool"){const p=((u=d.tool_call_id)==null?void 0:u.trim())||`orphan-tool-call:${d.id}`,f=Rn(s.get(p))||Rn(d.tool_name)||Rn(d.name)||FS(d.content)||sl,y=d.tool_success===!1||d.tool_success==null&&typeof d.content=="string"&&d.content.trimStart().startsWith("Error:"),g={role:"assistant",type:"tool_result",id:d.id,createdAt:h,toolName:f,toolCallId:p,result:{tool_name:f,result:d.content||"",display_preference:"Default"},isError:y,isCompressed:!!d.compressed,compressedEventId:d.compressed_by_event_id};o.push(g);continue}}return o},NS=750,mt={inFlight:null,timer:null,trailingPromise:null,trailingResolve:null,trailingReject:null};function BS(e,t){const s=e.map(ac);t(n=>{const o=new Set(n.processingChats);s.forEach(l=>{l.isRunning&&o.add(l.id)});const a=new Map(n.chats.map(l=>[l.id,l])),i=s.map(l=>{var x,T,_,j;const c=a.get(l.id);if(!c)return l;const u=wu(c.updatedAt),d=wu(l.updatedAt),h=u!==null&&d!==null&&u>d,p=c.config||{},f=l.config||{},y=Object.prototype.hasOwnProperty.call(p,"model"),g=Object.prototype.hasOwnProperty.call(p,"model_ref"),S=Object.prototype.hasOwnProperty.call(p,"reasoningEffort"),v=Math.max(c.messageCount??0,l.messageCount??0);return{...l,title:h?c.title:l.title,pinned:h?c.pinned:l.pinned,updatedAt:h?c.updatedAt:l.updatedAt,messages:c.messages,messageCount:v,config:{...p,...f,model:h&&y?p.model:f.model,model_ref:h&&g?p.model_ref:f.model_ref,reasoningEffort:h&&S?p.reasoningEffort:f.reasoningEffort,compressionEvents:((x=c.config)==null?void 0:x.compressionEvents)??((T=l.config)==null?void 0:T.compressionEvents),syncCursor:((_=c.config)==null?void 0:_.syncCursor)??((j=l.config)==null?void 0:j.syncCursor)}}});return{...n,chats:i,processingChats:o}})}async function _u(e){return mt.inFlight||(mt.inFlight=(async()=>{try{const t=await qs.listSessions();BS(t.sessions,e)}catch(t){throw console.error("[ChatSlice] Failed to refresh sessions:",t),t}})().finally(()=>{mt.inFlight=null})),mt.inFlight}const WS=(e,t)=>({chats:[],currentSessionId:null,latestActiveSessionId:null,processingChats:new Set,autoGenerateTitles:!0,isUpdatingAutoTitlePreference:!1,subSessionsByParent:{},pendingQuestionsBySession:{},addChat:async s=>{var p,f,y,g,S,v,x,T,_,j,P,M;const n=(s.title||is.t("chat.sidebar.newSession")).trim(),o=((f=(p=s.config)==null?void 0:p.baseSystemPrompt)==null?void 0:f.trim())||"",a=(y=ze.getState().getActiveModel())==null?void 0:y.trim(),i=((S=(g=s.config)==null?void 0:g.model)==null?void 0:S.trim())||a||void 0,l=((v=s.config)==null?void 0:v.reasoningEffort)??void 0;let c,u;if(ze.getState().isProviderModelRefEnabled()){const R=(x=s.config)==null?void 0:x.model_ref;if((T=R==null?void 0:R.provider)!=null&&T.trim()&&((_=R==null?void 0:R.model)!=null&&_.trim()))c=R,u=R.provider;else{const E=(j=ze.getState().providerConfig.defaults)==null?void 0:j.chat;if((P=E==null?void 0:E.provider)!=null&&P.trim()&&((M=E==null?void 0:E.model)!=null&&M.trim()))c=E,u=E.provider;else{const C=ze.getState().getActiveModel();C&&(c={provider:ze.getState().currentProvider,model:C},u=ze.getState().currentProvider)}}}const d=await qs.createSession({title:n,system_prompt:o||void 0,model:i,model_ref:c,provider:u,reasoning_effort:l||void 0}),h={...ac(d.session),title:n,config:{...s.config,model:d.session.model,model_ref:d.session.model_ref??null,reasoningEffort:d.session.reasoning_effort??null,baseSystemPrompt:o||$f},messages:[],currentInteraction:null};return e(R=>{const E=[h,...R.chats.filter(C=>C.id!==h.id)];return{...R,chats:E,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 qs.deleteSession(s)}catch(n){console.error(`[ChatSlice] Failed to delete backend session ${s}:`,n)}e(n=>{var c;const o=new Set;for(const u of n.chats)u.id===s&&o.add(u.id),u.rootSessionId===s&&o.add(u.id);const a=n.chats.filter(u=>!o.has(u.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(u=>{const d=u.chats.map(h=>h.id===s?{...h,...n,...l?{updatedAt:l}:{}}:h);return{...u,chats:d}});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")&&ze.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 u=n.config.reasoningEffort;u?c.reasoning_effort=u:c.clear_reasoning_effort=!0}Object.keys(c).length>0&&qs.patchSession(s,c).catch(u=>{console.warn(`[ChatSlice] Failed to patch session ${s}:`,u)})},persistSessionTitle:async(s,n)=>{var a;const o=(a=t().chats.find(i=>i.id===s))==null?void 0:a.title;e(i=>({...i,chats:i.chats.map(l=>l.id===s?{...l,title:n,updatedAt:new Date().toISOString()}:l)}));try{await qs.patchSession(s,{title:n})}catch(i){throw typeof o=="string"&&e(l=>({...l,chats:l.chats.map(c=>c.id===s?{...c,title:o}:c)})),console.warn(`[ChatSlice] persistSessionTitle failed for ${s}:`,i),i}},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(u=>{Object.prototype.hasOwnProperty.call(c,u)&&(c[u]=o[u])}),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 qs.deleteSessionMessage(s,n)}catch(a){return console.warn(`[ChatSlice] Failed to delete message ${n} from session ${s}:`,a),a instanceof Yn?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()=>mt.inFlight?mt.inFlight:mt.timer?(mt.trailingPromise||(mt.trailingPromise=new Promise((s,n)=>{mt.trailingResolve=s,mt.trailingReject=n})),mt.trailingPromise):(mt.timer=setTimeout(()=>{if(mt.timer=null,mt.trailingPromise){const s=mt.trailingResolve,n=mt.trailingReject;mt.trailingPromise=null,mt.trailingResolve=null,mt.trailingReject=null,_u(e).then(s,n)}},NS),_u(e)),loadChats:async()=>{var c,u,d;const s=localStorage.getItem(vu),n=s===null?t().autoGenerateTitles:s==="true";let o=await qs.listSessions();if(!o.sessions||o.sessions.length===0){const h=(c=ze.getState().getActiveModel())==null?void 0:c.trim(),p=(u=ze.getState().providerConfig.defaults)==null?void 0:u.chat;o={sessions:[(await qs.createSession({title:is.t("chat.sidebar.newSession"),model:h,model_ref:p,provider:p==null?void 0:p.provider})).session]}}const a=o.sessions.map(ac),i=((d=a[0])==null?void 0:d.id)??null,l=a.filter(h=>h.isRunning).map(h=>h.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,u,d,h,p,f;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 g=t().chats.find(T=>T.id===s);if(!g)return;const S=await qs.getHistory(s),v=(l=S.messages[S.messages.length-1])==null?void 0:l.role;if(n!=null&&n.waitForAssistant&&v==="user"&&y<a){const T=i>0?i*(y+1):200*(y+1);await new Promise(_=>setTimeout(_,T));continue}const x=zS(s,S.messages);if(o==="monotonic"){const T=g.messages||[],_=T.length,j=x.length,P=(c=x[x.length-1])==null?void 0:c.role,M=(u=T[T.length-1])==null?void 0:u.role,R=T[T.length-1],E=x[x.length-1],C=R==null?void 0:R.id,k=E==null?void 0:E.id;let b=!1;if(j>_?b=!0:j===_&&(b=M==="user"&&P!=="user"||typeof C=="string"&&typeof k=="string"&&C!==k),!b){t().updateSession(s,{messageCount:Math.max(g.messageCount??0,S.messages.length)});return}}t().updateSession(s,{messages:x,messageCount:S.messages.length,config:{...g.config||{},compressionEvents:(S.compression_events||[]).map(T=>({id:T.id,createdAt:T.created_at,messagesCompressed:T.messages_compressed,segmentsRemoved:T.segments_removed})),syncCursor:{messageCount:S.messages.length,lastMessageId:((d=S.messages[S.messages.length-1])==null?void 0:d.id)??null,hasPendingQuestion:((h=t().pendingQuestionRespond)==null?void 0:h.sessionId)===s,pendingQuestionToolCallId:((p=t().pendingQuestionRespond)==null?void 0:p.sessionId)===s?((f=t().pendingQuestionRespond)==null?void 0:f.toolCallId)??null:null}}});return}catch(g){if(y>=a){console.warn(`[ChatSlice] Failed to load history for ${s}:`,g);return}const S=i>0?i*(y+1):200*(y+1);await new Promise(v=>setTimeout(v,S))}},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(vu,String(s))}catch(o){throw console.warn("[ChatSlice] Failed to update auto-title preference:",o),e({autoGenerateTitles:n}),o}finally{e({isUpdatingAutoTitlePreference:!1})}},setPendingQuestionForSession:s=>{e(n=>({pendingQuestionsBySession:{...n.pendingQuestionsBySession,[s.sessionId]:s}}))},clearPendingQuestionForSession:s=>{e(n=>{const o={...n.pendingQuestionsBySession};return delete o[s],{pendingQuestionsBySession:o}})}});class ic extends Error{constructor(s="Proxy authentication required"){super(s);Je(this,"code","proxy_auth_required");this.name="ProxyAuthRequiredError"}}const Dn=class Dn{constructor(){}static getInstance(){return Dn.instance||(Dn.instance=new Dn),Dn.instance}resolveOpenAICompatBaseUrl(){const t=Mr().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 fd({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 Yn){if(n.status===428)throw new ic(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 ic(((s=o.error)==null?void 0:s.message)||n.message)}throw n}}};Je(Dn,"instance");let lc=Dn;const Lf=lc.getInstance(),US=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)},qS=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")},us=async e=>{try{await US(e);return}catch(t){try{qS(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 HS{async copyToClipboard(t){await us(t)}async getBambooConfig(){try{return await je.get("bamboo/config")}catch(t){return console.error("Failed to fetch Bamboo config:",t),{}}}async getBambooTools(){try{return await je.get("bamboo/tools")}catch(t){return console.error("Failed to fetch Bamboo tools:",t),{tools:[]}}}async getModelLimitDefaults(){try{return await je.get("bamboo/model-limits/defaults")}catch(t){return console.error("Failed to fetch model limit defaults:",t),{model_limits:[]}}}async setBambooConfig(t){return je.post("bamboo/config",t)}async validateBambooConfigPatch(t){return je.post("bamboo/config/validate",t)}async setProxyAuth(t){return je.post("bamboo/proxy-auth",t)}async getProxyAuthStatus(){try{return await je.get("bamboo/proxy-auth/status")}catch(t){return console.error("Failed to fetch proxy auth status:",t),{configured:!1,username:null}}}async clearProxyAuth(){return je.post("bamboo/proxy-auth",{username:"",password:""})}async resetBambooConfig(){return je.post("bamboo/config/reset",{})}async saveWorkflow(t,s){return je.post("bamboo/workflows",{name:t,content:s})}async deleteWorkflow(t){return je.delete(`bamboo/workflows/${encodeURIComponent(t)}`)}async getKeywordMaskingConfig(){try{return await je.get("bamboo/keyword-masking")}catch(t){return console.error("Failed to fetch keyword masking config:",t),{entries:[]}}}async updateKeywordMaskingConfig(t){return je.post("bamboo/keyword-masking",t)}async validateKeywordEntries(t){return je.post("bamboo/keyword-masking/validate",t)}async getSetupStatus(){return await je.get("bamboo/setup/status")}async markSetupComplete(){return je.post("bamboo/setup/complete",{})}async resetSetupStatus(){await je.post("bamboo/setup/incomplete",{})}async getAccessStatus(){return je.get("bamboo/access/status")}async verifyAccessPassword(t){return je.post("bamboo/access/verify",{password:t})}async updateAccessPassword(t){return je.post("bamboo/access/password",t)}}const Ln=class Ln{constructor(){Je(this,"httpUtilityService",new HS)}static getInstance(){return Ln.instance||(Ln.instance=new Ln),Ln.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)}};Je(Ln,"instance");let vs=Ln;const ot=vs.getInstance();let Ir=null,$r=null;const nl=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,bs=yn((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(Ir)return Ir;Ir=(async()=>{e({isLoadingConfig:!0,error:null});try{const o=await ot.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 Ir}finally{Ir=null}},saveConfig:async s=>{e({isLoadingConfig:!0,error:null,config:s});try{const n=await ot.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($r)return $r;$r=(async()=>{e({isLoadingProxyAuthStatus:!0,error:null});try{const o=await ot.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 $r}finally{$r=null}},applyProxyAuth:async s=>{await ot.setProxyAuth(s),await t().loadProxyAuthStatus({force:!0})},clearProxyAuth:async()=>{await ot.clearProxyAuth(),await t().loadProxyAuthStatus({force:!0})}}));let Dr=null;const YS=(e,t)=>({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:null,configModel:void 0,setSelectedModel:s=>{e({selectedModel:s})},loadConfigModel:async()=>{try{const s=await bs.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(Dr)return Dr;Dr=(async()=>{e({isLoadingModels:!0,modelsError:null});try{try{if(!(await ot.getSetupStatus()).is_complete){it("[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 Lf.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 ic){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 Dr}finally{Dr=null}}}),XS=["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}),dn=class dn{constructor(){Je(this,"deprecatedKeysCleanupDone",!1)}static getInstance(){return dn.instance||(dn.instance=new dn),dn.instance.cleanupDeprecatedPromptStorageKeys(),dn.instance}cleanupDeprecatedPromptStorageKeys(){if(!this.deprecatedKeysCleanupDone){this.deprecatedKeysCleanupDone=!0;try{for(const t of XS)localStorage.removeItem(t)}catch(t){console.warn("[SystemPromptService] Failed to cleanup deprecated prompt storage keys:",t)}}}async getSystemPromptPresets(){try{const t=await we.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 we.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 we.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 we.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)||""}};Je(dn,"instance");let yi=dn;const Tu="copilot_last_selected_prompt_id",Of="copilot_custom_system_prompts_v2",Ff="copilot_custom_system_prompts_v2_migrated_to_backend",zf="general_assistant",gd=80,mr=yi.getInstance();let Ca=null;function yd(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,gd)}function Nf(e){if(typeof e!="string")return null;const t=e.toLowerCase().trim().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");return t?t.slice(0,gd):null}function Bf(e,t){if(!t.has(e))return e;let s=2;for(;;){const n=`_${s}`,a=`${e.slice(0,Math.max(0,gd-n.length))}${n}`;if(!t.has(a))return a;s+=1}}function Wf(){try{const e=localStorage.getItem(Of);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=Nf(o==null?void 0:o.id)||yd(a),u=Bf(c,s);u!==zf&&(s.add(u),n.push({id:u,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 Uf(){try{return localStorage.getItem(Ff)==="1"}catch(e){return console.error("[promptSlice] Failed to read migration marker:",e),!1}}function ku(){try{localStorage.setItem(Ff,"1")}catch(e){console.error("[promptSlice] Failed to write migration marker:",e)}}function ju(){try{localStorage.removeItem(Of)}catch(e){console.error("[promptSlice] Failed to clear legacy custom prompts:",e)}}async function VS(){var o,a;if(Uf())return;const e=Wf();if(e.length===0){ju(),ku();return}const t=await mr.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===zf||i.isDefault)continue;const u=Nf(i.id)||yd(l),d=Bf(u,s);try{const h=await mr.createSystemPromptPreset({id:d,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||(ju(),ku())}async function KS(){Ca||(Ca=VS().finally(()=>{Ca=null})),await Ca}const GS=(e,t)=>({systemPrompts:[],lastSelectedPromptId:localStorage.getItem(Tu)||null,loadSystemPrompts:async()=>{try{await KS()}catch(o){console.warn("[promptSlice] Legacy prompt migration skipped:",o)}let s=[];try{s=await mr.getSystemPromptPresets()}catch(o){console.error("Failed to load system prompts from backend:",o)}let n=s.length?s:gi();if(!Uf()){const o=Wf();n=JS(n,o)}n.length===0&&(n=gi()),e({systemPrompts:n})},addSystemPrompt:async s=>{try{await mr.createSystemPromptPreset({id:yd(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 mr.updateSystemPromptPreset(s),await t().loadSystemPrompts()}catch(n){throw console.error("Failed to update system prompt:",n),n}},deleteSystemPrompt:async s=>{try{await mr.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(Tu,s)}catch(n){console.error("Failed to save last selected prompt ID to localStorage:",n)}}}),JS=(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())},QS=(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 ZS{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 je.get(a)}async getSkill(t){return je.get(`skills/${t}`)}async getFilteredTools(t){const s=t?`?session_id=${encodeURIComponent(t)}`:"";return(await je.get(`skills/filtered-tools${s}`)).tools??[]}}const cc=new ZS,ev=(e,t)=>({skills:[],isLoadingSkills:!1,skillsError:null,loadSkills:async(s,n)=>{e({isLoadingSkills:!0,skillsError:null});try{const o=await cc.listSkills(s,n);e({skills:o.skills,isLoadingSkills:!1})}catch(o){e({skillsError:o instanceof Error?o.message:is.t("components.skillManager.loadFailed"),isLoadingSkills:!1})}},getSkill:async s=>{e({isLoadingSkills:!0,skillsError:null});try{const n=await cc.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:is.t("components.skillManager.getFailed"),isLoadingSkills:!1})}},clearSkillsError:()=>{e({skillsError:null})}}),tv=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}})}),sv=(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,...u}=n.activeItems,{[s]:d,...h}=n.evaluationStates;return{taskLists:a,taskListVersions:l,activeItems:u,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}})}),dc=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:dc(s),allowCustom:n??!0,toolCallId:o??null}),nv=(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=dc(e.options),n=dc(t.options);return s.length!==n.length?!1:s.every((o,a)=>o===n[a])},qf="chat_input_reasoning_by_session_v1",Hf="chat_input_reasoning_last_used_v1",Cu={content:"",referenceText:null,attachments:[],reasoningEffort:"medium"},bd=e=>e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max",Yf=()=>{if(typeof window>"u")return{};try{const e=localStorage.getItem(qf);if(!e)return{};const t=JSON.parse(e),s={};for(const[n,o]of Object.entries(t||{}))bd(o)&&(s[n]=o);return s}catch{return{}}},rv=e=>{if(!(typeof window>"u"))try{localStorage.setItem(qf,JSON.stringify(e))}catch{}},ov=()=>{if(!(typeof window>"u"))try{const e=localStorage.getItem(Hf);return bd(e)?e:void 0}catch{return}},av=e=>{if(!(typeof window>"u"))try{localStorage.setItem(Hf,e)}catch{}},xd=e=>{const t=Yf();return bd(t[e])?t[e]:ov()},Lr=e=>({...Cu,reasoningEffort:xd(e)??Cu.reasoningEffort}),iv=(e,t)=>({inputStates:{},pendingQuestionRespond:null,setInputContent:(s,n)=>e(o=>({inputStates:{...o.inputStates,[s]:{...o.inputStates[s]||Lr(s),content:n}}})),setReferenceText:(s,n)=>e(o=>({inputStates:{...o.inputStates,[s]:{...o.inputStates[s]||Lr(s),referenceText:n}}})),setAttachments:(s,n)=>e(o=>({inputStates:{...o.inputStates,[s]:{...o.inputStates[s]||Lr(s),attachments:n}}})),setInputReasoningEffort:(s,n)=>{e(a=>({inputStates:{...a.inputStates,[s]:{...a.inputStates[s]||Lr(s),reasoningEffort:n}}}));const o=Yf();o[s]=n,rv(o),av(n)},clearInputState:s=>e(n=>{const{[s]:o,...a}=n.inputStates;return{inputStates:a}}),getInputState:s=>t().inputStates[s]||Lr(s),setPendingQuestionRespond:s=>e(n=>nv(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}})}),lv="bamboo_proxy_auth",cv=()=>{try{const e=localStorage.getItem(lv);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}},dv="auto",uv="required",mv=1e4,hv=2e3,pv=ds.getInstance();let Mu=null,Or=null,Pu=null,Fr=null;const Eu=new WeakMap,L=yn()(hS(fS((e,t,s)=>({...WS(e,t),...YS(e,t),...GS(e,t),...QS(e,t),...ev(e,t),...tv(e),...sv(e,t),...iv(e,t),agentAvailability:null,setAgentAvailability:n=>{e({agentAvailability:n})},checkAgentAvailability:async()=>{if(Or)return Or;Or=(async()=>{const n=await pv.healthCheck();return t().agentAvailability!==n&&e({agentAvailability:n}),n})();try{return await Or}finally{Or=null}},startAgentHealthCheck:()=>{Mu||(t().checkAgentAvailability(),Mu=setInterval(()=>{t().checkAgentAvailability()},mv))},refreshSessionsIndex:async()=>{if(Fr)return Fr;Fr=(async()=>{try{await t().refreshChats()}catch(n){console.warn("[AppStore] refreshChats failed:",n)}})();try{return await Fr}finally{Fr=null}},startSessionsIndexSync:()=>{Pu||(t().refreshSessionsIndex(),Pu=setInterval(()=>{t().refreshSessionsIndex()},hv))}})),{name:"AppStore"})),Xf=e=>{const t=Eu.get(e);if(t)return t;const s=new Map(e.map(n=>[n.id,n]));return Eu.set(e,s),s},bn=e=>t=>e?Xf(t.chats).get(e)??null:null,Sd=e=>e.currentSessionId?Xf(e.chats).get(e.currentSessionId)??null:null,fv=e=>{var t;return((t=Sd(e))==null?void 0:t.messages)??[]},Ru=async()=>{const e=cv();if(!e)return!1;try{return await ot.setProxyAuth(e),!0}catch(t){return console.error("Failed to apply stored proxy auth during startup:",t),!1}},gv=async()=>{try{const e=await bs.getState().loadConfig();if((typeof(e==null?void 0:e.proxy_auth_mode)=="string"?e.proxy_auth_mode:dv)!==uv)return await Ru(),!1;const s=await bs.getState().loadProxyAuthStatus({force:!0});return s!=null&&s.configured||await Ru()?!1:(L.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 Au=!1;const Vf=async(e=!1)=>{if(Au&&!e)return;Au=!0,L.getState().startAgentHealthCheck(),await ze.getState().loadProviderConfig(),await L.getState().loadChats(),await gv()||await L.getState().fetchModels(),await L.getState().loadSystemPrompts()},yv=Object.freeze(Object.defineProperty({__proto__:null,initializeStore:Vf,selectCurrentChat:Sd,selectCurrentMessages:fv,selectSessionById:bn,useAppStore:L},Symbol.toStringTag,{value:"Module"})),Xn={'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:Iu,Paragraph:bv}=pe,xv=({content:e,token:t,showGradient:s,onClick:n})=>r.jsx(te,{size:"small",style:{marginLeft:t.marginLG,marginTop:t.marginXS,backgroundColor:t.colorBgLayout,borderColor:t.colorBorderSecondary},styles:{body:{padding:t.paddingMD}},onClick:n,children:r.jsxs("div",{style:{maxHeight:"60vh",overflowY:"auto",position:"relative",paddingRight:t.paddingXS},children:[r.jsx(xs,{remarkPlugins:[Ii],components:{p:({children:o})=>r.jsx(bv,{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(Iu,{strong:!0,style:{fontSize:t.fontSizeHeading3,marginBottom:t.marginSM,display:"block"},children:o}),h2:({children:o})=>r.jsx(Iu,{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(br,{style:Xn,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:Sv}=pe,vv=({prompt:e,token:t,isSelected:s,isExpanded:n,onSelect:o,onToggleExpand:a,onCopy:i})=>{const{t:l}=ie(),c=e.content||"",{nonEmptyLineCount:u,wordCount:d,characterCount:h,showGradient:p}=m.useMemo(()=>{const y=(c?c.split(/\r?\n/):[]).filter(v=>v.trim().length>0).length,g=c.trim()?c.trim().split(/\s+/).filter(Boolean).length:0,S=c.length;return{nonEmptyLineCount:y,wordCount:g,characterCount:S,showGradient:!n&&S>600}},[c,n]);return r.jsx(lt.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(U,{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(U,{align:"start",children:[r.jsx(ls,{checked:s,onChange:()=>o(e.id),onClick:f=>f.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(ue,{color:"warning",children:l("chat.systemPromptSelector.defaultTag")}):null]}),r.jsxs(U,{size:"small",children:[r.jsx(B,{type:"text",size:"small",icon:n?r.jsx(lx,{}):r.jsx(sd,{}),onClick:f=>{f.stopPropagation(),a(e.id)},children:l(n?"chat.systemPromptSelector.hide":"chat.systemPromptSelector.preview")}),r.jsx(B,{type:"text",size:"small",icon:r.jsx(cs,{}),onClick:f=>i(f,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(U,{size:"small",wrap:!0,style:{marginLeft:t.marginLG},children:[r.jsx(ue,{color:"processing",children:l("chat.systemPromptSelector.lines",{count:u})}),r.jsx(ue,{color:"purple",children:l("chat.systemPromptSelector.words",{count:d})}),r.jsx(ue,{color:"success",children:l("chat.systemPromptSelector.chars",{count:h})})]}),n?r.jsx(xv,{content:c,token:t,showGradient:p,onClick:f=>f.stopPropagation()}):r.jsx(Sv,{type:"secondary",ellipsis:{rows:3},style:{marginLeft:t.marginLG,marginBottom:0,color:t.colorTextSecondary},children:c||l("chat.systemPromptSelector.noContent")})]})},e.id)},{Text:wv}=pe,{useToken:_v}=xe,Tv=({open:e,onClose:t,onSelect:s,prompts:n,title:o,showCancelButton:a=!0})=>{const{t:i}=ie(),{token:l}=_v(),[c,u]=fn.useMessage(),d=L(j=>j.lastSelectedPromptId),h=L(j=>j.setLastSelectedPromptId),[p,f]=m.useState(null),[y,g]=m.useState(null),S=m.useMemo(()=>n.filter(j=>j.id&&j.id.trim()!==""),[n]),v=async(j,P)=>{j.stopPropagation();const M=P.content??"";try{await us(M),c.success(i("success.promptCopied",{name:P.name}))}catch(R){console.error("[SystemPromptSelector] Failed to copy prompt:",R),c.error(i("error.copyPromptFailed"))}},x=o??i("chat.prompt.selectorTitle");m.useEffect(()=>{if(e){const j=S.find(M=>M.isDefault),P=d||(j==null?void 0:j.id)||(S.length>0?S[0].id:null);f(P)}},[e,d,S.length]);const T=j=>{f(j.id),h(j.id),s(j),t()},_=()=>{t()};return r.jsxs(r.Fragment,{children:[u,r.jsxs(Bt,{title:r.jsxs(U,{children:[r.jsx(Tr,{}),x]}),open:e,onCancel:_,width:700,footer:r.jsx(nS,{buttons:[...a?[rS(_)]:[],oS(()=>{const j=S.find(P=>P.id===p);j&&T(j)},{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(wv,{type:"secondary",style:{fontSize:l.fontSizeSM},children:i("chat.prompt.helperText")})}),S.length===0?r.jsx(Pt,{description:i("chat.prompt.emptyDescription"),style:{margin:l.marginLG}}):r.jsx("div",{children:S.map(j=>r.jsx(vv,{prompt:j,token:l,isSelected:p===j.id,isExpanded:y===j.id,onSelect:P=>f(P),onToggleExpand:P=>g(y===P?null:P),onCopy:v},j.id))})]})]})},kv=({chat:e,isSelected:t,onSelect:s,onDelete:n,onPin:o,onUnpin:a,onEdit:i,onGenerateTitle:l,onRunProjectDream:c,isGeneratingTitle:u,isRunningProjectDream:d,titleGenerationError:h})=>{const{t:p}=ie(),[f,y]=m.useState(!1),[g,S]=m.useState(e.title),[v,x]=m.useState(!1),[T,_]=m.useState(!1),{token:j}=xe.useToken(),P=m.useCallback(w=>{w.stopPropagation(),i&&g.trim()&&i(e.id,g.trim()),y(!1)},[e.id,g,i]),M=m.useCallback(w=>{w.stopPropagation(),S(e.title),y(!1)},[e.title]),R=[{key:"pin",icon:e.pinned?r.jsx(sc,{style:{color:j.colorWarning}}):r.jsx(nd,{}),label:e.pinned?p("chat.actions.unpin"):p("chat.actions.pin"),onClick:({domEvent:w})=>{w.stopPropagation(),e.pinned?a(e.id):o(e.id)}},{key:"edit",icon:r.jsx(ca,{}),label:p("chat.chatItem.edit"),onClick:({domEvent:w})=>{w.stopPropagation(),y(!0)}},...l?[{key:"generate-title",icon:u?r.jsx(xr,{}):r.jsx(bf,{style:h?{color:j.colorError}:void 0}),label:h||p("chat.actions.generateTitle"),disabled:u,onClick:({domEvent:w})=>{w.stopPropagation(),l(e.id)}}]:[],...c?[{key:"run-project-dream",icon:d?r.jsx(xr,{}):r.jsx(cx,{}),label:p("chat.actions.runProjectDream"),disabled:d,onClick:({domEvent:w})=>{w.stopPropagation(),c(e.id)}}]:[],{type:"divider"},{key:"delete",icon:r.jsx(gn,{}),label:p("common.delete"),danger:!0,onClick:({domEvent:w})=>{w.stopPropagation(),n(e.id)}}],E={padding:"8px 12px",borderRadius:j.borderRadiusSM,marginBottom:j.marginXXS,cursor:"pointer",transition:"all 0.2s cubic-bezier(0.4, 0, 0.2, 1)",backgroundColor:t?"var(--lotus-primary-soft)":v||T?"var(--lotus-item-hover-bg)":"transparent",border:"1px solid transparent",borderColor:t?"var(--lotus-tool-card-border)":v||T?j.colorBorderSecondary:"transparent",position:"relative",overflow:"visible",boxShadow:t?"var(--lotus-tool-card-shadow)":"none",transform:v&&!t?"translateX(2px)":"none"},C={flex:1,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",fontSize:13,fontWeight:t?600:500,color:t?"var(--lotus-primary)":j.colorText},k={flex:1,fontSize:j.fontSizeSM,marginRight:j.marginSM},b=f?[r.jsx(B,{type:"text",size:"small",icon:r.jsx(dx,{style:{color:j.colorSuccess}}),onClick:P,"aria-label":p("common.save")},"save"),r.jsx(B,{type:"text",size:"small",icon:r.jsx(kr,{style:{color:j.colorError}}),onClick:M,"aria-label":p("common.cancel")},"cancel")]:v||T?[r.jsx(qn,{menu:{items:R,className:"lotus-sidebar-actions-menu"},trigger:["click"],placement:"bottomRight",overlayClassName:"lotus-sidebar-actions-dropdown",open:T,onOpenChange:w=>_(w),children:r.jsx(B,{type:"text",size:"small",icon:r.jsx(ux,{}),"aria-label":p("common.moreActions","More actions"),onClick:w=>w.stopPropagation(),style:{color:j.colorTextSecondary,borderRadius:j.borderRadiusSM,background:j.colorFillTertiary,width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center"}})},"more")]:[];return r.jsx(lt.Item,{style:E,tabIndex:0,onClick:()=>!f&&s(e.id),onKeyDown:w=>{w.key==="Enter"&&!f?(w.preventDefault(),s(e.id)):(w.key==="Delete"||w.key==="Backspace")&&!f&&w.metaKey&&(w.preventDefault(),n(e.id))},onMouseEnter:()=>x(!0),onMouseLeave:()=>{T||x(!1)},onFocus:()=>x(!0),onBlur:()=>{T||x(!1)},actions:b,"data-testid":"chat-item",role:"option","aria-selected":t,"aria-label":e.title||p("chat.sidebar.untitledChat"),children:r.jsx(lt.Item.Meta,{title:f?r.jsx(be,{value:g,onChange:w=>S(w.target.value),onClick:w=>w.stopPropagation(),onPressEnter:w=>{w.preventDefault(),P(w)},autoFocus:!0,style:k,variant:"borderless",size:"small"}):r.jsxs("div",{style:{...C,display:"flex",alignItems:"center",gap:j.marginXS,minWidth:0},children:[e.pinned&&r.jsx(sc,{style:{color:j.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(ue,{color:"processing",style:{marginInlineEnd:0,flex:"0 0 auto"},children:p("chat.chatItem.childTag")}):null]})})})},jv=(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,uc=m.memo(kv,jv);uc.displayName="ChatItem";const $u=e=>({Today:0,Yesterday:1,"This Week":2,"This Month":3})[e]??4,Cv=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},Mv=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:$u(s)-$u(n)})},Pv=(e,t)=>e[t]?e[t].map(s=>s.id):[],Kf=(e,t)=>e[t]?e[t].length:0,Du=e=>e.pinned?"Pinned":e.createdByScheduleId?"Scheduled":new Date(e.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),Lu=(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},Ev=({groupedChatsByDate:e,childrenByRoot:t,expandedRootIds:s,onToggleRootExpanded:n,sortedDateKeys:o,expandedKeys:a,onCollapseChange:i,currentSessionId:l,onSelectChat:c,onDeleteChat:u,onDeleteByDate:d,onPinChat:h,onUnpinChat:p,onEditTitle:f,onGenerateTitle:y,onRunProjectDream:g,titleGenerationState:S,projectDreamState:v,token:x,hasActiveFilters:T})=>{const{t:_}=ie(),j=m.useMemo(()=>o.length?o.map(M=>{const R=e[M],E=Kf(e,M);return{dateKey:M,dateGroup:R,totalChatsInDate:E}}):[],[e,o]);if(!o.length)return r.jsx(Pt,{image:Pt.PRESENTED_IMAGE_SIMPLE,description:r.jsxs(U,{direction:"vertical",size:4,align:"center",children:[r.jsx("span",{style:{color:x.colorTextSecondary},children:T?_("chat.sidebar.empty.noMatches","No matching sessions"):_("chat.sidebar.empty.noSessions")}),r.jsx("span",{style:{color:x.colorTextSecondary,fontSize:12},children:T?_("chat.sidebar.empty.filterHint","Try adjusting your search or filters"):_("chat.sidebar.empty.hint")}),T&&r.jsx(B,{size:"small",type:"link",onClick:()=>{var R;const M=document.querySelector('[data-testid="sidebar-search-input"] input, .lotus-sidebar-search input');if(M){const E=(R=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value"))==null?void 0:R.set;E==null||E.call(M,""),M.dispatchEvent(new Event("input",{bubbles:!0}))}},children:_("chat.sidebar.empty.clearFilters","Clear filters")})]})});const P=new Set(a);return r.jsx(U,{direction:"vertical",size:"small",style:{width:"100%"},children:j.map(({dateKey:M,dateGroup:R,totalChatsInDate:E})=>{const C=P.has(M);return r.jsxs("div",{style:{borderRadius:x.borderRadiusSM,background:C?x.colorFillTertiary:"transparent",padding:4},children:[r.jsxs(V,{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":C,"aria-label":`${Lu(M,_)} (${E})`,onKeyDown:k=>{if(k.key==="Enter"||k.key===" "){k.preventDefault();const b=new Set(P);b.has(M)?b.delete(M):b.add(M),i(Array.from(b))}},onMouseEnter:k=>{k.currentTarget.style.background="var(--lotus-sidebar-item-hover-bg, rgba(204, 251, 241, 0.92))",k.currentTarget.style.borderColor="var(--lotus-sidebar-item-hover-border, rgba(13, 148, 136, 0.28))";const b=k.currentTarget.querySelector(".chat-sidebar-date-group-delete");b&&(b.style.opacity="1")},onMouseLeave:k=>{k.currentTarget.style.background="transparent",k.currentTarget.style.borderColor="transparent";const b=k.currentTarget.querySelector(".chat-sidebar-date-group-delete");b&&(b.style.opacity="0")},onClick:()=>{const k=new Set(P);k.has(M)?k.delete(M):k.add(M),i(Array.from(k))},className:"chat-sidebar-date-group-header",children:[r.jsxs(V,{align:"center",gap:"small",style:{minWidth:0},children:[C?r.jsx(Xt,{style:{fontSize:12,opacity:.6}}):r.jsx(Vs,{style:{fontSize:12,opacity:.6}}),r.jsxs("span",{style:{fontSize:12,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:M==="Today"?"var(--lotus-primary)":x.colorTextSecondary,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[Lu(M,_)," (",E,")"]})]}),r.jsx(B,{type:"text",size:"small",icon:r.jsx(gn,{}),className:"chat-sidebar-date-group-delete",style:{color:x.colorTextTertiary,opacity:0,transition:"opacity 0.2s ease"},onClick:k=>{k.stopPropagation(),d(M)}})]}),C?r.jsx("div",{style:{marginTop:4},children:r.jsx(lt,{itemLayout:"horizontal",dataSource:R,split:!1,renderItem:k=>{var b,w,A,I,$,W;return r.jsxs("div",{children:[r.jsxs(V,{align:"center",gap:6,children:[(b=t[k.id])!=null&&b.length?r.jsx(B,{size:"small",type:"text",style:{padding:0,width:22},"aria-label":s.has(k.id)?_("chat.sidebar.actions.collapseChildren"):_("chat.sidebar.actions.expandChildren"),onClick:O=>{O.preventDefault(),O.stopPropagation(),n(k.id)},children:s.has(k.id)?r.jsx(Xt,{}):r.jsx(Vs,{})}):r.jsx("div",{style:{width:22}}),r.jsx("div",{style:{flex:1,minWidth:0},children:r.jsx(uc,{chat:k,isSelected:k.id===l,onSelect:c,onDelete:u,onPin:h,onUnpin:p,onEdit:f,onGenerateTitle:y,onRunProjectDream:g,isGeneratingTitle:((w=S[k.id])==null?void 0:w.status)==="loading",isRunningProjectDream:((A=v[k.id])==null?void 0:A.status)==="loading",titleGenerationError:((I=S[k.id])==null?void 0:I.status)==="error"?($=S[k.id])==null?void 0:$.error:void 0})})]}),s.has(k.id)&&(((W=t[k.id])==null?void 0:W.length)??0)>0?r.jsx("div",{style:{marginLeft:22,marginTop:2},children:r.jsx(lt,{itemLayout:"horizontal",dataSource:t[k.id],split:!1,renderItem:O=>{var re,q,Z,X;return r.jsx("div",{style:{paddingLeft:12},children:r.jsx(uc,{chat:O,isSelected:O.id===l,onSelect:c,onDelete:u,onPin:h,onUnpin:p,onEdit:f,onGenerateTitle:y,onRunProjectDream:g,isGeneratingTitle:((re=S[O.id])==null?void 0:re.status)==="loading",isRunningProjectDream:((q=v[O.id])==null?void 0:q.status)==="loading",titleGenerationError:((Z=S[O.id])==null?void 0:Z.status)==="error"?(X=S[O.id])==null?void 0:X.error:void 0})},O.id)}})}):null]},k.id)}})}):null]},M)})})},Rv="copilot_ui_theme_v1";function Av(){var e;try{const t=localStorage.getItem(Rv);if(t==="light"||t==="dark")return t}catch{}return(e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}const Vn=yn(e=>({themeMode:Av(),setThemeMode:t=>e({themeMode:t}),toggleTheme:()=>e(t=>({themeMode:t.themeMode==="dark"?"light":"dark"}))})),Iv="2026.4.30",$v={version:Iv},vd=$v.version,{Text:Dv}=pe,Lv=({collapsed:e,onNewChat:t,onOpenSettings:s,screens:n,token:o})=>{const{t:a}=ie(),i=Vn(h=>h.themeMode),l=Vn(h=>h.toggleTheme),c=a("chat.sidebar.newSession"),u=a("settings.page.title"),d=i==="dark"?a("settings.app.lightMode","Light mode"):a("settings.app.darkMode","Dark mode");return r.jsxs(V,{vertical:!0,gap:e?"small":"middle",style:{padding:e?10:16,background:"transparent",borderTop:`1px solid ${o.colorBorderSecondary}`},children:[r.jsx(B,{"data-testid":"new-chat","data-tour-id":"new-session",type:"primary",icon:r.jsx(Ks,{}),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(V,{gap:8,align:"center",children:[r.jsx(B,{"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:u,"aria-label":u,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&&u}),!e&&r.jsx(Re,{title:d,placement:"top",children:r.jsx(B,{"data-testid":"toggle-theme",type:"text",icon:i==="dark"?r.jsx(mx,{}):r.jsx(hx,{}),onClick:l,"aria-label":d,className:"lotus-toolbar-icon",style:{width:44,height:44,borderRadius:o.borderRadiusLG,flexShrink:0}})})]}),!e&&r.jsxs(Dv,{type:"secondary","data-testid":"app-version-badge",style:{fontSize:o.fontSizeSM,textAlign:"center",userSelect:"text"},children:[a("settings.appTab.runningVersion","Running version"),": v",vd]})]})},Ou="provider",Xs=yn(e=>({isOpen:!1,origin:"chat",activeTabKey:Ou,open:(t,s=Ou)=>e({isOpen:!0,origin:t,activeTabKey:s}),close:()=>e({isOpen:!1}),setActiveTabKey:t=>e({activeTabKey:t})}));function Ce(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 z(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 Gf=function(){const{crypto:e}=globalThis;if(e!=null&&e.randomUUID)return Gf=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 mc(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const hc=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 Me extends Error{}class Mt extends Me{constructor(t,s,n,o){super(`${Mt.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:hc(s)});const a=s==null?void 0:s.error;return t===400?new Jf(t,a,n,o):t===401?new Qf(t,a,n,o):t===403?new Zf(t,a,n,o):t===404?new eg(t,a,n,o):t===409?new tg(t,a,n,o):t===422?new sg(t,a,n,o):t===429?new ng(t,a,n,o):t>=500?new rg(t,a,n,o):new Mt(t,a,n,o)}}class os extends Mt{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}}class Fi extends Mt{constructor({message:t,cause:s}){super(void 0,void 0,t||"Connection error.",void 0),s&&(this.cause=s)}}class wd extends Fi{constructor({message:t}={}){super({message:t??"Request timed out."})}}class Jf extends Mt{}class Qf extends Mt{}class Zf extends Mt{}class eg extends Mt{}class tg extends Mt{}class sg extends Mt{}class ng extends Mt{}class rg extends Mt{}class og extends Me{constructor(){super("Could not parse response content as the length limit was reached")}}class ag extends Me{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 Ov=/^[a-z][a-z0-9+.-]*:/i,Fv=e=>Ov.test(e);let Nt=e=>(Nt=Array.isArray,Nt(e)),Fu=Nt;function zv(e){return typeof e!="object"?{}:e??{}}function Nv(e){if(!e)return!0;for(const t in e)return!1;return!0}function Bv(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function al(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}const Wv=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new Me(`${e} must be an integer`);if(t<0)throw new Me(`${e} must be a positive integer`);return t},Uv=e=>{try{return JSON.parse(e)}catch{return}},ga=e=>new Promise(t=>setTimeout(t,e)),cr="5.10.2",qv=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Hv(){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 Yv=()=>{var s;const e=Hv();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":cr,"X-Stainless-OS":Nu(Deno.build.os),"X-Stainless-Arch":zu(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":cr,"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":cr,"X-Stainless-OS":Nu(globalThis.process.platform??"unknown"),"X-Stainless-Arch":zu(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=Xv();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":cr,"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":cr,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Xv(){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 zu=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",Nu=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 Bu;const Vv=()=>Bu??(Bu=Yv());function Kv(){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 ig(...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 lg(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return ig({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 cg(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 Gv(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 Jv=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),dg="RFC3986",ug=e=>String(e),Wu={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:ug},Qv="RFC1738";let pc=(e,t)=>(pc=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),pc(e,t));const Ms=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),il=1024,Zv=(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,u=[];for(let d=0;d<c.length;++d){let h=c.charCodeAt(d);if(h===45||h===46||h===95||h===126||h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||o===Qv&&(h===40||h===41)){u[u.length]=c.charAt(d);continue}if(h<128){u[u.length]=Ms[h];continue}if(h<2048){u[u.length]=Ms[192|h>>6]+Ms[128|h&63];continue}if(h<55296||h>=57344){u[u.length]=Ms[224|h>>12]+Ms[128|h>>6&63]+Ms[128|h&63];continue}d+=1,h=65536+((h&1023)<<10|c.charCodeAt(d)&1023),u[u.length]=Ms[240|h>>18]+Ms[128|h>>12&63]+Ms[128|h>>6&63]+Ms[128|h&63]}i+=u.join("")}return i};function ew(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Uu(e,t){if(Nt(e)){const s=[];for(let n=0;n<e.length;n+=1)s.push(t(e[n]));return s}return t(e)}const mg={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},hg=function(e,t){Array.prototype.push.apply(e,Nt(t)?t:[t])};let qu;const bt={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Zv,encodeValuesOnly:!1,format:dg,formatter:ug,indices:!1,serializeDate(e){return(qu??(qu=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function tw(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}const ll={};function pg(e,t,s,n,o,a,i,l,c,u,d,h,p,f,y,g,S,v){let x=e,T=v,_=0,j=!1;for(;(T=T.get(ll))!==void 0&&!j;){const C=T.get(e);if(_+=1,typeof C<"u"){if(C===_)throw new RangeError("Cyclic object value");j=!0}typeof T.get(ll)>"u"&&(_=0)}if(typeof u=="function"?x=u(t,x):x instanceof Date?x=p==null?void 0:p(x):s==="comma"&&Nt(x)&&(x=Uu(x,function(C){return C instanceof Date?p==null?void 0:p(C):C})),x===null){if(a)return c&&!g?c(t,bt.encoder,S,"key",f):t;x=""}if(tw(x)||ew(x)){if(c){const C=g?t:c(t,bt.encoder,S,"key",f);return[(y==null?void 0:y(C))+"="+(y==null?void 0:y(c(x,bt.encoder,S,"value",f)))]}return[(y==null?void 0:y(t))+"="+(y==null?void 0:y(String(x)))]}const P=[];if(typeof x>"u")return P;let M;if(s==="comma"&&Nt(x))g&&c&&(x=Uu(x,c)),M=[{value:x.length>0?x.join(",")||null:void 0}];else if(Nt(u))M=u;else{const C=Object.keys(x);M=d?C.sort(d):C}const R=l?String(t).replace(/\./g,"%2E"):String(t),E=n&&Nt(x)&&x.length===1?R+"[]":R;if(o&&Nt(x)&&x.length===0)return E+"[]";for(let C=0;C<M.length;++C){const k=M[C],b=typeof k=="object"&&typeof k.value<"u"?k.value:x[k];if(i&&b===null)continue;const w=h&&l?k.replace(/\./g,"%2E"):k,A=Nt(x)?typeof s=="function"?s(E,w):E:E+(h?"."+w:"["+w+"]");v.set(e,_);const I=new WeakMap;I.set(ll,v),hg(P,pg(b,A,s,n,o,a,i,l,s==="comma"&&g&&Nt(x)?null:c,u,d,h,p,f,y,g,S,I))}return P}function sw(e=bt){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||bt.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=dg;if(typeof e.format<"u"){if(!pc(Wu,e.format))throw new TypeError("Unknown format option provided.");s=e.format}const n=Wu[s];let o=bt.filter;(typeof e.filter=="function"||Nt(e.filter))&&(o=e.filter);let a;if(e.arrayFormat&&e.arrayFormat in mg?a=e.arrayFormat:"indices"in e?a=e.indices?"indices":"repeat":a=bt.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:bt.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:bt.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:bt.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:bt.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?bt.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:bt.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:bt.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:bt.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:bt.encodeValuesOnly,filter:o,format:s,formatter:n,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:bt.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:bt.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:bt.strictNullHandling}}function nw(e,t={}){let s=e;const n=sw(t);let o,a;typeof n.filter=="function"?(a=n.filter,s=a("",s)):Nt(n.filter)&&(a=n.filter,o=a);const i=[];if(typeof s!="object"||s===null)return"";const l=mg[n.arrayFormat],c=l==="comma"&&n.commaRoundTrip;o||(o=Object.keys(s)),n.sort&&o.sort(n.sort);const u=new WeakMap;for(let p=0;p<o.length;++p){const f=o[p];n.skipNulls&&s[f]===null||hg(i,pg(s[f],f,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,u))}const d=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&"),d.length>0?h+d:""}function rw(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 Hu;function _d(e){let t;return(Hu??(t=new globalThis.TextEncoder,Hu=t.encode.bind(t)))(e)}let Yu;function Xu(e){let t;return(Yu??(t=new globalThis.TextDecoder,Yu=t.decode.bind(t)))(e)}var Wt,Ut;class zi{constructor(){Wt.set(this,void 0),Ut.set(this,void 0),Ce(this,Wt,new Uint8Array),Ce(this,Ut,null)}decode(t){if(t==null)return[];const s=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?_d(t):t;Ce(this,Wt,rw([z(this,Wt,"f"),s]));const n=[];let o;for(;(o=ow(z(this,Wt,"f"),z(this,Ut,"f")))!=null;){if(o.carriage&&z(this,Ut,"f")==null){Ce(this,Ut,o.index);continue}if(z(this,Ut,"f")!=null&&(o.index!==z(this,Ut,"f")+1||o.carriage)){n.push(Xu(z(this,Wt,"f").subarray(0,z(this,Ut,"f")-1))),Ce(this,Wt,z(this,Wt,"f").subarray(z(this,Ut,"f"))),Ce(this,Ut,null);continue}const a=z(this,Ut,"f")!==null?o.preceding-1:o.preceding,i=Xu(z(this,Wt,"f").subarray(0,a));n.push(i),Ce(this,Wt,z(this,Wt,"f").subarray(o.index)),Ce(this,Ut,null)}return n}flush(){return z(this,Wt,"f").length?this.decode(`
12
+ `):void 0,ocrError:g.error?String(g.error):void 0})}const f=[];for(const g of d.content_parts||[]){if(g.type!=="image_url")continue;const S=((i=g.image_url)==null?void 0:i.url)||"";if(!S)continue;const v=OS(S),x=Df(S),T=p.get(S.trim());f.push({id:DS(),url:v,ocrText:T==null?void 0:T.ocrText,ocrError:T==null?void 0:T.ocrError,name:x?`attachment-${x.attachmentId}`:"image",size:0,type:"image/*"})}const y={role:"user",id:d.id,createdAt:h,content:d.content||"",images:f.length?f:void 0,isCompressed:!!d.compressed,compressedEventId:d.compressed_by_event_id};o.push(y);continue}if(d.role==="assistant"){const p=d.tool_calls||[];if(p.length>0){const g=(d.content||"").trim(),S=typeof d.reasoning=="string"&&d.reasoning.trim().length>0;if(g||S){const _=S?{reasoning:d.reasoning,backendMessageId:d.id}:{backendMessageId:d.id},j={role:"assistant",type:"text",id:`${d.id}_text`,createdAt:h,content:d.content||"",metadata:_,isCompressed:!!d.compressed,compressedEventId:d.compressed_by_event_id};o.push(j)}for(const _ of p)_.id&&s.set(_.id,Rn((l=_.function)==null?void 0:l.name)||sl);const v=(c=p[0])==null?void 0:c.id,x=v?n.get(v):void 0,T={role:"assistant",type:"tool_call",id:d.id,createdAt:h,toolCalls:p.map(_=>{var j;return{toolCallId:_.id,toolName:Rn((j=_.function)==null?void 0:j.name)||sl,parameters:(()=>{var P,M;try{return JSON.parse(((P=_.function)==null?void 0:P.arguments)||"{}")}catch{return{raw:((M=_.function)==null?void 0:M.arguments)||""}}})(),streamingOutput:""}}),...x?{metadata:x}:{},isCompressed:!!d.compressed,compressedEventId:d.compressed_by_event_id};o.push(T);continue}const f=typeof d.reasoning=="string"&&d.reasoning.trim().length>0?{reasoning:d.reasoning}:{},y={role:"assistant",type:"text",id:d.id,createdAt:h,content:d.content||"",metadata:f,isCompressed:!!d.compressed,compressedEventId:d.compressed_by_event_id};o.push(y);continue}if(d.role==="tool"){const p=((u=d.tool_call_id)==null?void 0:u.trim())||`orphan-tool-call:${d.id}`,f=Rn(s.get(p))||Rn(d.tool_name)||Rn(d.name)||FS(d.content)||sl,y=d.tool_success===!1||d.tool_success==null&&typeof d.content=="string"&&d.content.trimStart().startsWith("Error:"),g={role:"assistant",type:"tool_result",id:d.id,createdAt:h,toolName:f,toolCallId:p,result:{tool_name:f,result:d.content||"",display_preference:"Default"},isError:y,isCompressed:!!d.compressed,compressedEventId:d.compressed_by_event_id};o.push(g);continue}}return o},NS=750,mt={inFlight:null,timer:null,trailingPromise:null,trailingResolve:null,trailingReject:null};function BS(e,t){const s=e.map(ac);t(n=>{const o=new Set(n.processingChats);s.forEach(l=>{l.isRunning&&o.add(l.id)});const a=new Map(n.chats.map(l=>[l.id,l])),i=s.map(l=>{var x,T,_,j;const c=a.get(l.id);if(!c)return l;const u=wu(c.updatedAt),d=wu(l.updatedAt),h=u!==null&&d!==null&&u>d,p=c.config||{},f=l.config||{},y=Object.prototype.hasOwnProperty.call(p,"model"),g=Object.prototype.hasOwnProperty.call(p,"model_ref"),S=Object.prototype.hasOwnProperty.call(p,"reasoningEffort"),v=Math.max(c.messageCount??0,l.messageCount??0);return{...l,title:h?c.title:l.title,pinned:h?c.pinned:l.pinned,updatedAt:h?c.updatedAt:l.updatedAt,messages:c.messages,messageCount:v,config:{...p,...f,model:h&&y?p.model:f.model,model_ref:h&&g?p.model_ref:f.model_ref,reasoningEffort:h&&S?p.reasoningEffort:f.reasoningEffort,compressionEvents:((x=c.config)==null?void 0:x.compressionEvents)??((T=l.config)==null?void 0:T.compressionEvents),syncCursor:((_=c.config)==null?void 0:_.syncCursor)??((j=l.config)==null?void 0:j.syncCursor)}}});return{...n,chats:i,processingChats:o}})}async function _u(e){return mt.inFlight||(mt.inFlight=(async()=>{try{const t=await qs.listSessions();BS(t.sessions,e)}catch(t){throw console.error("[ChatSlice] Failed to refresh sessions:",t),t}})().finally(()=>{mt.inFlight=null})),mt.inFlight}const WS=(e,t)=>({chats:[],currentSessionId:null,latestActiveSessionId:null,processingChats:new Set,autoGenerateTitles:!0,isUpdatingAutoTitlePreference:!1,subSessionsByParent:{},pendingQuestionsBySession:{},addChat:async s=>{var p,f,y,g,S,v,x,T,_,j,P,M;const n=(s.title||is.t("chat.sidebar.newSession")).trim(),o=((f=(p=s.config)==null?void 0:p.baseSystemPrompt)==null?void 0:f.trim())||"",a=(y=ze.getState().getActiveModel())==null?void 0:y.trim(),i=((S=(g=s.config)==null?void 0:g.model)==null?void 0:S.trim())||a||void 0,l=((v=s.config)==null?void 0:v.reasoningEffort)??void 0;let c,u;if(ze.getState().isProviderModelRefEnabled()){const R=(x=s.config)==null?void 0:x.model_ref;if((T=R==null?void 0:R.provider)!=null&&T.trim()&&((_=R==null?void 0:R.model)!=null&&_.trim()))c=R,u=R.provider;else{const E=(j=ze.getState().providerConfig.defaults)==null?void 0:j.chat;if((P=E==null?void 0:E.provider)!=null&&P.trim()&&((M=E==null?void 0:E.model)!=null&&M.trim()))c=E,u=E.provider;else{const C=ze.getState().getActiveModel();C&&(c={provider:ze.getState().currentProvider,model:C},u=ze.getState().currentProvider)}}}const d=await qs.createSession({title:n,system_prompt:o||void 0,model:i,model_ref:c,provider:u,reasoning_effort:l||void 0}),h={...ac(d.session),title:n,config:{...s.config,model:d.session.model,model_ref:d.session.model_ref??null,reasoningEffort:d.session.reasoning_effort??null,baseSystemPrompt:o||$f},messages:[],currentInteraction:null};return e(R=>{const E=[h,...R.chats.filter(C=>C.id!==h.id)];return{...R,chats:E,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 qs.deleteSession(s)}catch(n){console.error(`[ChatSlice] Failed to delete backend session ${s}:`,n)}e(n=>{var c;const o=new Set;for(const u of n.chats)u.id===s&&o.add(u.id),u.rootSessionId===s&&o.add(u.id);const a=n.chats.filter(u=>!o.has(u.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(u=>{const d=u.chats.map(h=>h.id===s?{...h,...n,...l?{updatedAt:l}:{}}:h);return{...u,chats:d}});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")&&ze.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 u=n.config.reasoningEffort;u?c.reasoning_effort=u:c.clear_reasoning_effort=!0}Object.keys(c).length>0&&qs.patchSession(s,c).catch(u=>{console.warn(`[ChatSlice] Failed to patch session ${s}:`,u)})},persistSessionTitle:async(s,n)=>{var a;const o=(a=t().chats.find(i=>i.id===s))==null?void 0:a.title;e(i=>({...i,chats:i.chats.map(l=>l.id===s?{...l,title:n,updatedAt:new Date().toISOString()}:l)}));try{await qs.patchSession(s,{title:n})}catch(i){throw typeof o=="string"&&e(l=>({...l,chats:l.chats.map(c=>c.id===s?{...c,title:o}:c)})),console.warn(`[ChatSlice] persistSessionTitle failed for ${s}:`,i),i}},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(u=>{Object.prototype.hasOwnProperty.call(c,u)&&(c[u]=o[u])}),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 qs.deleteSessionMessage(s,n)}catch(a){return console.warn(`[ChatSlice] Failed to delete message ${n} from session ${s}:`,a),a instanceof Yn?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()=>mt.inFlight?mt.inFlight:mt.timer?(mt.trailingPromise||(mt.trailingPromise=new Promise((s,n)=>{mt.trailingResolve=s,mt.trailingReject=n})),mt.trailingPromise):(mt.timer=setTimeout(()=>{if(mt.timer=null,mt.trailingPromise){const s=mt.trailingResolve,n=mt.trailingReject;mt.trailingPromise=null,mt.trailingResolve=null,mt.trailingReject=null,_u(e).then(s,n)}},NS),_u(e)),loadChats:async()=>{var c,u,d;const s=localStorage.getItem(vu),n=s===null?t().autoGenerateTitles:s==="true";let o=await qs.listSessions();if(!o.sessions||o.sessions.length===0){const h=(c=ze.getState().getActiveModel())==null?void 0:c.trim(),p=(u=ze.getState().providerConfig.defaults)==null?void 0:u.chat;o={sessions:[(await qs.createSession({title:is.t("chat.sidebar.newSession"),model:h,model_ref:p,provider:p==null?void 0:p.provider})).session]}}const a=o.sessions.map(ac),i=((d=a[0])==null?void 0:d.id)??null,l=a.filter(h=>h.isRunning).map(h=>h.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,u,d,h,p,f;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 g=t().chats.find(T=>T.id===s);if(!g)return;const S=await qs.getHistory(s),v=(l=S.messages[S.messages.length-1])==null?void 0:l.role;if(n!=null&&n.waitForAssistant&&v==="user"&&y<a){const T=i>0?i*(y+1):200*(y+1);await new Promise(_=>setTimeout(_,T));continue}const x=zS(s,S.messages);if(o==="monotonic"){const T=g.messages||[],_=T.length,j=x.length,P=(c=x[x.length-1])==null?void 0:c.role,M=(u=T[T.length-1])==null?void 0:u.role,R=T[T.length-1],E=x[x.length-1],C=R==null?void 0:R.id,k=E==null?void 0:E.id;let b=!1;if(j>_?b=!0:j===_&&(b=M==="user"&&P!=="user"||typeof C=="string"&&typeof k=="string"&&C!==k),!b){t().updateSession(s,{messageCount:Math.max(g.messageCount??0,S.messages.length)});return}}t().updateSession(s,{messages:x,messageCount:S.messages.length,config:{...g.config||{},compressionEvents:(S.compression_events||[]).map(T=>({id:T.id,createdAt:T.created_at,messagesCompressed:T.messages_compressed,segmentsRemoved:T.segments_removed})),syncCursor:{messageCount:S.messages.length,lastMessageId:((d=S.messages[S.messages.length-1])==null?void 0:d.id)??null,hasPendingQuestion:((h=t().pendingQuestionRespond)==null?void 0:h.sessionId)===s,pendingQuestionToolCallId:((p=t().pendingQuestionRespond)==null?void 0:p.sessionId)===s?((f=t().pendingQuestionRespond)==null?void 0:f.toolCallId)??null:null}}});return}catch(g){if(y>=a){console.warn(`[ChatSlice] Failed to load history for ${s}:`,g);return}const S=i>0?i*(y+1):200*(y+1);await new Promise(v=>setTimeout(v,S))}},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(vu,String(s))}catch(o){throw console.warn("[ChatSlice] Failed to update auto-title preference:",o),e({autoGenerateTitles:n}),o}finally{e({isUpdatingAutoTitlePreference:!1})}},setPendingQuestionForSession:s=>{e(n=>({pendingQuestionsBySession:{...n.pendingQuestionsBySession,[s.sessionId]:s}}))},clearPendingQuestionForSession:s=>{e(n=>{const o={...n.pendingQuestionsBySession};return delete o[s],{pendingQuestionsBySession:o}})}});class ic extends Error{constructor(s="Proxy authentication required"){super(s);Je(this,"code","proxy_auth_required");this.name="ProxyAuthRequiredError"}}const Dn=class Dn{constructor(){}static getInstance(){return Dn.instance||(Dn.instance=new Dn),Dn.instance}resolveOpenAICompatBaseUrl(){const t=Mr().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 fd({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 Yn){if(n.status===428)throw new ic(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 ic(((s=o.error)==null?void 0:s.message)||n.message)}throw n}}};Je(Dn,"instance");let lc=Dn;const Lf=lc.getInstance(),US=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)},qS=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")},us=async e=>{try{await US(e);return}catch(t){try{qS(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 HS{async copyToClipboard(t){await us(t)}async getBambooConfig(){try{return await je.get("bamboo/config")}catch(t){return console.error("Failed to fetch Bamboo config:",t),{}}}async getBambooTools(){try{return await je.get("bamboo/tools")}catch(t){return console.error("Failed to fetch Bamboo tools:",t),{tools:[]}}}async getModelLimitDefaults(){try{return await je.get("bamboo/model-limits/defaults")}catch(t){return console.error("Failed to fetch model limit defaults:",t),{model_limits:[]}}}async setBambooConfig(t){return je.post("bamboo/config",t)}async validateBambooConfigPatch(t){return je.post("bamboo/config/validate",t)}async setProxyAuth(t){return je.post("bamboo/proxy-auth",t)}async getProxyAuthStatus(){try{return await je.get("bamboo/proxy-auth/status")}catch(t){return console.error("Failed to fetch proxy auth status:",t),{configured:!1,username:null}}}async clearProxyAuth(){return je.post("bamboo/proxy-auth",{username:"",password:""})}async resetBambooConfig(){return je.post("bamboo/config/reset",{})}async saveWorkflow(t,s){return je.post("bamboo/workflows",{name:t,content:s})}async deleteWorkflow(t){return je.delete(`bamboo/workflows/${encodeURIComponent(t)}`)}async getKeywordMaskingConfig(){try{return await je.get("bamboo/keyword-masking")}catch(t){return console.error("Failed to fetch keyword masking config:",t),{entries:[]}}}async updateKeywordMaskingConfig(t){return je.post("bamboo/keyword-masking",t)}async validateKeywordEntries(t){return je.post("bamboo/keyword-masking/validate",t)}async getSetupStatus(){return await je.get("bamboo/setup/status")}async markSetupComplete(){return je.post("bamboo/setup/complete",{})}async resetSetupStatus(){await je.post("bamboo/setup/incomplete",{})}async getAccessStatus(){return je.get("bamboo/access/status")}async verifyAccessPassword(t){return je.post("bamboo/access/verify",{password:t})}async updateAccessPassword(t){return je.post("bamboo/access/password",t)}}const Ln=class Ln{constructor(){Je(this,"httpUtilityService",new HS)}static getInstance(){return Ln.instance||(Ln.instance=new Ln),Ln.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)}};Je(Ln,"instance");let vs=Ln;const ot=vs.getInstance();let Ir=null,$r=null;const nl=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,bs=yn((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(Ir)return Ir;Ir=(async()=>{e({isLoadingConfig:!0,error:null});try{const o=await ot.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 Ir}finally{Ir=null}},saveConfig:async s=>{e({isLoadingConfig:!0,error:null,config:s});try{const n=await ot.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($r)return $r;$r=(async()=>{e({isLoadingProxyAuthStatus:!0,error:null});try{const o=await ot.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 $r}finally{$r=null}},applyProxyAuth:async s=>{await ot.setProxyAuth(s),await t().loadProxyAuthStatus({force:!0})},clearProxyAuth:async()=>{await ot.clearProxyAuth(),await t().loadProxyAuthStatus({force:!0})}}));let Dr=null;const YS=(e,t)=>({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:null,configModel:void 0,setSelectedModel:s=>{e({selectedModel:s})},loadConfigModel:async()=>{try{const s=await bs.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(Dr)return Dr;Dr=(async()=>{e({isLoadingModels:!0,modelsError:null});try{try{if(!(await ot.getSetupStatus()).is_complete){it("[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 Lf.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 ic){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 Dr}finally{Dr=null}}}),XS=["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}),dn=class dn{constructor(){Je(this,"deprecatedKeysCleanupDone",!1)}static getInstance(){return dn.instance||(dn.instance=new dn),dn.instance.cleanupDeprecatedPromptStorageKeys(),dn.instance}cleanupDeprecatedPromptStorageKeys(){if(!this.deprecatedKeysCleanupDone){this.deprecatedKeysCleanupDone=!0;try{for(const t of XS)localStorage.removeItem(t)}catch(t){console.warn("[SystemPromptService] Failed to cleanup deprecated prompt storage keys:",t)}}}async getSystemPromptPresets(){try{const t=await we.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 we.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 we.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 we.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)||""}};Je(dn,"instance");let yi=dn;const Tu="copilot_last_selected_prompt_id",Of="copilot_custom_system_prompts_v2",Ff="copilot_custom_system_prompts_v2_migrated_to_backend",zf="general_assistant",gd=80,mr=yi.getInstance();let Ca=null;function yd(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,gd)}function Nf(e){if(typeof e!="string")return null;const t=e.toLowerCase().trim().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");return t?t.slice(0,gd):null}function Bf(e,t){if(!t.has(e))return e;let s=2;for(;;){const n=`_${s}`,a=`${e.slice(0,Math.max(0,gd-n.length))}${n}`;if(!t.has(a))return a;s+=1}}function Wf(){try{const e=localStorage.getItem(Of);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=Nf(o==null?void 0:o.id)||yd(a),u=Bf(c,s);u!==zf&&(s.add(u),n.push({id:u,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 Uf(){try{return localStorage.getItem(Ff)==="1"}catch(e){return console.error("[promptSlice] Failed to read migration marker:",e),!1}}function ku(){try{localStorage.setItem(Ff,"1")}catch(e){console.error("[promptSlice] Failed to write migration marker:",e)}}function ju(){try{localStorage.removeItem(Of)}catch(e){console.error("[promptSlice] Failed to clear legacy custom prompts:",e)}}async function VS(){var o,a;if(Uf())return;const e=Wf();if(e.length===0){ju(),ku();return}const t=await mr.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===zf||i.isDefault)continue;const u=Nf(i.id)||yd(l),d=Bf(u,s);try{const h=await mr.createSystemPromptPreset({id:d,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||(ju(),ku())}async function KS(){Ca||(Ca=VS().finally(()=>{Ca=null})),await Ca}const GS=(e,t)=>({systemPrompts:[],lastSelectedPromptId:localStorage.getItem(Tu)||null,loadSystemPrompts:async()=>{try{await KS()}catch(o){console.warn("[promptSlice] Legacy prompt migration skipped:",o)}let s=[];try{s=await mr.getSystemPromptPresets()}catch(o){console.error("Failed to load system prompts from backend:",o)}let n=s.length?s:gi();if(!Uf()){const o=Wf();n=JS(n,o)}n.length===0&&(n=gi()),e({systemPrompts:n})},addSystemPrompt:async s=>{try{await mr.createSystemPromptPreset({id:yd(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 mr.updateSystemPromptPreset(s),await t().loadSystemPrompts()}catch(n){throw console.error("Failed to update system prompt:",n),n}},deleteSystemPrompt:async s=>{try{await mr.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(Tu,s)}catch(n){console.error("Failed to save last selected prompt ID to localStorage:",n)}}}),JS=(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())},QS=(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 ZS{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 je.get(a)}async getSkill(t){return je.get(`skills/${t}`)}async getFilteredTools(t){const s=t?`?session_id=${encodeURIComponent(t)}`:"";return(await je.get(`skills/filtered-tools${s}`)).tools??[]}}const cc=new ZS,ev=(e,t)=>({skills:[],isLoadingSkills:!1,skillsError:null,loadSkills:async(s,n)=>{e({isLoadingSkills:!0,skillsError:null});try{const o=await cc.listSkills(s,n);e({skills:o.skills,isLoadingSkills:!1})}catch(o){e({skillsError:o instanceof Error?o.message:is.t("components.skillManager.loadFailed"),isLoadingSkills:!1})}},getSkill:async s=>{e({isLoadingSkills:!0,skillsError:null});try{const n=await cc.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:is.t("components.skillManager.getFailed"),isLoadingSkills:!1})}},clearSkillsError:()=>{e({skillsError:null})}}),tv=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}})}),sv=(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,...u}=n.activeItems,{[s]:d,...h}=n.evaluationStates;return{taskLists:a,taskListVersions:l,activeItems:u,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}})}),dc=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:dc(s),allowCustom:n??!0,toolCallId:o??null}),nv=(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=dc(e.options),n=dc(t.options);return s.length!==n.length?!1:s.every((o,a)=>o===n[a])},qf="chat_input_reasoning_by_session_v1",Hf="chat_input_reasoning_last_used_v1",Cu={content:"",referenceText:null,attachments:[],reasoningEffort:"medium"},bd=e=>e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max",Yf=()=>{if(typeof window>"u")return{};try{const e=localStorage.getItem(qf);if(!e)return{};const t=JSON.parse(e),s={};for(const[n,o]of Object.entries(t||{}))bd(o)&&(s[n]=o);return s}catch{return{}}},rv=e=>{if(!(typeof window>"u"))try{localStorage.setItem(qf,JSON.stringify(e))}catch{}},ov=()=>{if(!(typeof window>"u"))try{const e=localStorage.getItem(Hf);return bd(e)?e:void 0}catch{return}},av=e=>{if(!(typeof window>"u"))try{localStorage.setItem(Hf,e)}catch{}},xd=e=>{const t=Yf();return bd(t[e])?t[e]:ov()},Lr=e=>({...Cu,reasoningEffort:xd(e)??Cu.reasoningEffort}),iv=(e,t)=>({inputStates:{},pendingQuestionRespond:null,setInputContent:(s,n)=>e(o=>({inputStates:{...o.inputStates,[s]:{...o.inputStates[s]||Lr(s),content:n}}})),setReferenceText:(s,n)=>e(o=>({inputStates:{...o.inputStates,[s]:{...o.inputStates[s]||Lr(s),referenceText:n}}})),setAttachments:(s,n)=>e(o=>({inputStates:{...o.inputStates,[s]:{...o.inputStates[s]||Lr(s),attachments:n}}})),setInputReasoningEffort:(s,n)=>{e(a=>({inputStates:{...a.inputStates,[s]:{...a.inputStates[s]||Lr(s),reasoningEffort:n}}}));const o=Yf();o[s]=n,rv(o),av(n)},clearInputState:s=>e(n=>{const{[s]:o,...a}=n.inputStates;return{inputStates:a}}),getInputState:s=>t().inputStates[s]||Lr(s),setPendingQuestionRespond:s=>e(n=>nv(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}})}),lv="bamboo_proxy_auth",cv=()=>{try{const e=localStorage.getItem(lv);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}},dv="auto",uv="required",mv=1e4,hv=2e3,pv=ds.getInstance();let Mu=null,Or=null,Pu=null,Fr=null;const Eu=new WeakMap,L=yn()(hS(fS((e,t,s)=>({...WS(e,t),...YS(e,t),...GS(e,t),...QS(e,t),...ev(e,t),...tv(e),...sv(e,t),...iv(e,t),agentAvailability:null,setAgentAvailability:n=>{e({agentAvailability:n})},checkAgentAvailability:async()=>{if(Or)return Or;Or=(async()=>{const n=await pv.healthCheck();return t().agentAvailability!==n&&e({agentAvailability:n}),n})();try{return await Or}finally{Or=null}},startAgentHealthCheck:()=>{Mu||(t().checkAgentAvailability(),Mu=setInterval(()=>{t().checkAgentAvailability()},mv))},refreshSessionsIndex:async()=>{if(Fr)return Fr;Fr=(async()=>{try{await t().refreshChats()}catch(n){console.warn("[AppStore] refreshChats failed:",n)}})();try{return await Fr}finally{Fr=null}},startSessionsIndexSync:()=>{Pu||(t().refreshSessionsIndex(),Pu=setInterval(()=>{t().refreshSessionsIndex()},hv))}})),{name:"AppStore"})),Xf=e=>{const t=Eu.get(e);if(t)return t;const s=new Map(e.map(n=>[n.id,n]));return Eu.set(e,s),s},bn=e=>t=>e?Xf(t.chats).get(e)??null:null,Sd=e=>e.currentSessionId?Xf(e.chats).get(e.currentSessionId)??null:null,fv=e=>{var t;return((t=Sd(e))==null?void 0:t.messages)??[]},Ru=async()=>{const e=cv();if(!e)return!1;try{return await ot.setProxyAuth(e),!0}catch(t){return console.error("Failed to apply stored proxy auth during startup:",t),!1}},gv=async()=>{try{const e=await bs.getState().loadConfig();if((typeof(e==null?void 0:e.proxy_auth_mode)=="string"?e.proxy_auth_mode:dv)!==uv)return await Ru(),!1;const s=await bs.getState().loadProxyAuthStatus({force:!0});return s!=null&&s.configured||await Ru()?!1:(L.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 Au=!1;const Vf=async(e=!1)=>{if(Au&&!e)return;Au=!0,L.getState().startAgentHealthCheck(),await ze.getState().loadProviderConfig(),await L.getState().loadChats(),await gv()||await L.getState().fetchModels(),await L.getState().loadSystemPrompts()},yv=Object.freeze(Object.defineProperty({__proto__:null,initializeStore:Vf,selectCurrentChat:Sd,selectCurrentMessages:fv,selectSessionById:bn,useAppStore:L},Symbol.toStringTag,{value:"Module"})),Xn={'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:Iu,Paragraph:bv}=pe,xv=({content:e,token:t,showGradient:s,onClick:n})=>r.jsx(te,{size:"small",style:{marginLeft:t.marginLG,marginTop:t.marginXS,backgroundColor:t.colorBgLayout,borderColor:t.colorBorderSecondary},styles:{body:{padding:t.paddingMD}},onClick:n,children:r.jsxs("div",{style:{maxHeight:"60vh",overflowY:"auto",position:"relative",paddingRight:t.paddingXS},children:[r.jsx(xs,{remarkPlugins:[Ii],components:{p:({children:o})=>r.jsx(bv,{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(Iu,{strong:!0,style:{fontSize:t.fontSizeHeading3,marginBottom:t.marginSM,display:"block"},children:o}),h2:({children:o})=>r.jsx(Iu,{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(br,{style:Xn,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:Sv}=pe,vv=({prompt:e,token:t,isSelected:s,isExpanded:n,onSelect:o,onToggleExpand:a,onCopy:i})=>{const{t:l}=ie(),c=e.content||"",{nonEmptyLineCount:u,wordCount:d,characterCount:h,showGradient:p}=m.useMemo(()=>{const y=(c?c.split(/\r?\n/):[]).filter(v=>v.trim().length>0).length,g=c.trim()?c.trim().split(/\s+/).filter(Boolean).length:0,S=c.length;return{nonEmptyLineCount:y,wordCount:g,characterCount:S,showGradient:!n&&S>600}},[c,n]);return r.jsx(lt.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(U,{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(U,{align:"start",children:[r.jsx(ls,{checked:s,onChange:()=>o(e.id),onClick:f=>f.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(ue,{color:"warning",children:l("chat.systemPromptSelector.defaultTag")}):null]}),r.jsxs(U,{size:"small",children:[r.jsx(B,{type:"text",size:"small",icon:n?r.jsx(lx,{}):r.jsx(sd,{}),onClick:f=>{f.stopPropagation(),a(e.id)},children:l(n?"chat.systemPromptSelector.hide":"chat.systemPromptSelector.preview")}),r.jsx(B,{type:"text",size:"small",icon:r.jsx(cs,{}),onClick:f=>i(f,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(U,{size:"small",wrap:!0,style:{marginLeft:t.marginLG},children:[r.jsx(ue,{color:"processing",children:l("chat.systemPromptSelector.lines",{count:u})}),r.jsx(ue,{color:"purple",children:l("chat.systemPromptSelector.words",{count:d})}),r.jsx(ue,{color:"success",children:l("chat.systemPromptSelector.chars",{count:h})})]}),n?r.jsx(xv,{content:c,token:t,showGradient:p,onClick:f=>f.stopPropagation()}):r.jsx(Sv,{type:"secondary",ellipsis:{rows:3},style:{marginLeft:t.marginLG,marginBottom:0,color:t.colorTextSecondary},children:c||l("chat.systemPromptSelector.noContent")})]})},e.id)},{Text:wv}=pe,{useToken:_v}=xe,Tv=({open:e,onClose:t,onSelect:s,prompts:n,title:o,showCancelButton:a=!0})=>{const{t:i}=ie(),{token:l}=_v(),[c,u]=fn.useMessage(),d=L(j=>j.lastSelectedPromptId),h=L(j=>j.setLastSelectedPromptId),[p,f]=m.useState(null),[y,g]=m.useState(null),S=m.useMemo(()=>n.filter(j=>j.id&&j.id.trim()!==""),[n]),v=async(j,P)=>{j.stopPropagation();const M=P.content??"";try{await us(M),c.success(i("success.promptCopied",{name:P.name}))}catch(R){console.error("[SystemPromptSelector] Failed to copy prompt:",R),c.error(i("error.copyPromptFailed"))}},x=o??i("chat.prompt.selectorTitle");m.useEffect(()=>{if(e){const j=S.find(M=>M.isDefault),P=d||(j==null?void 0:j.id)||(S.length>0?S[0].id:null);f(P)}},[e,d,S.length]);const T=j=>{f(j.id),h(j.id),s(j),t()},_=()=>{t()};return r.jsxs(r.Fragment,{children:[u,r.jsxs(Bt,{title:r.jsxs(U,{children:[r.jsx(Tr,{}),x]}),open:e,onCancel:_,width:700,footer:r.jsx(nS,{buttons:[...a?[rS(_)]:[],oS(()=>{const j=S.find(P=>P.id===p);j&&T(j)},{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(wv,{type:"secondary",style:{fontSize:l.fontSizeSM},children:i("chat.prompt.helperText")})}),S.length===0?r.jsx(Pt,{description:i("chat.prompt.emptyDescription"),style:{margin:l.marginLG}}):r.jsx("div",{children:S.map(j=>r.jsx(vv,{prompt:j,token:l,isSelected:p===j.id,isExpanded:y===j.id,onSelect:P=>f(P),onToggleExpand:P=>g(y===P?null:P),onCopy:v},j.id))})]})]})},kv=({chat:e,isSelected:t,onSelect:s,onDelete:n,onPin:o,onUnpin:a,onEdit:i,onGenerateTitle:l,onRunProjectDream:c,isGeneratingTitle:u,isRunningProjectDream:d,titleGenerationError:h})=>{const{t:p}=ie(),[f,y]=m.useState(!1),[g,S]=m.useState(e.title),[v,x]=m.useState(!1),[T,_]=m.useState(!1),{token:j}=xe.useToken(),P=m.useCallback(w=>{w.stopPropagation(),i&&g.trim()&&i(e.id,g.trim()),y(!1)},[e.id,g,i]),M=m.useCallback(w=>{w.stopPropagation(),S(e.title),y(!1)},[e.title]),R=[{key:"pin",icon:e.pinned?r.jsx(sc,{style:{color:j.colorWarning}}):r.jsx(nd,{}),label:e.pinned?p("chat.actions.unpin"):p("chat.actions.pin"),onClick:({domEvent:w})=>{w.stopPropagation(),e.pinned?a(e.id):o(e.id)}},{key:"edit",icon:r.jsx(ca,{}),label:p("chat.chatItem.edit"),onClick:({domEvent:w})=>{w.stopPropagation(),y(!0)}},...l?[{key:"generate-title",icon:u?r.jsx(xr,{}):r.jsx(bf,{style:h?{color:j.colorError}:void 0}),label:h||p("chat.actions.generateTitle"),disabled:u,onClick:({domEvent:w})=>{w.stopPropagation(),l(e.id)}}]:[],...c?[{key:"run-project-dream",icon:d?r.jsx(xr,{}):r.jsx(cx,{}),label:p("chat.actions.runProjectDream"),disabled:d,onClick:({domEvent:w})=>{w.stopPropagation(),c(e.id)}}]:[],{type:"divider"},{key:"delete",icon:r.jsx(gn,{}),label:p("common.delete"),danger:!0,onClick:({domEvent:w})=>{w.stopPropagation(),n(e.id)}}],E={padding:"8px 12px",borderRadius:j.borderRadiusSM,marginBottom:j.marginXXS,cursor:"pointer",transition:"all 0.2s cubic-bezier(0.4, 0, 0.2, 1)",backgroundColor:t?"var(--lotus-primary-soft)":v||T?"var(--lotus-item-hover-bg)":"transparent",border:"1px solid transparent",borderColor:t?"var(--lotus-tool-card-border)":v||T?j.colorBorderSecondary:"transparent",position:"relative",overflow:"visible",boxShadow:t?"var(--lotus-tool-card-shadow)":"none",transform:v&&!t?"translateX(2px)":"none"},C={flex:1,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",fontSize:13,fontWeight:t?600:500,color:t?"var(--lotus-primary)":j.colorText},k={flex:1,fontSize:j.fontSizeSM,marginRight:j.marginSM},b=f?[r.jsx(B,{type:"text",size:"small",icon:r.jsx(dx,{style:{color:j.colorSuccess}}),onClick:P,"aria-label":p("common.save")},"save"),r.jsx(B,{type:"text",size:"small",icon:r.jsx(kr,{style:{color:j.colorError}}),onClick:M,"aria-label":p("common.cancel")},"cancel")]:v||T?[r.jsx(qn,{menu:{items:R,className:"lotus-sidebar-actions-menu"},trigger:["click"],placement:"bottomRight",overlayClassName:"lotus-sidebar-actions-dropdown",open:T,onOpenChange:w=>_(w),children:r.jsx(B,{type:"text",size:"small",icon:r.jsx(ux,{}),"aria-label":p("common.moreActions","More actions"),onClick:w=>w.stopPropagation(),style:{color:j.colorTextSecondary,borderRadius:j.borderRadiusSM,background:j.colorFillTertiary,width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center"}})},"more")]:[];return r.jsx(lt.Item,{style:E,tabIndex:0,onClick:()=>!f&&s(e.id),onKeyDown:w=>{w.key==="Enter"&&!f?(w.preventDefault(),s(e.id)):(w.key==="Delete"||w.key==="Backspace")&&!f&&w.metaKey&&(w.preventDefault(),n(e.id))},onMouseEnter:()=>x(!0),onMouseLeave:()=>{T||x(!1)},onFocus:()=>x(!0),onBlur:()=>{T||x(!1)},actions:b,"data-testid":"chat-item",role:"option","aria-selected":t,"aria-label":e.title||p("chat.sidebar.untitledChat"),children:r.jsx(lt.Item.Meta,{title:f?r.jsx(be,{value:g,onChange:w=>S(w.target.value),onClick:w=>w.stopPropagation(),onPressEnter:w=>{w.preventDefault(),P(w)},autoFocus:!0,style:k,variant:"borderless",size:"small"}):r.jsxs("div",{style:{...C,display:"flex",alignItems:"center",gap:j.marginXS,minWidth:0},children:[e.pinned&&r.jsx(sc,{style:{color:j.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(ue,{color:"processing",style:{marginInlineEnd:0,flex:"0 0 auto"},children:p("chat.chatItem.childTag")}):null]})})})},jv=(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,uc=m.memo(kv,jv);uc.displayName="ChatItem";const $u=e=>({Today:0,Yesterday:1,"This Week":2,"This Month":3})[e]??4,Cv=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},Mv=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:$u(s)-$u(n)})},Pv=(e,t)=>e[t]?e[t].map(s=>s.id):[],Kf=(e,t)=>e[t]?e[t].length:0,Du=e=>e.pinned?"Pinned":e.createdByScheduleId?"Scheduled":new Date(e.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),Lu=(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},Ev=({groupedChatsByDate:e,childrenByRoot:t,expandedRootIds:s,onToggleRootExpanded:n,sortedDateKeys:o,expandedKeys:a,onCollapseChange:i,currentSessionId:l,onSelectChat:c,onDeleteChat:u,onDeleteByDate:d,onPinChat:h,onUnpinChat:p,onEditTitle:f,onGenerateTitle:y,onRunProjectDream:g,titleGenerationState:S,projectDreamState:v,token:x,hasActiveFilters:T})=>{const{t:_}=ie(),j=m.useMemo(()=>o.length?o.map(M=>{const R=e[M],E=Kf(e,M);return{dateKey:M,dateGroup:R,totalChatsInDate:E}}):[],[e,o]);if(!o.length)return r.jsx(Pt,{image:Pt.PRESENTED_IMAGE_SIMPLE,description:r.jsxs(U,{direction:"vertical",size:4,align:"center",children:[r.jsx("span",{style:{color:x.colorTextSecondary},children:T?_("chat.sidebar.empty.noMatches","No matching sessions"):_("chat.sidebar.empty.noSessions")}),r.jsx("span",{style:{color:x.colorTextSecondary,fontSize:12},children:T?_("chat.sidebar.empty.filterHint","Try adjusting your search or filters"):_("chat.sidebar.empty.hint")}),T&&r.jsx(B,{size:"small",type:"link",onClick:()=>{var R;const M=document.querySelector('[data-testid="sidebar-search-input"] input, .lotus-sidebar-search input');if(M){const E=(R=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value"))==null?void 0:R.set;E==null||E.call(M,""),M.dispatchEvent(new Event("input",{bubbles:!0}))}},children:_("chat.sidebar.empty.clearFilters","Clear filters")})]})});const P=new Set(a);return r.jsx(U,{direction:"vertical",size:"small",style:{width:"100%"},children:j.map(({dateKey:M,dateGroup:R,totalChatsInDate:E})=>{const C=P.has(M);return r.jsxs("div",{style:{borderRadius:x.borderRadiusSM,background:C?x.colorFillTertiary:"transparent",padding:4},children:[r.jsxs(V,{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":C,"aria-label":`${Lu(M,_)} (${E})`,onKeyDown:k=>{if(k.key==="Enter"||k.key===" "){k.preventDefault();const b=new Set(P);b.has(M)?b.delete(M):b.add(M),i(Array.from(b))}},onMouseEnter:k=>{k.currentTarget.style.background="var(--lotus-sidebar-item-hover-bg, rgba(204, 251, 241, 0.92))",k.currentTarget.style.borderColor="var(--lotus-sidebar-item-hover-border, rgba(13, 148, 136, 0.28))";const b=k.currentTarget.querySelector(".chat-sidebar-date-group-delete");b&&(b.style.opacity="1")},onMouseLeave:k=>{k.currentTarget.style.background="transparent",k.currentTarget.style.borderColor="transparent";const b=k.currentTarget.querySelector(".chat-sidebar-date-group-delete");b&&(b.style.opacity="0")},onClick:()=>{const k=new Set(P);k.has(M)?k.delete(M):k.add(M),i(Array.from(k))},className:"chat-sidebar-date-group-header",children:[r.jsxs(V,{align:"center",gap:"small",style:{minWidth:0},children:[C?r.jsx(Xt,{style:{fontSize:12,opacity:.6}}):r.jsx(Vs,{style:{fontSize:12,opacity:.6}}),r.jsxs("span",{style:{fontSize:12,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:M==="Today"?"var(--lotus-primary)":x.colorTextSecondary,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[Lu(M,_)," (",E,")"]})]}),r.jsx(B,{type:"text",size:"small",icon:r.jsx(gn,{}),className:"chat-sidebar-date-group-delete",style:{color:x.colorTextTertiary,opacity:0,transition:"opacity 0.2s ease"},onClick:k=>{k.stopPropagation(),d(M)}})]}),C?r.jsx("div",{style:{marginTop:4},children:r.jsx(lt,{itemLayout:"horizontal",dataSource:R,split:!1,renderItem:k=>{var b,w,A,I,$,W;return r.jsxs("div",{children:[r.jsxs(V,{align:"center",gap:6,children:[(b=t[k.id])!=null&&b.length?r.jsx(B,{size:"small",type:"text",style:{padding:0,width:22},"aria-label":s.has(k.id)?_("chat.sidebar.actions.collapseChildren"):_("chat.sidebar.actions.expandChildren"),onClick:O=>{O.preventDefault(),O.stopPropagation(),n(k.id)},children:s.has(k.id)?r.jsx(Xt,{}):r.jsx(Vs,{})}):r.jsx("div",{style:{width:22}}),r.jsx("div",{style:{flex:1,minWidth:0},children:r.jsx(uc,{chat:k,isSelected:k.id===l,onSelect:c,onDelete:u,onPin:h,onUnpin:p,onEdit:f,onGenerateTitle:y,onRunProjectDream:g,isGeneratingTitle:((w=S[k.id])==null?void 0:w.status)==="loading",isRunningProjectDream:((A=v[k.id])==null?void 0:A.status)==="loading",titleGenerationError:((I=S[k.id])==null?void 0:I.status)==="error"?($=S[k.id])==null?void 0:$.error:void 0})})]}),s.has(k.id)&&(((W=t[k.id])==null?void 0:W.length)??0)>0?r.jsx("div",{style:{marginLeft:22,marginTop:2},children:r.jsx(lt,{itemLayout:"horizontal",dataSource:t[k.id],split:!1,renderItem:O=>{var re,q,Z,X;return r.jsx("div",{style:{paddingLeft:12},children:r.jsx(uc,{chat:O,isSelected:O.id===l,onSelect:c,onDelete:u,onPin:h,onUnpin:p,onEdit:f,onGenerateTitle:y,onRunProjectDream:g,isGeneratingTitle:((re=S[O.id])==null?void 0:re.status)==="loading",isRunningProjectDream:((q=v[O.id])==null?void 0:q.status)==="loading",titleGenerationError:((Z=S[O.id])==null?void 0:Z.status)==="error"?(X=S[O.id])==null?void 0:X.error:void 0})},O.id)}})}):null]},k.id)}})}):null]},M)})})},Rv="copilot_ui_theme_v1";function Av(){var e;try{const t=localStorage.getItem(Rv);if(t==="light"||t==="dark")return t}catch{}return(e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}const Vn=yn(e=>({themeMode:Av(),setThemeMode:t=>e({themeMode:t}),toggleTheme:()=>e(t=>({themeMode:t.themeMode==="dark"?"light":"dark"}))})),Iv="2026.5.1",$v={version:Iv},vd=$v.version,{Text:Dv}=pe,Lv=({collapsed:e,onNewChat:t,onOpenSettings:s,screens:n,token:o})=>{const{t:a}=ie(),i=Vn(h=>h.themeMode),l=Vn(h=>h.toggleTheme),c=a("chat.sidebar.newSession"),u=a("settings.page.title"),d=i==="dark"?a("settings.app.lightMode","Light mode"):a("settings.app.darkMode","Dark mode");return r.jsxs(V,{vertical:!0,gap:e?"small":"middle",style:{padding:e?10:16,background:"transparent",borderTop:`1px solid ${o.colorBorderSecondary}`},children:[r.jsx(B,{"data-testid":"new-chat","data-tour-id":"new-session",type:"primary",icon:r.jsx(Ks,{}),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(V,{gap:8,align:"center",children:[r.jsx(B,{"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:u,"aria-label":u,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&&u}),!e&&r.jsx(Re,{title:d,placement:"top",children:r.jsx(B,{"data-testid":"toggle-theme",type:"text",icon:i==="dark"?r.jsx(mx,{}):r.jsx(hx,{}),onClick:l,"aria-label":d,className:"lotus-toolbar-icon",style:{width:44,height:44,borderRadius:o.borderRadiusLG,flexShrink:0}})})]}),!e&&r.jsxs(Dv,{type:"secondary","data-testid":"app-version-badge",style:{fontSize:o.fontSizeSM,textAlign:"center",userSelect:"text"},children:[a("settings.appTab.runningVersion","Running version"),": v",vd]})]})},Ou="provider",Xs=yn(e=>({isOpen:!1,origin:"chat",activeTabKey:Ou,open:(t,s=Ou)=>e({isOpen:!0,origin:t,activeTabKey:s}),close:()=>e({isOpen:!1}),setActiveTabKey:t=>e({activeTabKey:t})}));function Ce(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 z(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 Gf=function(){const{crypto:e}=globalThis;if(e!=null&&e.randomUUID)return Gf=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 mc(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const hc=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 Me extends Error{}class Mt extends Me{constructor(t,s,n,o){super(`${Mt.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:hc(s)});const a=s==null?void 0:s.error;return t===400?new Jf(t,a,n,o):t===401?new Qf(t,a,n,o):t===403?new Zf(t,a,n,o):t===404?new eg(t,a,n,o):t===409?new tg(t,a,n,o):t===422?new sg(t,a,n,o):t===429?new ng(t,a,n,o):t>=500?new rg(t,a,n,o):new Mt(t,a,n,o)}}class os extends Mt{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}}class Fi extends Mt{constructor({message:t,cause:s}){super(void 0,void 0,t||"Connection error.",void 0),s&&(this.cause=s)}}class wd extends Fi{constructor({message:t}={}){super({message:t??"Request timed out."})}}class Jf extends Mt{}class Qf extends Mt{}class Zf extends Mt{}class eg extends Mt{}class tg extends Mt{}class sg extends Mt{}class ng extends Mt{}class rg extends Mt{}class og extends Me{constructor(){super("Could not parse response content as the length limit was reached")}}class ag extends Me{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 Ov=/^[a-z][a-z0-9+.-]*:/i,Fv=e=>Ov.test(e);let Nt=e=>(Nt=Array.isArray,Nt(e)),Fu=Nt;function zv(e){return typeof e!="object"?{}:e??{}}function Nv(e){if(!e)return!0;for(const t in e)return!1;return!0}function Bv(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function al(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}const Wv=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new Me(`${e} must be an integer`);if(t<0)throw new Me(`${e} must be a positive integer`);return t},Uv=e=>{try{return JSON.parse(e)}catch{return}},ga=e=>new Promise(t=>setTimeout(t,e)),cr="5.10.2",qv=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Hv(){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 Yv=()=>{var s;const e=Hv();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":cr,"X-Stainless-OS":Nu(Deno.build.os),"X-Stainless-Arch":zu(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":cr,"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":cr,"X-Stainless-OS":Nu(globalThis.process.platform??"unknown"),"X-Stainless-Arch":zu(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=Xv();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":cr,"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":cr,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Xv(){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 zu=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",Nu=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 Bu;const Vv=()=>Bu??(Bu=Yv());function Kv(){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 ig(...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 lg(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return ig({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 cg(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 Gv(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 Jv=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),dg="RFC3986",ug=e=>String(e),Wu={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:ug},Qv="RFC1738";let pc=(e,t)=>(pc=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),pc(e,t));const Ms=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),il=1024,Zv=(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,u=[];for(let d=0;d<c.length;++d){let h=c.charCodeAt(d);if(h===45||h===46||h===95||h===126||h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||o===Qv&&(h===40||h===41)){u[u.length]=c.charAt(d);continue}if(h<128){u[u.length]=Ms[h];continue}if(h<2048){u[u.length]=Ms[192|h>>6]+Ms[128|h&63];continue}if(h<55296||h>=57344){u[u.length]=Ms[224|h>>12]+Ms[128|h>>6&63]+Ms[128|h&63];continue}d+=1,h=65536+((h&1023)<<10|c.charCodeAt(d)&1023),u[u.length]=Ms[240|h>>18]+Ms[128|h>>12&63]+Ms[128|h>>6&63]+Ms[128|h&63]}i+=u.join("")}return i};function ew(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Uu(e,t){if(Nt(e)){const s=[];for(let n=0;n<e.length;n+=1)s.push(t(e[n]));return s}return t(e)}const mg={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},hg=function(e,t){Array.prototype.push.apply(e,Nt(t)?t:[t])};let qu;const bt={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Zv,encodeValuesOnly:!1,format:dg,formatter:ug,indices:!1,serializeDate(e){return(qu??(qu=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function tw(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}const ll={};function pg(e,t,s,n,o,a,i,l,c,u,d,h,p,f,y,g,S,v){let x=e,T=v,_=0,j=!1;for(;(T=T.get(ll))!==void 0&&!j;){const C=T.get(e);if(_+=1,typeof C<"u"){if(C===_)throw new RangeError("Cyclic object value");j=!0}typeof T.get(ll)>"u"&&(_=0)}if(typeof u=="function"?x=u(t,x):x instanceof Date?x=p==null?void 0:p(x):s==="comma"&&Nt(x)&&(x=Uu(x,function(C){return C instanceof Date?p==null?void 0:p(C):C})),x===null){if(a)return c&&!g?c(t,bt.encoder,S,"key",f):t;x=""}if(tw(x)||ew(x)){if(c){const C=g?t:c(t,bt.encoder,S,"key",f);return[(y==null?void 0:y(C))+"="+(y==null?void 0:y(c(x,bt.encoder,S,"value",f)))]}return[(y==null?void 0:y(t))+"="+(y==null?void 0:y(String(x)))]}const P=[];if(typeof x>"u")return P;let M;if(s==="comma"&&Nt(x))g&&c&&(x=Uu(x,c)),M=[{value:x.length>0?x.join(",")||null:void 0}];else if(Nt(u))M=u;else{const C=Object.keys(x);M=d?C.sort(d):C}const R=l?String(t).replace(/\./g,"%2E"):String(t),E=n&&Nt(x)&&x.length===1?R+"[]":R;if(o&&Nt(x)&&x.length===0)return E+"[]";for(let C=0;C<M.length;++C){const k=M[C],b=typeof k=="object"&&typeof k.value<"u"?k.value:x[k];if(i&&b===null)continue;const w=h&&l?k.replace(/\./g,"%2E"):k,A=Nt(x)?typeof s=="function"?s(E,w):E:E+(h?"."+w:"["+w+"]");v.set(e,_);const I=new WeakMap;I.set(ll,v),hg(P,pg(b,A,s,n,o,a,i,l,s==="comma"&&g&&Nt(x)?null:c,u,d,h,p,f,y,g,S,I))}return P}function sw(e=bt){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||bt.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=dg;if(typeof e.format<"u"){if(!pc(Wu,e.format))throw new TypeError("Unknown format option provided.");s=e.format}const n=Wu[s];let o=bt.filter;(typeof e.filter=="function"||Nt(e.filter))&&(o=e.filter);let a;if(e.arrayFormat&&e.arrayFormat in mg?a=e.arrayFormat:"indices"in e?a=e.indices?"indices":"repeat":a=bt.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:bt.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:bt.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:bt.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:bt.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?bt.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:bt.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:bt.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:bt.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:bt.encodeValuesOnly,filter:o,format:s,formatter:n,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:bt.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:bt.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:bt.strictNullHandling}}function nw(e,t={}){let s=e;const n=sw(t);let o,a;typeof n.filter=="function"?(a=n.filter,s=a("",s)):Nt(n.filter)&&(a=n.filter,o=a);const i=[];if(typeof s!="object"||s===null)return"";const l=mg[n.arrayFormat],c=l==="comma"&&n.commaRoundTrip;o||(o=Object.keys(s)),n.sort&&o.sort(n.sort);const u=new WeakMap;for(let p=0;p<o.length;++p){const f=o[p];n.skipNulls&&s[f]===null||hg(i,pg(s[f],f,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,u))}const d=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&"),d.length>0?h+d:""}function rw(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 Hu;function _d(e){let t;return(Hu??(t=new globalThis.TextEncoder,Hu=t.encode.bind(t)))(e)}let Yu;function Xu(e){let t;return(Yu??(t=new globalThis.TextDecoder,Yu=t.decode.bind(t)))(e)}var Wt,Ut;class zi{constructor(){Wt.set(this,void 0),Ut.set(this,void 0),Ce(this,Wt,new Uint8Array),Ce(this,Ut,null)}decode(t){if(t==null)return[];const s=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?_d(t):t;Ce(this,Wt,rw([z(this,Wt,"f"),s]));const n=[];let o;for(;(o=ow(z(this,Wt,"f"),z(this,Ut,"f")))!=null;){if(o.carriage&&z(this,Ut,"f")==null){Ce(this,Ut,o.index);continue}if(z(this,Ut,"f")!=null&&(o.index!==z(this,Ut,"f")+1||o.carriage)){n.push(Xu(z(this,Wt,"f").subarray(0,z(this,Ut,"f")-1))),Ce(this,Wt,z(this,Wt,"f").subarray(z(this,Ut,"f"))),Ce(this,Ut,null);continue}const a=z(this,Ut,"f")!==null?o.preceding-1:o.preceding,i=Xu(z(this,Wt,"f").subarray(0,a));n.push(i),Ce(this,Wt,z(this,Wt,"f").subarray(o.index)),Ce(this,Ut,null)}return n}flush(){return z(this,Wt,"f").length?this.decode(`
13
13
  `):[]}}Wt=new WeakMap,Ut=new WeakMap;zi.NEWLINE_CHARS=new Set([`
14
14
  `,"\r"]);zi.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function ow(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 aw(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},Vu=(e,t,s)=>{if(e){if(Bv(bi,e))return e;jt(s).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(bi))}`)}};function Oo(){}function Ma(e,t,s){return!t||bi[e]>bi[s]?Oo:t[e].bind(t)}const iw={error:Oo,warn:Oo,info:Oo,debug:Oo};let Ku=new WeakMap;function jt(e){const t=e.logger,s=e.logLevel??"off";if(!t)return iw;const n=Ku.get(t);if(n&&n[0]===s)return n[1];const o={error:Ma("error",t,s),warn:Ma("warn",t,s),info:Ma("info",t,s),debug:Ma("debug",t,s)};return Ku.set(t,[s,o]),o}const Mn=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 zr;class Ls{constructor(t,s,n){this.iterator=t,zr.set(this,void 0),this.controller=s,Ce(this,zr,n)}static fromSSEResponse(t,s,n){let o=!1;const a=n?jt(n):console;async function*i(){if(o)throw new Me("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let l=!1;try{for await(const c of lw(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 u;try{u=JSON.parse(c.data)}catch(d){throw a.error("Could not parse message into JSON:",c.data),a.error("From chunk:",c.raw),d}if(u&&u.error)throw new Mt(void 0,u.error,void 0,t.headers);yield u}else{let u;try{u=JSON.parse(c.data)}catch(d){throw console.error("Could not parse message into JSON:",c.data),console.error("From chunk:",c.raw),d}if(c.event=="error")throw new Mt(void 0,u.error,u.message,void 0);yield{event:c.event,data:u}}}l=!0}catch(c){if(mc(c))return;throw c}finally{l||s.abort()}}return new Ls(i,s,n)}static fromReadableStream(t,s,n){let o=!1;async function*a(){const l=new zi,c=cg(t);for await(const u of c)for(const d of l.decode(u))yield d;for(const u of l.flush())yield u}async function*i(){if(o)throw new Me("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(mc(c))return;throw c}finally{l||s.abort()}}return new Ls(i,s,n)}[(zr=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 Ls(()=>o(t),this.controller,z(this,zr,"f")),new Ls(()=>o(s),this.controller,z(this,zr,"f"))]}toReadableStream(){const t=this;let s;return ig({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=_d(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*lw(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Me("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 Me("Attempted to iterate over a response with no body");const s=new dw,n=new zi,o=cg(e.body);for await(const a of cw(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*cw(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"?_d(s):s;let o=new Uint8Array(t.length+n.length);o.set(t),o.set(n,t.length),t=o;let a;for(;(a=aw(t))!==-1;)yield t.slice(0,a),t=t.slice(a)}t.length>0&&(yield t)}class dw{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(`
@@ -110,7 +110,7 @@ You are running on **${S_(e)}**.`;return e==="windows"?s+`
110
110
 
111
111
  `),Ey=()=>{try{return localStorage.getItem(Py)??""}catch(e){return console.error("Failed to load system prompt enhancement:",e),""}},C_=e=>{try{const t=e.trim()?e:"";localStorage.setItem(Py,t)}catch(t){console.error("Failed to save system prompt enhancement:",t)}},M_=e=>{const t=[];t.push(v_().trim()),t.push(k_().trim());const s=Ey().trim();return s&&t.push(s),Mc()&&t.push(g_().trim()),Ec()&&t.push(x_().trim()),(e??"").trim().toLowerCase()==="copilot"&&ki()&&t.push(__().trim()),t},P_=e=>j_(M_(e)),Rc=e=>{const t=(e??"").trim().toLowerCase();return t.includes("completion policy violation")&&t.includes("conclusion_with_options")},Ac=e=>{const t=(e??"").trim(),s=t?`
112
112
 
113
- 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 Ry(e){var E;const{modal:t,message:s}=ut.useApp(),{t:n}=ie(),o=m.useRef(null),a=m.useRef(null),i=m.useRef(""),l=m.useRef(new ds),c=L(C=>C.agentAvailability),u=L(C=>C.setAgentAvailability),d=L(C=>C.checkAgentAvailability),h=L(C=>C.startAgentHealthCheck),p=Hi(e.sessionId),f=ze(C=>C.currentProvider),y=L(C=>e.sessionId&&C.chats.find(k=>k.id===e.sessionId)||null),g=Ud((E=y==null?void 0:y.config)==null?void 0:E.model_ref);m.useEffect(()=>{h()},[h]);const S=m.useCallback(()=>{var k;(k=o.current)==null||k.abort();const C=y==null?void 0:y.id;C&&l.current.stopGeneration(C).catch(b=>{console.error("[useMessageStreaming] Failed to stop generation:",b)})},[y==null?void 0:y.id]),v=m.useCallback(C=>{var re;const k=L.getState(),w=(Array.isArray(k.chats)?k.chats:[]).find(q=>q.id===C),A=k.pendingQuestionRespond,I=(A==null?void 0:A.sessionId)===C?A:null,$=(re=w==null?void 0:w.config)==null?void 0:re.syncCursor,W=!!I||!!($!=null&&$.hasPendingQuestion),O=(I==null?void 0:I.toolCallId)??($==null?void 0:$.pendingQuestionToolCallId)??null;return{client_message_count:($==null?void 0:$.messageCount)??(w==null?void 0:w.messageCount)??0,client_last_message_id:($==null?void 0:$.lastMessageId)??null,client_has_pending_question:W,client_pending_question_tool_call_id:O}},[]),x=m.useCallback((C,k)=>{const b=k.sync;if(!b)return;const w=L.getState(),I=(Array.isArray(w.chats)?w.chats:[]).find($=>$.id===C);I&&e.updateSession(C,{messageCount:b.server_message_count,config:{...I.config||{},syncCursor:{messageCount:b.server_message_count,lastMessageId:b.server_last_message_id??null,hasPendingQuestion:b.has_pending_question,pendingQuestionToolCallId:b.pending_question_tool_call_id??null}}})},[e]),T=m.useCallback(async C=>{try{return await we.get(`respond/${C}/pending`)}catch(k){return console.warn(`[useMessageStreaming] Failed to fetch pending question for ${C}:`,k),{has_pending_question:!1}}},[]),_=m.useCallback(async(C,k,b)=>{var O,re;e.setSessionProcessing(C,!1),await L.getState().loadChatHistory(C,{mode:"replace"});const w=await T(C),A=L.getState().setPendingQuestionRespond,I=L.getState().clearPendingQuestionRespondForSession;if(w.has_pending_question){A({sessionId:C,question:w.question||"",options:w.options||[],allowCustom:w.allow_custom??!0,toolCallId:w.tool_call_id??null});const q=L.getState().chats.find(Z=>Z.id===C);return q&&e.updateSession(C,{config:{...q.config||{},syncCursor:{messageCount:q.messageCount??q.messages.length,lastMessageId:((re=(O=q.config)==null?void 0:O.syncCursor)==null?void 0:re.lastMessageId)??null,hasPendingQuestion:!0,pendingQuestionToolCallId:w.tool_call_id??null}}}),null}if(I(C),!((k==null?void 0:k.has_pending_user_message)??!1))return null;e.setSessionProcessing(C,!0),await new Promise(q=>setTimeout(q,0));const W=b?await l.current.execute(C,void 0,b,v(C),g??void 0):await l.current.execute(C,void 0,void 0,v(C),g??void 0);return x(C,W),W},[g,x,v,e,T]),j=m.useCallback(async(C,k,b)=>{var $,W;let w=k;x(C,w);const A=2;let I=0;for(;($=w.sync)!=null&&$.need_sync&&I<A;){const O=await _(C,w.sync,b);if(I+=1,!O){e.setSessionProcessing(C,!1);return}w=O,x(C,w)}if((W=w.sync)!=null&&W.need_sync){console.warn(`[useMessageStreaming] Execute remains out-of-sync after ${A} recovery attempt(s) for session ${C}.`,w.sync),e.setSessionProcessing(C,!1);return}if(!["started","already_running"].includes(w.status)){if(w.status==="completed"){it("[Streaming]","[Agent] Session already completed"),e.setSessionProcessing(C,!1);return}throw console.error("[Agent] Execute failed:",w.status),e.setSessionProcessing(C,!1),new Error(`Execute failed: ${w.status}`)}},[x,e,_]),P=m.useCallback(async(C,k,b,w,A)=>{var $,W;if(!p)throw new Error(n("chat.model.noModelSelected"));const I=new AbortController;o.current=I;try{const O=P_(f).trim(),re=(f??"").trim().toLowerCase()==="copilot"&&ki(),Z=((($=y==null?void 0:y.config)==null?void 0:$.workspacePath)||"").trim().replace(/\/+$/,"").replace(/\\+$/,""),X=await l.current.sendMessage({message:C,session_id:k,enhance_prompt:O||void 0,copilot_conclusion_with_options_enhancement_enabled:re,workspace_path:Z||void 0,selected_skill_ids:A&&A.length>0?A:void 0,images:(W=b.images)==null?void 0:W.filter(K=>!!K.base64).map(K=>({base64:K.base64,name:K.name,size:K.size,type:K.type})),model:p,...g?{model_ref:g,provider:g.provider}:{}}),{session_id:se}=X;se!==k&&console.warn(`[useMessageStreaming] Backend returned unexpected session_id=${se} for sessionId=${k}`),await L.getState().loadChatHistory(k,{mode:"replace"}),e.setSessionProcessing(k,!0),await new Promise(K=>setTimeout(K,0));const ee=w?await l.current.execute(k,void 0,w,v(k),g??void 0):await l.current.execute(k,void 0,void 0,v(k),g??void 0);it("[Streaming]","[Agent] Execute status:",ee.status),await j(k,ee,w)}catch(O){throw O}},[p,g,v,y,f,e,j,n]),M=m.useCallback(async(C,k,b,w)=>{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 A=c;if(A===null&&(A=await d()),!A){s.error(n("chat.streaming.agentUnavailable"));return}if(!p){s.error(n("chat.streaming.modelConfigNotLoaded"));return}const I=e.sessionId,$=(k==null?void 0:k.map(O=>({id:O.id,base64:O.base64,name:O.name,size:O.size,type:O.type})))||[],W={role:"user",content:C,id:crypto.randomUUID(),createdAt:new Date().toISOString(),images:$};await e.addMessage(I,W);try{it("[Streaming]","[useChatStreaming] Using Agent Server"),await P(C,I,W,b,w)}catch(O){if(a.current&&qe.clear(I,a.current),a.current=null,i.current="",O instanceof Error&&O.name==="AbortError")s.info(n("chat.streaming.requestCancelled"));else{console.error("[useChatStreaming] Failed to send message:",O);const re=O instanceof Error?O.message:String(O??"");Rc(re)?s.error(Ac(re)):(s.error(n("chat.streaming.sendFailed")),u(!1))}e.setSessionProcessing(I,!1)}finally{o.current=null,a.current&&qe.clear(I,a.current),a.current=null,i.current=""}},[c,s,d,y,e,t,P,u,p,n]),R=m.useCallback(async(C,k="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 b=c;if(b===null&&(b=await d()),!b){s.error(n("chat.streaming.agentUnavailable"));return}const w=e.sessionId;a.current&&qe.clear(w,a.current),a.current=null,i.current="";try{const A=k==="error_retry"?"error_retry":"after_last_user",I=await l.current.truncateSessionMessages(w,{mode:A});(k==="regenerate"||(I.messages_removed??0)>0)&&await L.getState().loadChatHistory(w,{mode:"replace"}),e.setSessionProcessing(w,!0);const $=C?await l.current.execute(w,void 0,C,v(w),g??void 0):await l.current.execute(w,void 0,void 0,v(w),g??void 0);await j(w,$,C)}catch(A){console.error("[useMessageStreaming] Retry failed:",A);const I=A instanceof Error?A.message:String(A??"");Rc(I)?s.error(Ac(I)):s.error(n("chat.streaming.retryFailed")),e.setSessionProcessing(w,!1)}finally{o.current=null}},[p,g,c,s,v,d,y,e,j,t,n]);return{sendMessage:M,retryLastTurn:R,cancel:S,agentAvailable:c}}function E_(e,t){const s=m.useMemo(()=>e.baseMessages,[e.baseMessages]),n=m.useCallback(async()=>{var u;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(d=>d.role==="user");if(!l)return;const c="content"in l?l.content:l.displayText;typeof c=="string"&&await((u=t==null?void 0:t.onRetry)==null?void 0:u.call(t,c))},[e,t]);return{currentMessages:s,retryLastMessage:n}}const R_=()=>{const e=h_(),t=Hd(e),s=p_(e),n=Ry({sessionId:e.currentSessionId,addMessage:e.addMessage,setSessionProcessing:e.setSessionProcessing,updateSession:e.updateSession}),o=E_(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}},Ay="lotus_vdi_safe_mode",ji=()=>{try{return localStorage.getItem(Ay)==="true"}catch{return!1}},A_=e=>{try{localStorage.setItem(Ay,e.toString())}catch(t){console.error("[vdiSafeMode] Failed to persist setting:",t)}},{Text:Oa}=pe,{useToken:I_}=xe,$_=({httpProxy:e,httpsProxy:t,onHttpProxyChange:s,onHttpsProxyChange:n,onReload:o,onSave:a,isLoading:i})=>{const{t:l}=ie(),{token:c}=I_(),u=bs(_=>_.proxyAuthStatus),d=bs(_=>_.isLoadingProxyAuthStatus),h=bs(_=>_.loadProxyAuthStatus),p=bs(_=>_.applyProxyAuth),f=bs(_=>_.clearProxyAuth),[y,g]=m.useState({username:"",password:""}),[S,v]=m.useState(!1);m.useEffect(()=>{h()},[h]);const x=async()=>{const _=y.username.trim();if(_){v(!0);try{await p({username:_,password:y.password}),g({username:"",password:""})}catch(j){console.error("Failed to apply proxy auth:",j)}finally{v(!1)}}},T=async()=>{v(!0);try{await f()}catch(_){console.error("Failed to clear proxy auth:",_)}finally{v(!1)}};return r.jsx(te,{size:"small",title:r.jsx(Oa,{strong:!0,children:l("settings.networkCard.title")}),className:"lotus-settings-card",children:r.jsxs(U,{direction:"vertical",size:c.marginSM,style:{width:"100%"},children:[r.jsx(tt,{message:l("settings.networkCard.guideTip"),type:"info",showIcon:!0}),r.jsxs(U,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[r.jsx(Oa,{type:"secondary",children:l("settings.networkCard.httpProxy")}),r.jsx(be,{"data-testid":"proxy-url",style:{width:"100%"},value:e,onChange:_=>s(_.target.value),placeholder:l("settings.networkCard.proxyPlaceholder"),disabled:i})]}),r.jsxs(U,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[r.jsx(Oa,{type:"secondary",children:l("settings.networkCard.httpsProxy")}),r.jsx(be,{style:{width:"100%"},value:t,onChange:_=>n(_.target.value),placeholder:l("settings.networkCard.proxyPlaceholder"),disabled:i})]}),r.jsx(te,{size:"small",title:l("settings.networkCard.proxyAuthTitle"),className:"lotus-settings-card",style:{marginTop:c.marginSM},children:u!=null&&u.configured?r.jsxs(U,{direction:"vertical",style:{width:"100%"},children:[r.jsx(tt,{type:"success",message:l("settings.networkCard.proxyConfiguredForUser",{username:u.username??""}),showIcon:!0}),r.jsx(B,{onClick:T,loading:S||d,danger:!0,children:l("settings.networkCard.clearCredentials")})]}):r.jsxs(U,{direction:"vertical",size:c.marginXS,style:{width:"100%"},children:[r.jsx(be,{placeholder:l("settings.networkCard.username"),value:y.username,onChange:_=>g(j=>({...j,username:_.target.value}))}),r.jsx(be.Password,{placeholder:l("settings.networkCard.password"),value:y.password,onChange:_=>g(j=>({...j,password:_.target.value}))}),r.jsx(B,{type:"primary",onClick:x,loading:S||d,disabled:!y.username.trim(),children:l("settings.networkCard.apply")})]})}),r.jsx(Oa,{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(B,{onClick:()=>Promise.resolve(o()).finally(()=>h({force:!0})),disabled:i,children:l("settings.networkCard.reload")}),r.jsx(B,{"data-testid":"save-proxy-settings",type:"primary",onClick:()=>Promise.resolve(a()).finally(()=>h({force:!0})),disabled:i,children:l("settings.networkCard.save")})]})]})})},{Text:D_}=pe,{useToken:L_}=xe,O_=({msgApi:e})=>{const{t}=ie(),{token:s}=L_(),[n]=ne.useForm(),[o,a]=m.useState(!1),[i,l]=m.useState(!1),[c,u]=m.useState(!1),[d,h]=m.useState(!1),[p,f]=m.useState(null),y=c&&!d,g=m.useMemo(()=>c?d?t("settings.configTab.accessPassword.helperLocalBypass","当前是本地访问,可直接修改访问密码,无需输入当前密码。"):t("settings.configTab.accessPassword.helperRemote","当前是远程访问。修改访问密码前,必须先输入当前密码。"):t("settings.configTab.accessPassword.helperNotEnabled","未设置访问密码。设置后,远程访问需要先输入密码,本地 loopback 访问可直接绕过。"),[d,c,t]),S=m.useCallback(async()=>{a(!0),f(null);try{const x=await ot.getAccessStatus();u(x.password_enabled),h(x.local_bypass)}catch(x){const T=x instanceof Error?x.message:t("settings.configTab.accessPassword.loadStatusFailed","Failed to load access status");f(T)}finally{a(!1)}},[t]);m.useEffect(()=>{S()},[S]);const v=async()=>{var x;try{const T=await n.validateFields();l(!0),await ot.updateAccessPassword({current_password:((x=T.currentPassword)==null?void 0:x.trim())||void 0,new_password:T.newPassword.trim()}),e.success(c?t("settings.configTab.accessPassword.updated","访问密码已更新"):t("settings.configTab.accessPassword.enabled","访问密码已设置")),n.resetFields(),await S()}catch(T){if(T.errorFields)return;const _=T instanceof Error?T.message:t("settings.configTab.accessPassword.updateFailed","Failed to update access password");e.error(_)}finally{l(!1)}};return r.jsx(te,{size:"small",className:"lotus-settings-card",title:r.jsx(D_,{strong:!0,children:t("settings.configTab.accessPasswordTitle","访问密码")}),children:r.jsxs(U,{direction:"vertical",size:s.marginMD,style:{width:"100%"},children:[r.jsx(tt,{type:c?"info":"warning",showIcon:!0,message:c?t("settings.configTab.accessPassword.statusEnabled","访问密码已启用"):t("settings.configTab.accessPassword.statusDisabled","访问密码未启用"),description:g}),p?r.jsx(tt,{type:"error",showIcon:!0,message:p}):null,r.jsxs(ne,{form:n,layout:"vertical",disabled:o||i,children:[y?r.jsx(ne.Item,{label:t("settings.configTab.accessPassword.currentPasswordLabel","当前密码"),name:"currentPassword",rules:[{required:!0,message:t("settings.configTab.accessPassword.validation.currentPasswordRequired","请输入当前密码")}],children:r.jsx(be.Password,{autoComplete:"current-password"})}):null,r.jsx(ne.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(be.Password,{autoComplete:"new-password"})}),r.jsx(ne.Item,{label:t("settings.configTab.accessPassword.confirmPasswordLabel","确认密码"),name:"confirmPassword",dependencies:["newPassword"],rules:[{required:!0,message:t("settings.configTab.accessPassword.validation.confirmPasswordRequired","请再次输入新密码")},({getFieldValue:x})=>({validator(T,_){return!_||x("newPassword")===_?Promise.resolve():Promise.reject(new Error(t("settings.configTab.accessPassword.validation.passwordMismatch","两次输入的密码不一致")))}})],children:r.jsx(be.Password,{autoComplete:"new-password"})}),r.jsx(B,{type:"primary",loading:i,onClick:()=>void v(),children:c?t("settings.configTab.accessPassword.updateAction","更新访问密码"):t("settings.configTab.accessPassword.enableAction","启用访问密码")})]})]})})},{Text:Jt}=pe,{useToken:F_}=xe,vm="http://127.0.0.1:9562/v1",Xo=e=>[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort(),z_=e=>{var s;const t=(s=e.tools)==null?void 0:s.disabled;return Array.isArray(t)?Xo(t.filter(n=>typeof n=="string")):[]},N_=({msgApi:e,locale:t,onLocaleChange:s})=>{const{t:n}=ie(),{token:o}=F_(),[a,i]=m.useState({http_proxy:"",https_proxy:"",memory:{auto_dream_enabled:!1,background_model:""}}),[l,c]=m.useState(vm),[u,d]=m.useState([]),[h,p]=m.useState([]),[f,y]=m.useState([]),[g,S]=m.useState(!1),[v,x]=m.useState(!1),T=m.useCallback(async()=>{var $,W;S(!0);try{const[O,re]=await Promise.all([ot.getBambooConfig(),ot.getBambooTools()]);i({http_proxy:O.http_proxy||"",https_proxy:O.https_proxy||"",memory:{auto_dream_enabled:(($=O.memory)==null?void 0:$.auto_dream_enabled)??!1,background_model:((W=O.memory)==null?void 0:W.background_model)||""}});const q=z_(O);p(q),y(q),d(Xo(re.tools||[]))}catch(O){console.error("Failed to load config:",O),e.error(n("settings.configTab.loadConfigFailed"))}finally{S(!1)}},[e,n]);m.useEffect(()=>{T()},[T]);const _=$=>{i(W=>({...W,http_proxy:$}))},j=$=>{i(W=>({...W,https_proxy:$}))},P=$=>{i(W=>({...W,memory:{...W.memory,auto_dream_enabled:$}}))},M=$=>{i(W=>({...W,memory:{...W.memory,background_model:$}}))},R=async()=>{var $,W;S(!0);try{const O=await ot.validateBambooConfigPatch(a);if(!O.valid){const q=((W=($=O.errors)==null?void 0:$.proxy)==null?void 0:W[0])??Object.values(O.errors||{}).flat().filter(Boolean)[0];e.error((q==null?void 0:q.message)||n("settings.configTab.invalidConfig"));return}await ot.setBambooConfig(a),e.success(n("settings.configTab.saveConfigSuccess"))}catch(O){console.error("Failed to save config:",O);const re=O instanceof Error&&O.message.trim()?O.message:n("settings.configTab.saveConfigFailed");e.error(re)}finally{S(!1)}},E=async()=>{e.success(n("settings.configTab.backendSaved"))},C=()=>{c(vm),e.success(n("settings.configTab.backendResetDefault"))},k=($,W)=>{p(O=>{const re=new Set(O);return W?re.delete($):re.add($),Xo([...re])})},b=async()=>{x(!0);try{const $=await ot.getBambooTools();d(Xo($.tools||[])),e.success(n("settings.configTab.toolsReloadSuccess"))}catch($){console.error("Failed to reload tools:",$),e.error(n("settings.configTab.toolsLoadFailed"))}finally{x(!1)}},w=async()=>{x(!0);try{const $=Xo(h);await ot.setBambooConfig({tools:{disabled:$}}),p($),y($),e.success(n("settings.configTab.toolsSaveSuccess"))}catch($){console.error("Failed to save tool settings:",$),e.error(n("settings.configTab.toolsSaveFailed"))}finally{x(!1)}},A=JSON.stringify(h)!==JSON.stringify(f),I=new Set(h);return r.jsx(Ss,{spinning:g,tip:n("settings.common.loading"),children:r.jsx(ui,{items:[{key:"general",label:n("settings.configTab.tabs.general"),children:r.jsxs(U,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[r.jsx(tt,{message:n("settings.configTab.providerMovedTitle"),description:n("settings.configTab.providerMovedDescription"),type:"info",showIcon:!0,closable:!0}),r.jsx($_,{httpProxy:a.http_proxy,httpsProxy:a.https_proxy,onHttpProxyChange:_,onHttpsProxyChange:j,onReload:T,onSave:R,isLoading:g}),r.jsx(te,{size:"small",className:"lotus-settings-card",title:r.jsx(Jt,{strong:!0,children:n("settings.configTab.language")}),children:r.jsx(Le,{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:$=>s($)})}),r.jsx(te,{size:"small",className:"lotus-settings-card",title:r.jsx(Jt,{strong:!0,children:n("settings.configTab.memoryTitle")}),children:r.jsxs(U,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[r.jsx(Jt,{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(Jt,{strong:!0,children:n("settings.configTab.autoDreamEnabled")}),r.jsx("div",{children:r.jsx(Jt,{type:"secondary",style:{fontSize:o.fontSizeSM},children:n("settings.configTab.autoDreamEnabledHint")})})]}),r.jsx(ft,{"data-testid":"auto-dream-toggle",checked:a.memory.auto_dream_enabled,onChange:P})]}),r.jsxs(U,{direction:"vertical",size:o.marginXXS,style:{width:"100%"},children:[r.jsx(Jt,{strong:!0,children:n("settings.configTab.backgroundModel")}),r.jsx(be,{"data-testid":"auto-dream-background-model-input",value:a.memory.background_model,onChange:$=>M($.target.value),placeholder:n("settings.configTab.backgroundModelPlaceholder")}),r.jsx(Jt,{type:"secondary",style:{fontSize:o.fontSizeSM},children:n("settings.configTab.backgroundModelHint")})]}),r.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:r.jsx(B,{"data-testid":"save-memory-settings",type:"primary",onClick:R,loading:g,children:n("settings.configTab.save")})})]})}),r.jsx(te,{size:"small",title:r.jsx(Jt,{strong:!0,children:n("settings.configTab.backendApiBaseUrlTitle")}),children:r.jsxs(U,{direction:"vertical",size:o.marginSM,style:{width:"100%"},children:[r.jsx(U,{direction:"vertical",size:o.marginXXS,style:{width:"100%"},children:r.jsx(be,{style:{width:"100%"},value:l,onChange:$=>c($.target.value),placeholder:n("settings.configTab.backendApiPlaceholder")})}),r.jsx(Jt,{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(B,{"data-testid":"reset-to-defaults",onClick:C,children:n("settings.configTab.resetToDefault")}),r.jsx(B,{"data-testid":"save-api-settings",type:"primary",onClick:E,children:n("settings.configTab.save")})]})]})}),r.jsx(O_,{msgApi:e})]})},{key:"tools",label:n("settings.configTab.tabs.tools"),children:r.jsx(te,{size:"small",title:r.jsx(Jt,{strong:!0,children:n("settings.configTab.toolsTitle")}),children:r.jsxs(U,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[r.jsx(Jt,{type:"secondary",children:n("settings.configTab.toolsDescription")}),u.length===0?r.jsx(tt,{type:"info",showIcon:!0,message:n("settings.configTab.toolsEmpty")}):r.jsx(lt,{bordered:!0,dataSource:u,renderItem:$=>r.jsx(lt.Item,{actions:[r.jsx(ft,{checked:!I.has($),onChange:W=>k($,W)},`${$}-switch`)],children:r.jsx(Jt,{code:!0,children:$})})}),r.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:o.marginSM},children:[r.jsx(B,{onClick:b,loading:v,children:n("settings.configTab.reloadTools")}),r.jsx(B,{type:"primary",onClick:w,loading:v,disabled:!A,children:n("settings.configTab.save")})]})]})})}]})})},wm={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},Xd=yn()(bS(e=>({settings:wm,updateSettings:t=>e(s=>({settings:{...s.settings,...t}})),resetSettings:()=>e({settings:wm})}),{name:"mermaid-settings"})),Xi=()=>Xd(t=>t.settings),B_=()=>Xd(e=>e.updateSettings),W_=()=>Xd(e=>e.resetSettings),{Title:U_,Text:Sl}=pe,{useToken:q_}=xe,H_=()=>{const{t:e}=ie(),{token:t}=q_(),s=Xi(),n=B_(),o=W_(),[a]=ne.useForm();xt.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(U_,{level:3,style:{marginBottom:"8px"},children:e("settings.mermaidTab.title")}),r.jsx(Sl,{type:"secondary",style:{display:"block",marginBottom:"24px"},children:e("settings.mermaidTab.description")}),r.jsxs(ne,{form:a,layout:"vertical",initialValues:s,onValuesChange:i,children:[r.jsxs(te,{title:e("settings.mermaidTab.themeCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:[r.jsx(ns,{gutter:16,children:r.jsx(Be,{span:24,children:r.jsx(ne.Item,{name:"theme",label:r.jsxs(U,{children:[e("settings.mermaidTab.themeLabel"),r.jsx(Re,{title:e("settings.mermaidTab.themeTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsxs(Le,{children:[r.jsx(Le.Option,{value:"default",children:e("settings.mermaidTab.themeOptions.default")}),r.jsx(Le.Option,{value:"neutral",children:e("settings.mermaidTab.themeOptions.neutral")}),r.jsx(Le.Option,{value:"dark",children:e("settings.mermaidTab.themeOptions.dark")}),r.jsx(Le.Option,{value:"forest",children:e("settings.mermaidTab.themeOptions.forest")}),r.jsx(Le.Option,{value:"base",children:e("settings.mermaidTab.themeOptions.base")})]})})})}),r.jsxs(Sl,{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(te,{title:e("settings.mermaidTab.globalCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:[r.jsxs(ns,{gutter:16,children:[r.jsx(Be,{span:12,children:r.jsx(ne.Item,{name:"fontSize",label:r.jsxs(U,{children:[e("settings.mermaidTab.fontSizeLabel"),r.jsx(Re,{title:e("settings.mermaidTab.fontSizeTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:10,max:32,step:1,style:{width:"100%"},addonAfter:"px"})})}),r.jsx(Be,{span:12,children:r.jsx(ne.Item,{name:"defaultScale",label:r.jsxs(U,{children:[e("settings.mermaidTab.defaultZoomLabel"),r.jsx(Re,{title:e("settings.mermaidTab.defaultZoomTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:.1,max:3,step:.1,style:{width:"100%"}})})})]}),r.jsx(ne.Item,{name:"useMaxWidth",label:r.jsxs(U,{children:[e("settings.mermaidTab.responsiveWidthLabel"),r.jsx(Re,{title:e("settings.mermaidTab.responsiveWidthTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),valuePropName:"checked",children:r.jsx(ft,{})})]}),r.jsx(te,{title:e("settings.mermaidTab.flowchartCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsxs(ns,{gutter:16,children:[r.jsx(Be,{span:8,children:r.jsx(ne.Item,{name:"flowchartNodeSpacing",label:r.jsxs(U,{children:[e("settings.mermaidTab.flowchartNodeSpacingLabel"),r.jsx(Re,{title:e("settings.mermaidTab.flowchartNodeSpacingTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:20,max:200,step:10,style:{width:"100%"}})})}),r.jsx(Be,{span:8,children:r.jsx(ne.Item,{name:"flowchartRankSpacing",label:r.jsxs(U,{children:[e("settings.mermaidTab.flowchartRankSpacingLabel"),r.jsx(Re,{title:e("settings.mermaidTab.flowchartRankSpacingTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:20,max:200,step:10,style:{width:"100%"}})})}),r.jsx(Be,{span:8,children:r.jsx(ne.Item,{name:"flowchartCurve",label:r.jsxs(U,{children:[e("settings.mermaidTab.flowchartCurveTypeLabel"),r.jsx(Re,{title:e("settings.mermaidTab.flowchartCurveTypeTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsxs(Le,{children:[r.jsx(Le.Option,{value:"basis",children:e("settings.mermaidTab.flowchartCurveOptions.basis")}),r.jsx(Le.Option,{value:"linear",children:e("settings.mermaidTab.flowchartCurveOptions.linear")}),r.jsx(Le.Option,{value:"cardinal",children:e("settings.mermaidTab.flowchartCurveOptions.cardinal")})]})})})]})}),r.jsx(te,{title:e("settings.mermaidTab.sequenceCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsxs(ns,{gutter:16,children:[r.jsx(Be,{span:6,children:r.jsx(ne.Item,{name:"sequenceActorMargin",label:r.jsxs(U,{children:[e("settings.mermaidTab.sequenceActorMarginLabel"),r.jsx(Re,{title:e("settings.mermaidTab.sequenceActorMarginTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:20,max:200,step:10,style:{width:"100%"}})})}),r.jsx(Be,{span:6,children:r.jsx(ne.Item,{name:"sequenceMessageMargin",label:r.jsxs(U,{children:[e("settings.mermaidTab.sequenceMessageMarginLabel"),r.jsx(Re,{title:e("settings.mermaidTab.sequenceMessageMarginTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:10,max:100,step:5,style:{width:"100%"}})})}),r.jsx(Be,{span:6,children:r.jsx(ne.Item,{name:"sequenceWidth",label:r.jsxs(U,{children:[e("settings.mermaidTab.sequenceActorWidthLabel"),r.jsx(Re,{title:e("settings.mermaidTab.sequenceActorWidthTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:100,max:300,step:10,style:{width:"100%"}})})}),r.jsx(Be,{span:6,children:r.jsx(ne.Item,{name:"sequenceHeight",label:r.jsxs(U,{children:[e("settings.mermaidTab.sequenceActorHeightLabel"),r.jsx(Re,{title:e("settings.mermaidTab.sequenceActorHeightTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:40,max:150,step:5,style:{width:"100%"}})})})]})}),r.jsx(te,{title:e("settings.mermaidTab.ganttCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsxs(ns,{gutter:16,children:[r.jsx(Be,{span:12,children:r.jsx(ne.Item,{name:"ganttBarHeight",label:r.jsxs(U,{children:[e("settings.mermaidTab.ganttBarHeightLabel"),r.jsx(Re,{title:e("settings.mermaidTab.ganttBarHeightTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:10,max:50,step:5,style:{width:"100%"},addonAfter:"px"})})}),r.jsx(Be,{span:12,children:r.jsx(ne.Item,{name:"ganttTopPadding",label:r.jsxs(U,{children:[e("settings.mermaidTab.ganttTopPaddingLabel"),r.jsx(Re,{title:e("settings.mermaidTab.ganttTopPaddingTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:20,max:100,step:10,style:{width:"100%"}})})})]})}),r.jsx(U,{children:r.jsx(B,{icon:r.jsx(fx,{}),onClick:l,children:e("settings.mermaidTab.resetToDefaults")})}),r.jsx($t,{}),r.jsx(te,{title:e("settings.mermaidTab.previewTitle"),styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsx(Sl,{type:"secondary",children:e("settings.mermaidTab.previewDescription")})})]})]})},Y_=m.lazy(()=>Dt(()=>import("./index-v1C2DQLr.js"),__vite__mapDeps([0,1,2,3,4,5,6,7]),import.meta.url)),{Text:_n}=pe,{useToken:X_}=xe,V_=({promptEnhancement:e,onPromptEnhancementChange:t,mermaidEnhancementEnabled:s,taskEnhancementEnabled:n,showCopilotConclusionWithOptionsEnhancement:o,copilotConclusionWithOptionsEnhancementEnabled:a,onMermaidToggle:i,onTaskToggle:l,onCopilotConclusionWithOptionsToggle:c,onSaveEnhancement:u})=>{const{t:d}=ie(),{token:h}=X_(),p=h.marginLG;return r.jsxs(V,{vertical:!0,gap:p,children:[r.jsx(te,{size:"small",className:"lotus-settings-card",children:r.jsx(m.Suspense,{fallback:r.jsx(Ss,{size:"small"}),children:r.jsx(Y_,{})})}),r.jsx(te,{size:"small",className:"lotus-settings-card",children:r.jsxs(U,{direction:"vertical",size:h.marginXS,style:{width:"100%"},children:[r.jsx(_n,{strong:!0,children:d("settings.promptsTab.title")}),r.jsxs(V,{align:"center",gap:h.marginSM,children:[r.jsx(_n,{strong:!0,children:d("settings.promptsTab.mermaidEnhancement")}),r.jsx(ft,{checked:s,onChange:i})]}),r.jsxs(V,{align:"center",gap:h.marginSM,children:[r.jsx(_n,{strong:!0,children:d("settings.promptsTab.taskListRules")}),r.jsx(ft,{checked:n,onChange:l})]}),o&&r.jsxs(U,{direction:"vertical",size:h.marginXXS,style:{width:"100%"},children:[r.jsxs(V,{align:"center",gap:h.marginSM,children:[r.jsx(_n,{strong:!0,children:d("settings.promptsTab.copilotConclusionWithOptionsBeforeFinish")}),r.jsx(ft,{checked:a,onChange:c})]}),r.jsx(_n,{type:"secondary",style:{fontSize:h.fontSizeSM},children:d("settings.promptsTab.copilotConclusionWithOptionsBeforeFinishDescription",{defaultValue:T_()})})]}),r.jsx(be.TextArea,{rows:6,placeholder:d("settings.promptsTab.enhancementPlaceholder"),value:e,onChange:f=>t(f.target.value)}),r.jsx(V,{justify:"flex-end",children:r.jsx(B,{type:"primary",onClick:u,children:d("settings.promptsTab.saveEnhancement")})}),r.jsx(_n,{type:"secondary",style:{fontSize:h.fontSizeSM},children:d("settings.promptsTab.description")})]})}),s&&r.jsx(ws,{size:"small",items:[{key:"mermaid",label:r.jsx(_n,{strong:!0,children:d("settings.mermaidTab.title")}),children:r.jsx(H_,{})}]})]})},Vd="bodhi_onboarding_complete",K_=()=>localStorage.getItem(Vd)==="true",G_=()=>localStorage.setItem(Vd,"true"),J_=()=>localStorage.removeItem(Vd),Q_=["new-session","task-templates","model-picker","sidebar","open-settings"],Z_=()=>{const e={};for(const t of Q_)e[t]=document.querySelector(`[data-tour-id="${t}"]`);return e},e0=({disabled:e=!1})=>{const{t}=ie(),[s,n]=m.useState(!1),[o,a]=m.useState(null);m.useEffect(()=>{if(e||K_())return;const c=setTimeout(()=>{const u=Z_();a(u),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=()=>{G_(),n(!1)};return r.jsx(gx,{open:s,onClose:l,steps:i})},{Text:Ps}=pe,{useToken:t0}=xe,s0=({autoGenerateTitles:e,isUpdatingAutoTitlePreference:t,onAutoTitleToggle:s,themeMode:n,onThemeModeChange:o,vdiSafeMode:a,onVdiSafeModeToggle:i,onClearLocalStorage:l,onResetApp:c,isResetting:u,darkModeKey:d})=>{const{t:h}=ie(),{token:p}=t0();return r.jsx(te,{size:"small",className:"lotus-settings-card",children:r.jsxs(U,{direction:"vertical",size:p.marginSM,style:{width:"100%"},children:[r.jsxs(V,{align:"center",gap:p.marginSM,children:[r.jsx(Ps,{strong:!0,children:h("settings.appTab.autoGenerateTitle")}),r.jsx(ft,{checked:e,loading:t,onChange:s})]}),r.jsx(Ps,{type:"secondary",style:{fontSize:p.fontSizeSM},children:h("settings.appTab.autoGenerateTitleDesc")}),r.jsxs(V,{align:"center",justify:"space-between",gap:p.marginSM,children:[r.jsx(Ps,{strong:!0,children:h("settings.appTab.runningVersion","Running version")}),r.jsxs(Ps,{code:!0,"data-testid":"settings-app-version",children:["v",vd]})]}),r.jsx(Ps,{type:"secondary",style:{fontSize:p.fontSizeSM},children:h("settings.appTab.runningVersionDesc","This is the currently running Lotus frontend version.")}),r.jsxs(V,{align:"center",gap:p.marginSM,children:[r.jsx(Ps,{strong:!0,children:h("settings.appTab.darkMode")}),r.jsx(ft,{"data-testid":"dark-mode-toggle",checked:n==="dark",onChange:f=>{const y=f?"dark":"light";o(y),localStorage.setItem(d,y)}})]}),r.jsxs(V,{align:"center",gap:p.marginSM,children:[r.jsx(Ps,{strong:!0,children:h("settings.appTab.vdiSafeMode","Graphics compatibility mode")}),r.jsx(ft,{"data-testid":"vdi-safe-mode-toggle",checked:a,onChange:i})]}),r.jsx(Ps,{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(B,{block:!0,icon:r.jsx(rd,{}),onClick:()=>{J_(),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(B,{danger:!0,block:!0,icon:r.jsx(gn,{}),children:h("settings.appTab.clearLocalStorageButton")})}),r.jsx($t,{style:{margin:`${p.marginSM}px 0`}}),r.jsxs(V,{align:"center",gap:p.marginSM,children:[r.jsx(ua,{style:{color:p.colorError}}),r.jsx(Ps,{strong:!0,style:{color:p.colorError},children:h("settings.appTab.dangerZone")})]}),r.jsx(Ps,{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(B,{"data-testid":"reset-to-defaults",danger:!0,block:!0,type:"primary",icon:r.jsx(Sf,{}),loading:u,children:h("settings.appTab.resetButton")})})]})})},{Text:Tn}=pe,{useToken:n0}=xe,_m=[{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,}"}],r0=(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:is.t("settings.keywordMaskingTab.invalidRegexPattern")}}},o0=()=>{const{t:e}=ie(),{message:t}=ut.useApp(),{token:s}=n0(),[n,o]=m.useState([]),[a,i]=m.useState(!1),[l,c]=m.useState(null),[u,d]=m.useState(""),[h,p]=m.useState("exact"),[f,y]=m.useState(!0),[g,S]=m.useState(),[v,x]=m.useState("My token is sk-123"),T=m.useCallback(async()=>{try{i(!0);const w=await vs.getInstance().getKeywordMaskingConfig();o(w.entries)}catch(b){t.error(e("settings.keywordMaskingTab.loadFailed")),console.error(b)}finally{i(!1)}},[e]);m.useEffect(()=>{T()},[T]);const _=async b=>{try{const w=vs.getInstance(),A=await w.validateKeywordEntries(b);if(!A.valid&&A.errors){const $=A.errors.map(W=>`Entry ${W.index+1}: ${W.message}`).join("; ");return t.error(`${e("settings.keywordMaskingTab.validationFailedPrefix")}: ${$}`),!1}const I=await w.updateKeywordMaskingConfig(b);return o(I.entries),t.success(e("settings.keywordMaskingTab.saveSuccess")),!0}catch(w){return t.error(w instanceof Error?w.message:e("settings.keywordMaskingTab.saveFailed")),!1}},j=async()=>{const b={pattern:"",match_type:"exact",enabled:!0},w=[...n,b];o(w),c(w.length-1),d(""),p("exact"),y(!0),S(void 0)},P=b=>{const w=n[b];c(b),d(w.pattern),p(w.match_type),y(w.enabled),S(void 0)},M=async()=>{if(l===null)return;if(!u.trim()){t.error(e("settings.keywordMaskingTab.patternRequired"));return}const b=[...n];b[l]={pattern:u.trim(),match_type:h,enabled:f},await _(b)&&c(null)},R=()=>{var b;l!==null&&!((b=n[l])!=null&&b.pattern)&&o(n.filter((w,A)=>A!==l)),c(null)},E=async b=>{const w=n.filter((A,I)=>I!==b);await _(w)},C=async(b,w)=>{const A=[...n];A[b]={...A[b],enabled:w},await _(A)},k=r0(v,u,h);return r.jsx(te,{className:"lotus-settings-card",title:e("settings.keywordMaskingTab.title"),extra:r.jsx(B,{"data-testid":"add-keyword",type:"primary",icon:r.jsx(Ks,{}),onClick:j,loading:a,children:e("settings.keywordMaskingTab.addKeyword")}),children:r.jsxs(U,{direction:"vertical",style:{width:"100%"},size:"large",children:[r.jsx(Tn,{type:"secondary",children:e("settings.keywordMaskingTab.description")}),r.jsx(lt,{loading:a,dataSource:n,locale:{emptyText:e("settings.keywordMaskingTab.empty")},renderItem:(b,w)=>r.jsx(lt.Item,{style:{backgroundColor:s.colorFillAlter,marginBottom:8,borderRadius:s.borderRadius,padding:12},actions:l===w?[r.jsx(B,{"data-testid":"save-keyword",type:"primary",icon:r.jsx(Di,{}),onClick:M,"aria-label":e("settings.keywordMaskingTab.save")},"save"),r.jsx(B,{onClick:R,children:e("settings.keywordMaskingTab.cancel")},"cancel")]:[r.jsx(B,{icon:r.jsx(ca,{}),onClick:()=>P(w),"aria-label":e("settings.keywordMaskingTab.edit")},"edit"),r.jsx(B,{"data-testid":`delete-keyword-${w}`,danger:!0,icon:r.jsx(gn,{}),onClick:()=>E(w),"aria-label":e("settings.keywordMaskingTab.delete")},"delete")],children:r.jsx(V,{vertical:!0,style:{width:"100%"},gap:8,children:l===w?r.jsxs(r.Fragment,{children:[r.jsx(be,{"data-testid":"keyword-pattern-input",placeholder:e("settings.keywordMaskingTab.patternPlaceholder"),value:u,onChange:A=>d(A.target.value),autoFocus:!0}),r.jsxs(V,{gap:8,align:"center",wrap:"wrap",children:[r.jsx(Le,{"data-testid":"keyword-examples-select","aria-label":e("settings.keywordMaskingTab.examples"),placeholder:e("settings.keywordMaskingTab.examples"),value:g,onChange:A=>{S(A);const I=_m.find($=>$.value===A);I&&(d(I.pattern),p(I.match_type))},options:_m.map(A=>({value:A.value,label:e(A.labelKey)})),style:{minWidth:220}}),r.jsx(Le,{value:h,onChange:p,options:[{value:"exact",label:e("settings.keywordMaskingTab.exactMatch")},{value:"regex",label:e("settings.keywordMaskingTab.regexPattern")}],style:{width:150}}),r.jsx(ft,{checked:f,onChange:y})]}),r.jsxs(V,{vertical:!0,gap:6,children:[r.jsx(Tn,{type:"secondary",children:e("settings.keywordMaskingTab.sampleText")}),r.jsx(be,{placeholder:e("settings.keywordMaskingTab.sampleTextPlaceholder"),value:v,onChange:A=>x(A.target.value)}),r.jsx(Tn,{type:"secondary",children:e("settings.keywordMaskingTab.maskedPreview")}),r.jsx(be,{readOnly:!0,value:k.masked,status:k.error?"error":void 0}),k.error&&r.jsx(Tn,{type:"danger",children:k.error})]})]}):r.jsxs(V,{justify:"space-between",align:"center",children:[r.jsxs(V,{vertical:!0,gap:4,children:[r.jsx(Tn,{strong:!0,children:b.pattern||e("settings.keywordMaskingTab.emptyPattern")}),r.jsxs(V,{gap:8,children:[r.jsx(Tn,{type:"secondary",style:{fontSize:12},children:b.match_type==="regex"?e("settings.keywordMaskingTab.regexPattern"):e("settings.keywordMaskingTab.exactMatch")}),!b.enabled&&r.jsx(Tn,{type:"warning",style:{fontSize:12},children:e("settings.keywordMaskingTab.disabled")})]})]}),r.jsx(ft,{checked:b.enabled,onChange:A=>C(w,A),size:"small"})]})})})})]})})},{Text:nr,Paragraph:a0}=pe,i0=/^[A-Za-z_][A-Za-z0-9_]*$/,l0=()=>{const{t:e}=ie(),{message:t}=ut.useApp(),[s,n]=m.useState([]),[o,a]=m.useState(!1),[i,l]=m.useState(!1),[c,u]=m.useState(null),[d]=ne.useForm(),h=m.useCallback(async()=>{a(!0);try{const x=await zt.getEnvVars();n(x.entries)}catch{t.error(e("settings.envVars.fetchError","Failed to load environment variables"))}finally{a(!1)}},[e]);m.useEffect(()=>{h()},[h]);const p=async x=>{var _;const T={name:x.name.trim(),value:x.value,secret:x.secret??!1,description:((_=x.description)==null?void 0:_.trim())||void 0};try{const j=await zt.upsertEnvVar(T);n(j.entries),t.success(c?e("settings.envVars.updated","Variable updated"):e("settings.envVars.created","Variable created")),S()}catch(j){t.error((j instanceof Error?j.message:void 0)||e("settings.envVars.saveError","Failed to save variable"))}},f=async x=>{try{const T=await zt.deleteEnvVar(x);n(T.entries),t.success(e("settings.envVars.deleted","Variable deleted"))}catch(T){t.error((T instanceof Error?T.message:void 0)||e("settings.envVars.deleteError","Failed to delete variable"))}},y=()=>{u(null),d.resetFields(),d.setFieldsValue({secret:!1}),l(!0)},g=x=>{u(x.name),d.setFieldsValue({name:x.name,value:"",secret:x.secret,description:x.description??""}),l(!0)},S=()=>{l(!1),u(null),d.resetFields()},v=[{title:e("settings.envVars.name","Name"),dataIndex:"name",key:"name",render:x=>r.jsx(nr,{code:!0,children:x})},{title:e("settings.envVars.value","Value"),dataIndex:"value",key:"value",render:(x,T)=>T.secret?r.jsxs(nr,{type:"secondary",children:[r.jsx(uu,{style:{marginRight:4}}),T.has_value?"••••••••":e("settings.envVars.notSet","(not set)")]}):r.jsx(nr,{children:x||r.jsx(nr,{type:"secondary",children:e("settings.envVars.empty","(empty)")})})},{title:e("settings.envVars.type","Type"),key:"secret",width:100,render:(x,T)=>T.secret?r.jsx(ue,{color:"warning",icon:r.jsx(uu,{}),children:e("settings.envVars.secret","Secret")}):r.jsx(ue,{color:"processing",children:e("settings.envVars.plain","Plain")})},{title:e("settings.envVars.descriptionCol","Description"),dataIndex:"description",key:"description",ellipsis:!0,render:x=>x?r.jsx(nr,{type:"secondary",children:x}):r.jsx(nr,{type:"secondary",italic:!0,children:"—"})},{title:e("settings.envVars.actions","Actions"),key:"actions",width:120,render:(x,T)=>r.jsxs(U,{size:"small",children:[r.jsx(B,{type:"text",size:"small",icon:r.jsx(ca,{}),onClick:()=>g(T),"aria-label":e("settings.envVars.edit","Edit")}),r.jsx(mi,{title:e("settings.envVars.deleteConfirm","Delete this variable?"),onConfirm:()=>f(T.name),okText:e("settings.envVars.yes","Yes"),cancelText:e("settings.envVars.no","No"),children:r.jsx(B,{type:"text",size:"small",danger:!0,icon:r.jsx(gn,{}),"aria-label":e("settings.envVars.delete","Delete")})})]})}];return r.jsxs("div",{style:{maxWidth:900},children:[r.jsxs(te,{className:"lotus-settings-card",title:e("settings.envVars.title","Environment Variables"),extra:r.jsx(B,{type:"primary",icon:r.jsx(Ks,{}),onClick:y,children:e("settings.envVars.addButton","Add Variable")}),children:[r.jsx(a0,{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(Gs,{dataSource:s,columns:v,rowKey:"name",size:"small",pagination:!1,loading:o,locale:{emptyText:e("settings.envVars.noVars","No environment variables configured")}})]}),r.jsx(Bt,{title:c?e("settings.envVars.editTitle","Edit Variable"):e("settings.envVars.addTitle","Add Environment Variable"),open:i,onCancel:S,onOk:()=>d.submit(),okText:e("settings.envVars.save","Save"),cancelText:e("settings.envVars.cancel","Cancel"),destroyOnClose:!0,children:r.jsxs(ne,{form:d,layout:"vertical",onFinish:p,initialValues:{secret:!1},children:[r.jsx(ne.Item,{name:"name",label:e("settings.envVars.name","Name"),rules:[{required:!0,message:e("settings.envVars.nameRequired","Variable name is required")},{pattern:i0,message:e("settings.envVars.nameInvalid","Must start with a letter or underscore, followed by letters, digits, or underscores")}],children:r.jsx(be,{placeholder:"GITHUB_TOKEN",disabled:c!==null,autoFocus:c===null})}),r.jsx(ne.Item,{name:"value",label:e("settings.envVars.value","Value"),rules:[{required:c===null,message:e("settings.envVars.valueRequired","Value is required for new variables")}],extra:c?e("settings.envVars.valueEditHint","Leave empty to keep the existing value"):void 0,children:r.jsx(be.Password,{placeholder:c?e("settings.envVars.valuePlaceholderEdit","Enter new value or leave empty"):e("settings.envVars.valuePlaceholder","Enter value"),visibilityToggle:!0})}),r.jsx(ne.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(ft,{})}),r.jsx(ne.Item,{name:"description",label:e("settings.envVars.descriptionField","Description"),children:r.jsx(be,{placeholder:e("settings.envVars.descriptionPlaceholder","Optional description")})})]})})]})},On=class On{constructor(){}static getInstance(){return On.instance||(On.instance=new On),On.instance}async listWorkflows(){try{it("[WorkflowManager]","[WorkflowManagerService] Listing workflows");const t=await je.get("bamboo/workflows"),s=Array.isArray(t)?t:[];return it("[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{it("[WorkflowManager]","[WorkflowManagerService] Getting workflow: "+t);const s=await je.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 it("[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),ES(s)&&s.status===404?new Error("Workflow '"+t+"' not found"):s instanceof Error&&s.message.includes("404")?new Error("Workflow '"+t+"' not found"):s}}};Je(On,"instance");let Ic=On;const{Text:vl}=pe,{TextArea:c0}=be,{useToken:d0}=xe,u0=e=>!(!e||e.includes("/")||e.includes("\\")||e.includes("..")),m0=()=>{const{t:e}=ie(),{token:t}=d0(),[s,n]=fn.useMessage(),[o,a]=m.useState([]),[i,l]=m.useState(!1),[c,u]=m.useState(!1),[d,h]=m.useState(!1),[p,f]=m.useState(null),[y,g]=m.useState(""),[S,v]=m.useState(""),[x,T]=m.useState(!1),_=m.useMemo(()=>Ic.getInstance(),[]),j=m.useCallback(async()=>{l(!0);try{const C=await _.listWorkflows();return a(C),C}catch{return s.error(e("settings.workflowsTab.loadFailed")),[]}finally{l(!1)}},[s,e,_]);m.useEffect(()=>{j()},[j]);const P=m.useCallback(async C=>{f(C),g(C.name),T(!1),u(!0);try{const k=await _.getWorkflow(C.name);v(k.content??"")}catch{s.error(e("settings.workflowsTab.loadContentFailed")),v("")}finally{u(!1)}},[s,e,_]),M=()=>{f(null),g(""),v(""),T(!1)},R=m.useCallback(async()=>{if(!u0(y)){s.error(e("settings.workflowsTab.invalidName"));return}const C=o.some(k=>k.name===y);if(!p&&C){s.error(e("settings.workflowsTab.nameAlreadyExists"));return}h(!0);try{await vs.getInstance().saveWorkflow(y,S),s.success(e("settings.workflowsTab.saved")),T(!1);const w=(await j()).find(A=>A.name===y);w&&f(w)}catch(k){s.error(k instanceof Error?k.message:e("settings.workflowsTab.saveFailed"))}finally{h(!1)}},[S,y,j,s,p,e,o]),E=m.useCallback(async C=>{try{await vs.getInstance().deleteWorkflow(C.name),s.success(e("settings.workflowsTab.deleted")),(p==null?void 0:p.name)===C.name&&M(),await j()}catch(k){s.error(k instanceof Error?k.message:e("settings.workflowsTab.deleteFailed"))}},[j,s,p,e]);return r.jsxs("div",{style:{padding:"24px"},children:[n,r.jsxs(te,{title:e("settings.workflowsTab.title"),extra:r.jsxs(U,{children:[r.jsx(B,{icon:r.jsx(Zs,{}),onClick:j,loading:i,children:e("settings.workflowsTab.refresh")}),r.jsx(B,{"data-testid":"create-workflow",icon:r.jsx(Ks,{}),onClick:M,children:e("settings.workflowsTab.newWorkflow")}),r.jsx(B,{"data-testid":"save-workflow",type:"primary",icon:r.jsx(Di,{}),onClick:R,loading:d,disabled:!x,children:e("settings.workflowsTab.save")})]}),children:[r.jsx(vl,{type:"secondary",children:e("settings.workflowsTab.description")}),r.jsxs(V,{gap:t.marginLG,style:{marginTop:t.marginLG},children:[r.jsx("div",{style:{width:320,flexShrink:0},children:r.jsx(lt,{loading:i,dataSource:o,locale:{emptyText:e("settings.workflowsTab.empty")},renderItem:C=>r.jsx(lt.Item,{style:{cursor:"pointer",backgroundColor:(p==null?void 0:p.name)===C.name?t.colorFillSecondary:"transparent",borderRadius:t.borderRadius,padding:t.paddingSM},onClick:()=>P(C),actions:[r.jsx(B,{"data-testid":`delete-workflow-${C.name}`,type:"text",danger:!0,size:"small",icon:r.jsx(gn,{}),onClick:k=>{k.stopPropagation(),E(C)},"aria-label":e("settings.workflowsTab.delete")},"delete")],children:r.jsxs(U,{direction:"vertical",size:0,children:[r.jsxs(vl,{strong:!0,children:["/",C.name]}),r.jsx(vl,{type:"secondary",style:{fontSize:12},children:C.filename})]})})})}),r.jsx("div",{style:{flex:1},children:r.jsxs(U,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx(be,{"data-testid":"workflow-name",placeholder:e("settings.workflowsTab.namePlaceholder"),value:y,onChange:C=>{g(C.target.value),T(!0)},disabled:!!p,prefix:r.jsx(ca,{})}),r.jsx(c0,{"data-testid":"workflow-content",placeholder:e("settings.workflowsTab.contentPlaceholder"),value:S,onChange:C=>{v(C.target.value),T(!0)},autoSize:{minRows:12},disabled:c})]})})]})]})]})};var ye=(e=>(e.Connecting="connecting",e.Ready="ready",e.Degraded="degraded",e.Stopped="stopped",e.Error="error",e))(ye||{});const Sa=6e4,va=3e4,aa=2e4,Ci=1e4,Vi=e=>({id:e,enabled:!0,transport:{type:"stdio",command:"",args:[],env:{},startup_timeout_ms:aa},request_timeout_ms:Sa,healthcheck_interval_ms:va,allowed_tools:[],denied_tools:[]}),h0=()=>({status:"stopped",tool_count:0,restart_count:0}),p0=e=>{switch(typeof e=="string"?e.trim().toLowerCase():""){case ye.Connecting:return ye.Connecting;case ye.Ready:return ye.Ready;case ye.Degraded:return ye.Degraded;case ye.Error:return ye.Error;case ye.Stopped:default:return ye.Stopped}},Ys=(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},f0=(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:Ys(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:Ys(s.startup_timeout_ms,aa)}},g0=(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:Ys(n.request_timeout_ms,Sa),healthcheck_interval_ms:Ys(n.healthcheck_interval_ms,va),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:Ys(n.reconnect.initial_backoff_ms,1e3),max_backoff_ms:Ys(n.reconnect.max_backoff_ms,3e4),max_attempts:Ys(n.reconnect.max_attempts,0)}:void 0,transport:f0(n.transport,s.transport)}},y0=e=>{const t=h0(),n=e.runtime??{},o=n.status??e.status;return{status:p0(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:Ys(n.tool_count??e.tool_count,t.tool_count),restart_count:Ys(n.restart_count??e.restart_count,t.restart_count),last_ping_at:typeof n.last_ping_at=="string"?n.last_ping_at:void 0}},b0=e=>{const t=g0(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:y0(e)}},x0=(e,t)=>`mcp__${e}__${t}`,S0=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}},v0=(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"?S0(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?x0(i,l):""),u=typeof n.description=="string"?n.description:"",d=n,h="parameters"in d?d.parameters:"inputSchema"in d?d.inputSchema:"input_schema"in d?d.input_schema:void 0,p=c||l||`mcp_tool_${s}`;return{alias:p,server_id:i||"unknown",original_name:l||p,description:u,parameters:h}};class w0{async getServers(){const t=await we.get("mcp/servers");return Array.isArray(t.servers)?t.servers.map(b0):[]}async addServer(t){return we.post("mcp/servers",t)}async updateServer(t,s){const n={...s,id:t};return we.put(`mcp/servers/${t}`,n)}async deleteServer(t){return we.delete(`mcp/servers/${t}`)}async connectServer(t){return we.post(`mcp/servers/${t}/connect`)}async disconnectServer(t){return we.post(`mcp/servers/${t}/disconnect`)}async refreshTools(t){return we.post(`mcp/servers/${t}/refresh`)}async getTools(t){const s=t?`mcp/servers/${t}/tools`:"mcp/tools",n=await we.get(s);return(Array.isArray(n.tools)?n.tools:[]).map((a,i)=>v0(a,t,i)).filter(a=>!!a)}async importServers(t){return we.post("mcp/servers/import",t)}}const Iy=new w0,_0=5e3,Bs=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,Tm=(e,t)=>`${e}:${t}`,T0=(e={})=>{const{service:t=Iy,autoRefreshMs:s=_0,autoRefreshEnabled:n=!0}=e,[o,a]=m.useState([]),[i,l]=m.useState(null),[c,u]=m.useState({}),[d,h]=m.useState({}),[p,f]=m.useState({}),[y,g]=m.useState(!1),[S,v]=m.useState(!1),[x,T]=m.useState(!1),[_,j]=m.useState(null),P=m.useRef({}),M=m.useCallback(X=>{const se=new Set(X.map(K=>K.id)),ee=X.map(K=>{const Y=P.current[K.id]??K.config,G={...Y,id:K.id,name:Y.name??K.name};return P.current[K.id]=G,{...K,name:K.name||G.name||K.id,enabled:K.enabled??G.enabled,config:G}});return Object.keys(P.current).forEach(K=>{se.has(K)||delete P.current[K]}),ee},[]),R=m.useCallback(async({silent:X=!1}={})=>{X||g(!0);try{const se=await t.getServers(),ee=M(se);a(ee),l(K=>{var F;return K&&ee.some(Y=>Y.id===K)?K:((F=ee[0])==null?void 0:F.id)??null}),j(null)}catch(se){throw j(Bs(se,"Failed to load MCP servers")),se}finally{X||g(!1)}},[M,t]),E=m.useCallback(async(X,se=!1)=>{if(!X)return[];if(!se&&c[X])return c[X];h(ee=>({...ee,[X]:!0}));try{const ee=await t.getTools(X);return u(K=>({...K,[X]:ee})),j(null),ee}catch(ee){throw j(Bs(ee,"Failed to load MCP tools")),ee}finally{h(ee=>({...ee,[X]:!1}))}},[t,c]),C=m.useCallback((X,se,ee)=>{const K=Tm(X,se);f(F=>({...F,[K]:ee}))},[]),k=m.useCallback(async X=>{v(!0);try{await t.addServer(X),P.current[X.id]=X,await R()}catch(se){throw j(Bs(se,"Failed to add MCP server")),se}finally{v(!1)}},[R,t]),b=m.useCallback(async(X,se)=>{v(!0);try{const ee={...se,id:X};await t.updateServer(X,ee),P.current[X]=ee,await R()}catch(ee){throw j(Bs(ee,"Failed to update MCP server")),ee}finally{v(!1)}},[R,t]),w=m.useCallback(async X=>{C(X,"delete",!0);try{await t.deleteServer(X),u(se=>{const ee={...se};return delete ee[X],ee}),delete P.current[X],await R()}catch(se){throw j(Bs(se,"Failed to delete MCP server")),se}finally{C(X,"delete",!1)}},[R,t,C]),A=m.useCallback(async X=>{C(X,"connect",!0);try{await t.connectServer(X),await R({silent:!0})}catch(se){throw j(Bs(se,"Failed to connect MCP server")),se}finally{C(X,"connect",!1)}},[R,t,C]),I=m.useCallback(async X=>{C(X,"disconnect",!0);try{await t.disconnectServer(X),await R({silent:!0})}catch(se){throw j(Bs(se,"Failed to disconnect MCP server")),se}finally{C(X,"disconnect",!1)}},[R,t,C]),$=m.useCallback(async X=>{C(X,"refresh",!0);try{await t.refreshTools(X),await E(X,!0),await R({silent:!0})}catch(se){throw j(Bs(se,"Failed to refresh MCP tools")),se}finally{C(X,"refresh",!1)}},[E,R,t,C]),W=m.useCallback(async()=>{T(!0);try{const X=o.map(se=>se.id);await Promise.all(X.map(async se=>{try{await t.refreshTools(se)}catch{}})),await R(),i&&await E(i,!0)}catch(X){throw j(Bs(X,"Failed to refresh MCP status")),X}finally{T(!1)}},[E,R,i,o,t]),O=m.useCallback(X=>{l(X)},[]),re=m.useCallback((X,se)=>!!p[Tm(X,se)],[p]),q=m.useMemo(()=>i?c[i]??[]:[],[i,c]),Z=m.useMemo(()=>i?!!d[i]:!1,[i,d]);return m.useEffect(()=>{R().catch(()=>{})},[R]),m.useEffect(()=>{if(!n||s<=0)return;const X=window.setInterval(()=>{R({silent:!0}).catch(()=>{})},s);return()=>{window.clearInterval(X)}},[n,s,R]),m.useEffect(()=>{i&&E(i).catch(()=>{})},[E,i]),{servers:o,selectedServerId:i,selectedServerTools:q,isLoadingServers:y,isMutatingConfig:S,isRefreshingAll:x,isSelectedServerToolsLoading:Z,error:_,setSelectedServerId:O,refreshServers:R,addServer:k,updateServer:b,deleteServer:w,connectServer:A,disconnectServer:I,refreshServerTools:$,refreshAll:W,isServerActionLoading:re}},k0={[ye.Connecting]:"blue",[ye.Ready]:"green",[ye.Degraded]:"orange",[ye.Stopped]:"default",[ye.Error]:"red"},j0=e=>e===ye.Connecting||e===ye.Ready||e===ye.Degraded,C0=e=>{if(!e)return;const t=e.replace(/\s+/g," ").trim();if(t)return t.length>180?`${t.slice(0,180)}...`:t},M0=({servers:e,loading:t=!1,selectedServerId:s,onSelectServer:n,onEditServer:o,onDeleteServer:a,onConnectServer:i,onDisconnectServer:l,onRefreshTools:c,isServerActionLoading:u})=>{const{t:d}=ie(),{token:h}=xe.useToken(),p=m.useMemo(()=>({[ye.Connecting]:d("settings.mcpTab.statusHelp.connecting"),[ye.Ready]:d("settings.mcpTab.statusHelp.ready"),[ye.Degraded]:d("settings.mcpTab.statusHelp.degraded"),[ye.Stopped]:d("settings.mcpTab.statusHelp.stopped"),[ye.Error]:d("settings.mcpTab.statusHelp.error")}),[d]),f=m.useMemo(()=>[{key:"name",title:d("settings.mcpServerTable.columns.name"),render:(y,g)=>g.name||g.id},{key:"transport",title:d("settings.mcpServerTable.columns.transportType"),render:(y,g)=>g.config.transport.type==="sse"?d("settings.mcpServerTable.transportOptions.sse"):d("settings.mcpServerTable.transportOptions.stdio"),width:140},{key:"status",title:d("settings.mcpServerTable.columns.status"),render:(y,g)=>{var _,j;const S=((_=g.runtime)==null?void 0:_.status)??ye.Stopped,v=C0((j=g.runtime)==null?void 0:j.last_error),x=p[S],T={[ye.Connecting]:d("settings.mcpTab.status.connecting"),[ye.Ready]:d("settings.mcpTab.status.ready"),[ye.Degraded]:d("settings.mcpTab.status.degraded"),[ye.Stopped]:d("settings.mcpTab.status.stopped"),[ye.Error]:d("settings.mcpTab.status.error")};return r.jsx(Re,{title:v?`${x} ${d("settings.mcpTab.statusLastError",{error:v})}`:x,children:r.jsx(ue,{color:S===ye.Stopped?void 0:k0[S],style:{marginInlineEnd:0,cursor:"help",...S===ye.Stopped?{background:h.colorFillSecondary,borderColor:h.colorBorderSecondary,color:h.colorTextSecondary}:void 0},children:T[S]})})},width:120},{key:"toolCount",title:d("settings.mcpServerTable.columns.toolCount"),render:(y,g)=>{var S;return((S=g.runtime)==null?void 0:S.tool_count)??0},width:100},{key:"actions",title:d("settings.mcpServerTable.columns.actions"),width:360,render:(y,g)=>{var x;const S=((x=g.runtime)==null?void 0:x.status)??ye.Stopped,v=j0(S);return r.jsxs(U,{size:h.marginXS,children:[r.jsx(B,{size:"small",onClick:T=>{T.stopPropagation(),o==null||o(g)},children:d("settings.mcpServerTable.actions.edit")}),r.jsx(mi,{title:d("settings.mcpServerTable.deleteTitle"),description:d("settings.mcpServerTable.deleteDescription",{name:g.name||g.id}),onConfirm:()=>a==null?void 0:a(g),okText:d("settings.mcpServerTable.actions.delete"),okButtonProps:{danger:!0,loading:u==null?void 0:u(g.id,"delete")},children:r.jsx(B,{size:"small",danger:!0,loading:u==null?void 0:u(g.id,"delete"),onClick:T=>T.stopPropagation(),children:d("settings.mcpServerTable.actions.delete")})}),v?r.jsx(B,{size:"small",onClick:T=>{T.stopPropagation(),l==null||l(g)},loading:u==null?void 0:u(g.id,"disconnect"),children:d("settings.mcpServerTable.actions.disconnect")}):r.jsx(B,{size:"small",type:"primary",ghost:!0,onClick:T=>{T.stopPropagation(),i==null||i(g)},loading:u==null?void 0:u(g.id,"connect"),children:d("settings.mcpServerTable.actions.connect")}),r.jsx(B,{size:"small",onClick:T=>{T.stopPropagation(),c==null||c(g)},loading:u==null?void 0:u(g.id,"refresh"),children:d("settings.mcpServerTable.actions.refreshTools")})]})}}],[u,i,a,l,o,c,p,d,h.colorBorderSecondary,h.colorFillSecondary,h.colorTextSecondary,h.marginXS]);return r.jsx(Gs,{rowKey:"id",columns:f,dataSource:e,loading:t,pagination:!1,locale:{emptyText:d("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:km}=pe,{TextArea:P0}=be,jm=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||Sa,healthcheckIntervalMs:t.healthcheck_interval_ms||va,allowedTools:t.allowed_tools||[],deniedTools:t.denied_tools||[]}},E0=e=>e.reduce((t,s)=>{var o;const n=(o=s.key)==null?void 0:o.trim();return n&&(t[n]=s.value??""),t},{}),R0=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??""}}),Cm=(e,t,s)=>{var d,h,p;const n=t==="edit"&&(s==null?void 0:s.id)||e.id,o=(d=e.name)==null?void 0:d.trim(),a=typeof e.requestTimeoutMs=="number"?e.requestTimeoutMs:(s==null?void 0:s.request_timeout_ms)??Sa,i=typeof e.healthcheckIntervalMs=="number"?e.healthcheckIntervalMs:(s==null?void 0:s.healthcheck_interval_ms)??va,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)??[],u=e.transportType==="sse"?{type:"sse",url:((h=e.url)==null?void 0:h.trim())||"",headers:R0(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:E0(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:u,request_timeout_ms:a,healthcheck_interval_ms:i,allowed_tools:l,denied_tools:c,reconnect:s==null?void 0:s.reconnect}},Mm=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:Sa,l=typeof n.healthcheck_interval_ms=="number"?n.healthcheck_interval_ms:va,c=Array.isArray(n.allowed_tools)?n.allowed_tools.filter(h=>typeof h=="string"):[],u=Array.isArray(n.denied_tools)?n.denied_tools.filter(h=>typeof h=="string"):[],d=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 g=y,S=typeof g.name=="string"?g.name:"",v=typeof g.value=="string"?g.value:"";return S.trim()?{name:S,value:v}:null}).filter(y=>!!y):h&&typeof h=="object"?Object.entries(h).filter(([y])=>y.trim()).map(([y,g])=>({name:y,value:typeof g=="string"?g:""})):[],f=typeof n.connect_timeout_ms=="number"?n.connect_timeout_ms:Ci;return{valid:!0,config:{id:o,name:d,enabled:a,transport:{type:"sse",url:n.url,headers:p,connect_timeout_ms:f},request_timeout_ms:i,healthcheck_interval_ms:l,allowed_tools:c,denied_tools:u,reconnect:void 0}}}if(typeof n.command=="string"){const h=Array.isArray(n.args)?n.args.filter(g=>typeof g=="string"):[],p=n.env,f=p&&typeof p=="object"?Object.entries(p).reduce((g,[S,v])=>(typeof v=="string"&&(g[S]=v),g),{}):{},y=typeof n.startup_timeout_ms=="number"?n.startup_timeout_ms:aa;return{valid:!0,config:{id:o,name:d,enabled:a,transport:{type:"stdio",command:n.command,args:h,cwd:typeof n.cwd=="string"?n.cwd:void 0,env:f,startup_timeout_ms:y},request_timeout_ms:i,healthcheck_interval_ms:l,allowed_tools:c,denied_tools:u,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")})}}},A0=({open:e,mode:t,initialConfig:s,confirmLoading:n=!1,onCancel:o,onSubmit:a})=>{const{t:i}=ie(),[l]=ne.useForm(),[c,u]=m.useState("form"),[d,h]=m.useState(""),[p,f]=m.useState(null),y=m.useMemo(()=>jm(s),[s]),g=ne.useWatch("transportType",l)??"stdio";m.useEffect(()=>{e&&(l.setFieldsValue(y),h(Mm(s)),f(null),u("form"))},[l,y,s,e]);const S=()=>{l.resetFields(),h(""),f(null),o()},v=async()=>{if(c==="json"){const _=wl(d,i);if(!_.valid){f(_.error);return}f(null);try{await a(_.config),h("")}catch(j){console.error("MCP server JSON submission error:",j)}return}try{const _=await l.validateFields(),j=Cm(_,t,s);await a(j),l.resetFields()}catch(_){console.error("MCP server form submission error:",_)}},x=_=>{h(_),p&&wl(_,i).valid&&f(null)},T=_=>{if(_==="json")try{const j=l.getFieldsValue(),P=Cm(j,t,s);h(JSON.stringify(P,null,2))}catch{h(Mm(s))}else{const j=wl(d,i);j.valid&&l.setFieldsValue(jm(j.config))}u(_),f(null)};return r.jsxs(Bt,{title:i(t==="edit"?"settings.mcpServerForm.editTitle":"settings.mcpServerForm.addTitle"),open:e,onCancel:S,onOk:()=>{v()},okText:i("settings.mcpServerForm.save"),destroyOnClose:!0,forceRender:!0,confirmLoading:n,width:720,children:[r.jsx("div",{style:{marginBottom:16},children:r.jsxs(ls.Group,{value:c,onChange:_=>T(_.target.value),optionType:"button",buttonStyle:"solid",children:[r.jsxs(ls.Button,{value:"form",children:[r.jsx(yx,{})," ",i("settings.mcpServerForm.modeForm")]}),r.jsxs(ls.Button,{value:"json",children:[r.jsx(Li,{})," ",i("settings.mcpServerForm.modeJson")]})]})}),c==="json"&&p&&r.jsx(tt,{type:"error",message:i("settings.mcpServerForm.jsonError"),description:p,showIcon:!0,style:{marginBottom:16},closable:!0,onClose:()=>f(null)}),c==="json"?r.jsx(P0,{value:d,onChange:_=>x(_.target.value),rows:20,style:{fontFamily:"monospace",fontSize:13},placeholder:JSON.stringify(Vi("example-server"),null,2)}):r.jsxs(ne,{layout:"vertical",form:l,preserve:!0,initialValues:y,children:[r.jsx(ne.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(be,{placeholder:"filesystem",disabled:t==="edit",autoComplete:"off"})}),r.jsx(ne.Item,{name:"name",label:i("settings.mcpServerForm.displayName"),children:r.jsx(be,{placeholder:"Filesystem MCP",autoComplete:"off"})}),r.jsx(ne.Item,{name:"enabled",label:i("settings.mcpServerForm.enabled"),valuePropName:"checked",extra:i("settings.mcpServerForm.enabledHelp"),children:r.jsx(ft,{})}),r.jsx(ne.Item,{name:"transportType",label:i("settings.mcpServerForm.transportType"),rules:[{required:!0,message:i("settings.mcpServerForm.transportTypeRequired")}],children:r.jsx(Le,{options:[{label:i("settings.mcpServerForm.transportOptions.stdio"),value:"stdio"},{label:i("settings.mcpServerForm.transportOptions.sse"),value:"sse"}]})}),g==="stdio"?r.jsxs(r.Fragment,{children:[r.jsx(ne.Item,{name:"command",label:i("settings.mcpServerForm.command"),rules:[{required:!0,message:i("settings.mcpServerForm.commandRequired")}],children:r.jsx(be,{placeholder:"npx",autoComplete:"off"})}),r.jsx(ne.Item,{name:"args",label:i("settings.mcpServerForm.arguments"),children:r.jsx(Le,{mode:"tags",tokenSeparators:[","],placeholder:i("settings.mcpServerForm.argumentsPlaceholder"),open:!1})}),r.jsx(ne.List,{name:"envEntries",children:(_,{add:j,remove:P})=>r.jsxs(U,{direction:"vertical",style:{width:"100%"},children:[r.jsxs(U,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[r.jsx(km,{strong:!0,children:i("settings.mcpServerForm.envVars")}),r.jsx(B,{icon:r.jsx(Ks,{}),onClick:()=>j({key:"",value:""}),type:"dashed",children:i("settings.mcpServerForm.addEnv")})]}),_.map(M=>r.jsxs(U,{align:"baseline",style:{display:"flex"},children:[r.jsx(ne.Item,{...M,name:[M.name,"key"],rules:[{required:!0,message:i("settings.mcpServerForm.keyRequired")}],children:r.jsx(be,{placeholder:"MCP_ROOT",autoComplete:"off"})}),r.jsx(ne.Item,{...M,name:[M.name,"value"],children:r.jsx(be,{placeholder:"/Users/me/workspace",autoComplete:"off"})}),r.jsx(B,{danger:!0,type:"text",icon:r.jsx(nc,{}),onClick:()=>P(M.name),"aria-label":i("settings.mcpServerForm.removeEnv","Remove environment variable")})]},M.key))]})})]}):r.jsxs(r.Fragment,{children:[r.jsx(ne.Item,{name:"url",label:i("settings.mcpServerForm.sseUrl"),rules:[{required:!0,message:i("settings.mcpServerForm.sseUrlRequired")},{validator:async(_,j)=>{if(j)try{new URL(j)}catch{throw new Error(i("settings.mcpServerForm.validUrlRequired"))}}}],children:r.jsx(be,{placeholder:"http://localhost:4000/sse",autoComplete:"off"})}),r.jsx(ne.List,{name:"headerEntries",children:(_,{add:j,remove:P})=>r.jsxs(U,{direction:"vertical",style:{width:"100%"},children:[r.jsxs(U,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[r.jsx(km,{strong:!0,children:i("settings.mcpServerForm.headers")}),r.jsx(B,{icon:r.jsx(Ks,{}),onClick:()=>j({name:"",value:""}),type:"dashed",children:i("settings.mcpServerForm.addHeader")})]}),_.map(M=>r.jsxs(U,{align:"baseline",style:{display:"flex"},children:[r.jsx(ne.Item,{...M,name:[M.name,"name"],rules:[{required:!0,message:i("settings.mcpServerForm.headerNameRequired")}],children:r.jsx(be,{placeholder:"Authorization",autoComplete:"off"})}),r.jsx(ne.Item,{...M,name:[M.name,"value"],children:r.jsx(be,{placeholder:"Bearer token",autoComplete:"off"})}),r.jsx(B,{danger:!0,type:"text",icon:r.jsx(nc,{}),onClick:()=>P(M.name),"aria-label":i("settings.mcpServerForm.removeHeader","Remove header")})]},M.key))]})})]})]})]})},I0={maxLines:8,maxCharacters:500},un=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),on=e=>typeof e=="string"?e:void 0,In=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Pm=e=>typeof e=="boolean"?e:void 0,Kd=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const s=JSON.parse(t);return un(s)?s:null}catch{return null}},$y=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
+ 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 Ry(e){var E;const{modal:t,message:s}=ut.useApp(),{t:n}=ie(),o=m.useRef(null),a=m.useRef(null),i=m.useRef(""),l=m.useRef(new ds),c=L(C=>C.agentAvailability),u=L(C=>C.setAgentAvailability),d=L(C=>C.checkAgentAvailability),h=L(C=>C.startAgentHealthCheck),p=Hi(e.sessionId),f=ze(C=>C.currentProvider),y=L(C=>e.sessionId&&C.chats.find(k=>k.id===e.sessionId)||null),g=Ud((E=y==null?void 0:y.config)==null?void 0:E.model_ref);m.useEffect(()=>{h()},[h]);const S=m.useCallback(()=>{var k;(k=o.current)==null||k.abort();const C=y==null?void 0:y.id;C&&l.current.stopGeneration(C).catch(b=>{console.error("[useMessageStreaming] Failed to stop generation:",b)})},[y==null?void 0:y.id]),v=m.useCallback(C=>{var re;const k=L.getState(),w=(Array.isArray(k.chats)?k.chats:[]).find(q=>q.id===C),A=k.pendingQuestionRespond,I=(A==null?void 0:A.sessionId)===C?A:null,$=(re=w==null?void 0:w.config)==null?void 0:re.syncCursor,W=!!I||!!($!=null&&$.hasPendingQuestion),O=(I==null?void 0:I.toolCallId)??($==null?void 0:$.pendingQuestionToolCallId)??null;return{client_message_count:($==null?void 0:$.messageCount)??(w==null?void 0:w.messageCount)??0,client_last_message_id:($==null?void 0:$.lastMessageId)??null,client_has_pending_question:W,client_pending_question_tool_call_id:O}},[]),x=m.useCallback((C,k)=>{const b=k.sync;if(!b)return;const w=L.getState(),I=(Array.isArray(w.chats)?w.chats:[]).find($=>$.id===C);I&&e.updateSession(C,{messageCount:b.server_message_count,config:{...I.config||{},syncCursor:{messageCount:b.server_message_count,lastMessageId:b.server_last_message_id??null,hasPendingQuestion:b.has_pending_question,pendingQuestionToolCallId:b.pending_question_tool_call_id??null}}})},[e]),T=m.useCallback(async C=>{try{return await we.get(`respond/${C}/pending`)}catch(k){return console.warn(`[useMessageStreaming] Failed to fetch pending question for ${C}:`,k),{has_pending_question:!1}}},[]),_=m.useCallback(async(C,k,b)=>{var O,re;e.setSessionProcessing(C,!1),await L.getState().loadChatHistory(C,{mode:"replace"});const w=await T(C),A=L.getState().setPendingQuestionRespond,I=L.getState().clearPendingQuestionRespondForSession;if(w.has_pending_question){A({sessionId:C,question:w.question||"",options:w.options||[],allowCustom:w.allow_custom??!0,toolCallId:w.tool_call_id??null});const q=L.getState().chats.find(Z=>Z.id===C);return q&&e.updateSession(C,{config:{...q.config||{},syncCursor:{messageCount:q.messageCount??q.messages.length,lastMessageId:((re=(O=q.config)==null?void 0:O.syncCursor)==null?void 0:re.lastMessageId)??null,hasPendingQuestion:!0,pendingQuestionToolCallId:w.tool_call_id??null}}}),null}if(I(C),!((k==null?void 0:k.has_pending_user_message)??!1))return null;e.setSessionProcessing(C,!0),await new Promise(q=>setTimeout(q,0));const W=b?await l.current.execute(C,void 0,b,v(C),g??void 0):await l.current.execute(C,void 0,void 0,v(C),g??void 0);return x(C,W),W},[g,x,v,e,T]),j=m.useCallback(async(C,k,b)=>{var $,W;let w=k;x(C,w);const A=2;let I=0;for(;($=w.sync)!=null&&$.need_sync&&I<A;){const O=await _(C,w.sync,b);if(I+=1,!O){e.setSessionProcessing(C,!1);return}w=O,x(C,w)}if((W=w.sync)!=null&&W.need_sync){console.warn(`[useMessageStreaming] Execute remains out-of-sync after ${A} recovery attempt(s) for session ${C}.`,w.sync),e.setSessionProcessing(C,!1);return}if(!["started","already_running"].includes(w.status)){if(w.status==="completed"){it("[Streaming]","[Agent] Session already completed"),e.setSessionProcessing(C,!1);return}throw console.error("[Agent] Execute failed:",w.status),e.setSessionProcessing(C,!1),new Error(`Execute failed: ${w.status}`)}},[x,e,_]),P=m.useCallback(async(C,k,b,w,A)=>{var $,W;if(!p)throw new Error(n("chat.model.noModelSelected"));const I=new AbortController;o.current=I;try{const O=P_(f).trim(),re=(f??"").trim().toLowerCase()==="copilot"&&ki(),Z=((($=y==null?void 0:y.config)==null?void 0:$.workspacePath)||"").trim().replace(/\/+$/,"").replace(/\\+$/,""),X=await l.current.sendMessage({message:C,session_id:k,enhance_prompt:O||void 0,copilot_conclusion_with_options_enhancement_enabled:re,workspace_path:Z||void 0,selected_skill_ids:A&&A.length>0?A:void 0,images:(W=b.images)==null?void 0:W.filter(K=>!!K.base64).map(K=>({base64:K.base64,name:K.name,size:K.size,type:K.type})),model:p,...g?{model_ref:g,provider:g.provider}:{}}),{session_id:se}=X;se!==k&&console.warn(`[useMessageStreaming] Backend returned unexpected session_id=${se} for sessionId=${k}`),await L.getState().loadChatHistory(k,{mode:"replace"}),e.setSessionProcessing(k,!0),await new Promise(K=>setTimeout(K,0));const ee=w?await l.current.execute(k,void 0,w,v(k),g??void 0):await l.current.execute(k,void 0,void 0,v(k),g??void 0);it("[Streaming]","[Agent] Execute status:",ee.status),await j(k,ee,w)}catch(O){throw O}},[p,g,v,y,f,e,j,n]),M=m.useCallback(async(C,k,b,w)=>{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 A=c;if(A===null&&(A=await d()),!A){s.error(n("chat.streaming.agentUnavailable"));return}if(!p){s.error(n("chat.streaming.modelConfigNotLoaded"));return}const I=e.sessionId,$=(k==null?void 0:k.map(O=>({id:O.id,base64:O.base64,name:O.name,size:O.size,type:O.type})))||[],W={role:"user",content:C,id:crypto.randomUUID(),createdAt:new Date().toISOString(),images:$};await e.addMessage(I,W);try{it("[Streaming]","[useChatStreaming] Using Agent Server"),await P(C,I,W,b,w)}catch(O){if(a.current&&qe.clear(I,a.current),a.current=null,i.current="",O instanceof Error&&O.name==="AbortError")s.info(n("chat.streaming.requestCancelled"));else{console.error("[useChatStreaming] Failed to send message:",O);const re=O instanceof Error?O.message:String(O??"");Rc(re)?s.error(Ac(re)):(s.error(n("chat.streaming.sendFailed")),u(!1))}e.setSessionProcessing(I,!1)}finally{o.current=null,a.current&&qe.clear(I,a.current),a.current=null,i.current=""}},[c,s,d,y,e,t,P,u,p,n]),R=m.useCallback(async(C,k="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 b=c;if(b===null&&(b=await d()),!b){s.error(n("chat.streaming.agentUnavailable"));return}const w=e.sessionId;a.current&&qe.clear(w,a.current),a.current=null,i.current="";try{const A=k==="error_retry"?"error_retry":"after_last_user",I=await l.current.truncateSessionMessages(w,{mode:A});(k==="regenerate"||(I.messages_removed??0)>0)&&await L.getState().loadChatHistory(w,{mode:"replace"}),e.setSessionProcessing(w,!0);const $=C?await l.current.execute(w,void 0,C,v(w),g??void 0):await l.current.execute(w,void 0,void 0,v(w),g??void 0);await j(w,$,C)}catch(A){console.error("[useMessageStreaming] Retry failed:",A);const I=A instanceof Error?A.message:String(A??"");Rc(I)?s.error(Ac(I)):s.error(n("chat.streaming.retryFailed")),e.setSessionProcessing(w,!1)}finally{o.current=null}},[p,g,c,s,v,d,y,e,j,t,n]);return{sendMessage:M,retryLastTurn:R,cancel:S,agentAvailable:c}}function E_(e,t){const s=m.useMemo(()=>e.baseMessages,[e.baseMessages]),n=m.useCallback(async()=>{var u;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(d=>d.role==="user");if(!l)return;const c="content"in l?l.content:l.displayText;typeof c=="string"&&await((u=t==null?void 0:t.onRetry)==null?void 0:u.call(t,c))},[e,t]);return{currentMessages:s,retryLastMessage:n}}const R_=()=>{const e=h_(),t=Hd(e),s=p_(e),n=Ry({sessionId:e.currentSessionId,addMessage:e.addMessage,setSessionProcessing:e.setSessionProcessing,updateSession:e.updateSession}),o=E_(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}},Ay="lotus_vdi_safe_mode",ji=()=>{try{return localStorage.getItem(Ay)==="true"}catch{return!1}},A_=e=>{try{localStorage.setItem(Ay,e.toString())}catch(t){console.error("[vdiSafeMode] Failed to persist setting:",t)}},{Text:Oa}=pe,{useToken:I_}=xe,$_=({httpProxy:e,httpsProxy:t,onHttpProxyChange:s,onHttpsProxyChange:n,onReload:o,onSave:a,isLoading:i})=>{const{t:l}=ie(),{token:c}=I_(),u=bs(_=>_.proxyAuthStatus),d=bs(_=>_.isLoadingProxyAuthStatus),h=bs(_=>_.loadProxyAuthStatus),p=bs(_=>_.applyProxyAuth),f=bs(_=>_.clearProxyAuth),[y,g]=m.useState({username:"",password:""}),[S,v]=m.useState(!1);m.useEffect(()=>{h()},[h]);const x=async()=>{const _=y.username.trim();if(_){v(!0);try{await p({username:_,password:y.password}),g({username:"",password:""})}catch(j){console.error("Failed to apply proxy auth:",j)}finally{v(!1)}}},T=async()=>{v(!0);try{await f()}catch(_){console.error("Failed to clear proxy auth:",_)}finally{v(!1)}};return r.jsx(te,{size:"small",title:r.jsx(Oa,{strong:!0,children:l("settings.networkCard.title")}),className:"lotus-settings-card",children:r.jsxs(U,{direction:"vertical",size:c.marginSM,style:{width:"100%"},children:[r.jsx(tt,{message:l("settings.networkCard.guideTip"),type:"info",showIcon:!0}),r.jsxs(U,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[r.jsx(Oa,{type:"secondary",children:l("settings.networkCard.httpProxy")}),r.jsx(be,{"data-testid":"proxy-url",style:{width:"100%"},value:e,onChange:_=>s(_.target.value),placeholder:l("settings.networkCard.proxyPlaceholder"),disabled:i})]}),r.jsxs(U,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[r.jsx(Oa,{type:"secondary",children:l("settings.networkCard.httpsProxy")}),r.jsx(be,{style:{width:"100%"},value:t,onChange:_=>n(_.target.value),placeholder:l("settings.networkCard.proxyPlaceholder"),disabled:i})]}),r.jsx(te,{size:"small",title:l("settings.networkCard.proxyAuthTitle"),className:"lotus-settings-card",style:{marginTop:c.marginSM},children:u!=null&&u.configured?r.jsxs(U,{direction:"vertical",style:{width:"100%"},children:[r.jsx(tt,{type:"success",message:l("settings.networkCard.proxyConfiguredForUser",{username:u.username??""}),showIcon:!0}),r.jsx(B,{onClick:T,loading:S||d,danger:!0,children:l("settings.networkCard.clearCredentials")})]}):r.jsxs(U,{direction:"vertical",size:c.marginXS,style:{width:"100%"},children:[r.jsx(be,{placeholder:l("settings.networkCard.username"),value:y.username,onChange:_=>g(j=>({...j,username:_.target.value}))}),r.jsx(be.Password,{placeholder:l("settings.networkCard.password"),value:y.password,onChange:_=>g(j=>({...j,password:_.target.value}))}),r.jsx(B,{type:"primary",onClick:x,loading:S||d,disabled:!y.username.trim(),children:l("settings.networkCard.apply")})]})}),r.jsx(Oa,{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(B,{onClick:()=>Promise.resolve(o()).finally(()=>h({force:!0})),disabled:i,children:l("settings.networkCard.reload")}),r.jsx(B,{"data-testid":"save-proxy-settings",type:"primary",onClick:()=>Promise.resolve(a()).finally(()=>h({force:!0})),disabled:i,children:l("settings.networkCard.save")})]})]})})},{Text:D_}=pe,{useToken:L_}=xe,O_=({msgApi:e})=>{const{t}=ie(),{token:s}=L_(),[n]=ne.useForm(),[o,a]=m.useState(!1),[i,l]=m.useState(!1),[c,u]=m.useState(!1),[d,h]=m.useState(!1),[p,f]=m.useState(null),y=c&&!d,g=m.useMemo(()=>c?d?t("settings.configTab.accessPassword.helperLocalBypass","当前是本地访问,可直接修改访问密码,无需输入当前密码。"):t("settings.configTab.accessPassword.helperRemote","当前是远程访问。修改访问密码前,必须先输入当前密码。"):t("settings.configTab.accessPassword.helperNotEnabled","未设置访问密码。设置后,远程访问需要先输入密码,本地 loopback 访问可直接绕过。"),[d,c,t]),S=m.useCallback(async()=>{a(!0),f(null);try{const x=await ot.getAccessStatus();u(x.password_enabled),h(x.local_bypass)}catch(x){const T=x instanceof Error?x.message:t("settings.configTab.accessPassword.loadStatusFailed","Failed to load access status");f(T)}finally{a(!1)}},[t]);m.useEffect(()=>{S()},[S]);const v=async()=>{var x;try{const T=await n.validateFields();l(!0),await ot.updateAccessPassword({current_password:((x=T.currentPassword)==null?void 0:x.trim())||void 0,new_password:T.newPassword.trim()}),e.success(c?t("settings.configTab.accessPassword.updated","访问密码已更新"):t("settings.configTab.accessPassword.enabled","访问密码已设置")),n.resetFields(),await S()}catch(T){if(T.errorFields)return;const _=T instanceof Error?T.message:t("settings.configTab.accessPassword.updateFailed","Failed to update access password");e.error(_)}finally{l(!1)}};return r.jsx(te,{size:"small",className:"lotus-settings-card",title:r.jsx(D_,{strong:!0,children:t("settings.configTab.accessPasswordTitle","访问密码")}),children:r.jsxs(U,{direction:"vertical",size:s.marginMD,style:{width:"100%"},children:[r.jsx(tt,{type:c?"info":"warning",showIcon:!0,message:c?t("settings.configTab.accessPassword.statusEnabled","访问密码已启用"):t("settings.configTab.accessPassword.statusDisabled","访问密码未启用"),description:g}),p?r.jsx(tt,{type:"error",showIcon:!0,message:p}):null,r.jsxs(ne,{form:n,layout:"vertical",disabled:o||i,children:[y?r.jsx(ne.Item,{label:t("settings.configTab.accessPassword.currentPasswordLabel","当前密码"),name:"currentPassword",rules:[{required:!0,message:t("settings.configTab.accessPassword.validation.currentPasswordRequired","请输入当前密码")}],children:r.jsx(be.Password,{autoComplete:"current-password"})}):null,r.jsx(ne.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(be.Password,{autoComplete:"new-password"})}),r.jsx(ne.Item,{label:t("settings.configTab.accessPassword.confirmPasswordLabel","确认密码"),name:"confirmPassword",dependencies:["newPassword"],rules:[{required:!0,message:t("settings.configTab.accessPassword.validation.confirmPasswordRequired","请再次输入新密码")},({getFieldValue:x})=>({validator(T,_){return!_||x("newPassword")===_?Promise.resolve():Promise.reject(new Error(t("settings.configTab.accessPassword.validation.passwordMismatch","两次输入的密码不一致")))}})],children:r.jsx(be.Password,{autoComplete:"new-password"})}),r.jsx(B,{type:"primary",loading:i,onClick:()=>void v(),children:c?t("settings.configTab.accessPassword.updateAction","更新访问密码"):t("settings.configTab.accessPassword.enableAction","启用访问密码")})]})]})})},{Text:Jt}=pe,{useToken:F_}=xe,vm="http://127.0.0.1:9562/v1",Xo=e=>[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort(),z_=e=>{var s;const t=(s=e.tools)==null?void 0:s.disabled;return Array.isArray(t)?Xo(t.filter(n=>typeof n=="string")):[]},N_=({msgApi:e,locale:t,onLocaleChange:s})=>{const{t:n}=ie(),{token:o}=F_(),[a,i]=m.useState({http_proxy:"",https_proxy:"",memory:{auto_dream_enabled:!1,background_model:""}}),[l,c]=m.useState(vm),[u,d]=m.useState([]),[h,p]=m.useState([]),[f,y]=m.useState([]),[g,S]=m.useState(!1),[v,x]=m.useState(!1),T=m.useCallback(async()=>{var $,W;S(!0);try{const[O,re]=await Promise.all([ot.getBambooConfig(),ot.getBambooTools()]);i({http_proxy:O.http_proxy||"",https_proxy:O.https_proxy||"",memory:{auto_dream_enabled:(($=O.memory)==null?void 0:$.auto_dream_enabled)??!1,background_model:((W=O.memory)==null?void 0:W.background_model)||""}});const q=z_(O);p(q),y(q),d(Xo(re.tools||[]))}catch(O){console.error("Failed to load config:",O),e.error(n("settings.configTab.loadConfigFailed"))}finally{S(!1)}},[e,n]);m.useEffect(()=>{T()},[T]);const _=$=>{i(W=>({...W,http_proxy:$}))},j=$=>{i(W=>({...W,https_proxy:$}))},P=$=>{i(W=>({...W,memory:{...W.memory,auto_dream_enabled:$}}))},M=$=>{i(W=>({...W,memory:{...W.memory,background_model:$}}))},R=async()=>{var $,W;S(!0);try{const O=await ot.validateBambooConfigPatch(a);if(!O.valid){const q=((W=($=O.errors)==null?void 0:$.proxy)==null?void 0:W[0])??Object.values(O.errors||{}).flat().filter(Boolean)[0];e.error((q==null?void 0:q.message)||n("settings.configTab.invalidConfig"));return}await ot.setBambooConfig(a),e.success(n("settings.configTab.saveConfigSuccess"))}catch(O){console.error("Failed to save config:",O);const re=O instanceof Error&&O.message.trim()?O.message:n("settings.configTab.saveConfigFailed");e.error(re)}finally{S(!1)}},E=async()=>{e.success(n("settings.configTab.backendSaved"))},C=()=>{c(vm),e.success(n("settings.configTab.backendResetDefault"))},k=($,W)=>{p(O=>{const re=new Set(O);return W?re.delete($):re.add($),Xo([...re])})},b=async()=>{x(!0);try{const $=await ot.getBambooTools();d(Xo($.tools||[])),e.success(n("settings.configTab.toolsReloadSuccess"))}catch($){console.error("Failed to reload tools:",$),e.error(n("settings.configTab.toolsLoadFailed"))}finally{x(!1)}},w=async()=>{x(!0);try{const $=Xo(h);await ot.setBambooConfig({tools:{disabled:$}}),p($),y($),e.success(n("settings.configTab.toolsSaveSuccess"))}catch($){console.error("Failed to save tool settings:",$),e.error(n("settings.configTab.toolsSaveFailed"))}finally{x(!1)}},A=JSON.stringify(h)!==JSON.stringify(f),I=new Set(h);return r.jsx(Ss,{spinning:g,tip:n("settings.common.loading"),children:r.jsx(ui,{items:[{key:"general",label:n("settings.configTab.tabs.general"),children:r.jsxs(U,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[r.jsx(tt,{message:n("settings.configTab.providerMovedTitle"),description:n("settings.configTab.providerMovedDescription"),type:"info",showIcon:!0,closable:!0}),r.jsx($_,{httpProxy:a.http_proxy,httpsProxy:a.https_proxy,onHttpProxyChange:_,onHttpsProxyChange:j,onReload:T,onSave:R,isLoading:g}),r.jsx(te,{size:"small",className:"lotus-settings-card",title:r.jsx(Jt,{strong:!0,children:n("settings.configTab.language")}),children:r.jsx(Le,{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:$=>s($)})}),r.jsx(te,{size:"small",className:"lotus-settings-card",title:r.jsx(Jt,{strong:!0,children:n("settings.configTab.memoryTitle")}),children:r.jsxs(U,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[r.jsx(Jt,{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(Jt,{strong:!0,children:n("settings.configTab.autoDreamEnabled")}),r.jsx("div",{children:r.jsx(Jt,{type:"secondary",style:{fontSize:o.fontSizeSM},children:n("settings.configTab.autoDreamEnabledHint")})})]}),r.jsx(ft,{"data-testid":"auto-dream-toggle",checked:a.memory.auto_dream_enabled,onChange:P})]}),r.jsxs(U,{direction:"vertical",size:o.marginXXS,style:{width:"100%"},children:[r.jsx(Jt,{strong:!0,children:n("settings.configTab.backgroundModel")}),r.jsx(be,{"data-testid":"auto-dream-background-model-input",value:a.memory.background_model,onChange:$=>M($.target.value),placeholder:n("settings.configTab.backgroundModelPlaceholder")}),r.jsx(Jt,{type:"secondary",style:{fontSize:o.fontSizeSM},children:n("settings.configTab.backgroundModelHint")})]}),r.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:r.jsx(B,{"data-testid":"save-memory-settings",type:"primary",onClick:R,loading:g,children:n("settings.configTab.save")})})]})}),r.jsx(te,{size:"small",title:r.jsx(Jt,{strong:!0,children:n("settings.configTab.backendApiBaseUrlTitle")}),children:r.jsxs(U,{direction:"vertical",size:o.marginSM,style:{width:"100%"},children:[r.jsx(U,{direction:"vertical",size:o.marginXXS,style:{width:"100%"},children:r.jsx(be,{style:{width:"100%"},value:l,onChange:$=>c($.target.value),placeholder:n("settings.configTab.backendApiPlaceholder")})}),r.jsx(Jt,{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(B,{"data-testid":"reset-to-defaults",onClick:C,children:n("settings.configTab.resetToDefault")}),r.jsx(B,{"data-testid":"save-api-settings",type:"primary",onClick:E,children:n("settings.configTab.save")})]})]})}),r.jsx(O_,{msgApi:e})]})},{key:"tools",label:n("settings.configTab.tabs.tools"),children:r.jsx(te,{size:"small",title:r.jsx(Jt,{strong:!0,children:n("settings.configTab.toolsTitle")}),children:r.jsxs(U,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[r.jsx(Jt,{type:"secondary",children:n("settings.configTab.toolsDescription")}),u.length===0?r.jsx(tt,{type:"info",showIcon:!0,message:n("settings.configTab.toolsEmpty")}):r.jsx(lt,{bordered:!0,dataSource:u,renderItem:$=>r.jsx(lt.Item,{actions:[r.jsx(ft,{checked:!I.has($),onChange:W=>k($,W)},`${$}-switch`)],children:r.jsx(Jt,{code:!0,children:$})})}),r.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:o.marginSM},children:[r.jsx(B,{onClick:b,loading:v,children:n("settings.configTab.reloadTools")}),r.jsx(B,{type:"primary",onClick:w,loading:v,disabled:!A,children:n("settings.configTab.save")})]})]})})}]})})},wm={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},Xd=yn()(bS(e=>({settings:wm,updateSettings:t=>e(s=>({settings:{...s.settings,...t}})),resetSettings:()=>e({settings:wm})}),{name:"mermaid-settings"})),Xi=()=>Xd(t=>t.settings),B_=()=>Xd(e=>e.updateSettings),W_=()=>Xd(e=>e.resetSettings),{Title:U_,Text:Sl}=pe,{useToken:q_}=xe,H_=()=>{const{t:e}=ie(),{token:t}=q_(),s=Xi(),n=B_(),o=W_(),[a]=ne.useForm();xt.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(U_,{level:3,style:{marginBottom:"8px"},children:e("settings.mermaidTab.title")}),r.jsx(Sl,{type:"secondary",style:{display:"block",marginBottom:"24px"},children:e("settings.mermaidTab.description")}),r.jsxs(ne,{form:a,layout:"vertical",initialValues:s,onValuesChange:i,children:[r.jsxs(te,{title:e("settings.mermaidTab.themeCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:[r.jsx(ns,{gutter:16,children:r.jsx(Be,{span:24,children:r.jsx(ne.Item,{name:"theme",label:r.jsxs(U,{children:[e("settings.mermaidTab.themeLabel"),r.jsx(Re,{title:e("settings.mermaidTab.themeTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsxs(Le,{children:[r.jsx(Le.Option,{value:"default",children:e("settings.mermaidTab.themeOptions.default")}),r.jsx(Le.Option,{value:"neutral",children:e("settings.mermaidTab.themeOptions.neutral")}),r.jsx(Le.Option,{value:"dark",children:e("settings.mermaidTab.themeOptions.dark")}),r.jsx(Le.Option,{value:"forest",children:e("settings.mermaidTab.themeOptions.forest")}),r.jsx(Le.Option,{value:"base",children:e("settings.mermaidTab.themeOptions.base")})]})})})}),r.jsxs(Sl,{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(te,{title:e("settings.mermaidTab.globalCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:[r.jsxs(ns,{gutter:16,children:[r.jsx(Be,{span:12,children:r.jsx(ne.Item,{name:"fontSize",label:r.jsxs(U,{children:[e("settings.mermaidTab.fontSizeLabel"),r.jsx(Re,{title:e("settings.mermaidTab.fontSizeTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:10,max:32,step:1,style:{width:"100%"},addonAfter:"px"})})}),r.jsx(Be,{span:12,children:r.jsx(ne.Item,{name:"defaultScale",label:r.jsxs(U,{children:[e("settings.mermaidTab.defaultZoomLabel"),r.jsx(Re,{title:e("settings.mermaidTab.defaultZoomTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:.1,max:3,step:.1,style:{width:"100%"}})})})]}),r.jsx(ne.Item,{name:"useMaxWidth",label:r.jsxs(U,{children:[e("settings.mermaidTab.responsiveWidthLabel"),r.jsx(Re,{title:e("settings.mermaidTab.responsiveWidthTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),valuePropName:"checked",children:r.jsx(ft,{})})]}),r.jsx(te,{title:e("settings.mermaidTab.flowchartCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsxs(ns,{gutter:16,children:[r.jsx(Be,{span:8,children:r.jsx(ne.Item,{name:"flowchartNodeSpacing",label:r.jsxs(U,{children:[e("settings.mermaidTab.flowchartNodeSpacingLabel"),r.jsx(Re,{title:e("settings.mermaidTab.flowchartNodeSpacingTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:20,max:200,step:10,style:{width:"100%"}})})}),r.jsx(Be,{span:8,children:r.jsx(ne.Item,{name:"flowchartRankSpacing",label:r.jsxs(U,{children:[e("settings.mermaidTab.flowchartRankSpacingLabel"),r.jsx(Re,{title:e("settings.mermaidTab.flowchartRankSpacingTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:20,max:200,step:10,style:{width:"100%"}})})}),r.jsx(Be,{span:8,children:r.jsx(ne.Item,{name:"flowchartCurve",label:r.jsxs(U,{children:[e("settings.mermaidTab.flowchartCurveTypeLabel"),r.jsx(Re,{title:e("settings.mermaidTab.flowchartCurveTypeTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsxs(Le,{children:[r.jsx(Le.Option,{value:"basis",children:e("settings.mermaidTab.flowchartCurveOptions.basis")}),r.jsx(Le.Option,{value:"linear",children:e("settings.mermaidTab.flowchartCurveOptions.linear")}),r.jsx(Le.Option,{value:"cardinal",children:e("settings.mermaidTab.flowchartCurveOptions.cardinal")})]})})})]})}),r.jsx(te,{title:e("settings.mermaidTab.sequenceCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsxs(ns,{gutter:16,children:[r.jsx(Be,{span:6,children:r.jsx(ne.Item,{name:"sequenceActorMargin",label:r.jsxs(U,{children:[e("settings.mermaidTab.sequenceActorMarginLabel"),r.jsx(Re,{title:e("settings.mermaidTab.sequenceActorMarginTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:20,max:200,step:10,style:{width:"100%"}})})}),r.jsx(Be,{span:6,children:r.jsx(ne.Item,{name:"sequenceMessageMargin",label:r.jsxs(U,{children:[e("settings.mermaidTab.sequenceMessageMarginLabel"),r.jsx(Re,{title:e("settings.mermaidTab.sequenceMessageMarginTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:10,max:100,step:5,style:{width:"100%"}})})}),r.jsx(Be,{span:6,children:r.jsx(ne.Item,{name:"sequenceWidth",label:r.jsxs(U,{children:[e("settings.mermaidTab.sequenceActorWidthLabel"),r.jsx(Re,{title:e("settings.mermaidTab.sequenceActorWidthTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:100,max:300,step:10,style:{width:"100%"}})})}),r.jsx(Be,{span:6,children:r.jsx(ne.Item,{name:"sequenceHeight",label:r.jsxs(U,{children:[e("settings.mermaidTab.sequenceActorHeightLabel"),r.jsx(Re,{title:e("settings.mermaidTab.sequenceActorHeightTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:40,max:150,step:5,style:{width:"100%"}})})})]})}),r.jsx(te,{title:e("settings.mermaidTab.ganttCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsxs(ns,{gutter:16,children:[r.jsx(Be,{span:12,children:r.jsx(ne.Item,{name:"ganttBarHeight",label:r.jsxs(U,{children:[e("settings.mermaidTab.ganttBarHeightLabel"),r.jsx(Re,{title:e("settings.mermaidTab.ganttBarHeightTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:10,max:50,step:5,style:{width:"100%"},addonAfter:"px"})})}),r.jsx(Be,{span:12,children:r.jsx(ne.Item,{name:"ganttTopPadding",label:r.jsxs(U,{children:[e("settings.mermaidTab.ganttTopPaddingLabel"),r.jsx(Re,{title:e("settings.mermaidTab.ganttTopPaddingTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:20,max:100,step:10,style:{width:"100%"}})})})]})}),r.jsx(U,{children:r.jsx(B,{icon:r.jsx(fx,{}),onClick:l,children:e("settings.mermaidTab.resetToDefaults")})}),r.jsx($t,{}),r.jsx(te,{title:e("settings.mermaidTab.previewTitle"),styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsx(Sl,{type:"secondary",children:e("settings.mermaidTab.previewDescription")})})]})]})},Y_=m.lazy(()=>Dt(()=>import("./index-D839lRZb.js"),__vite__mapDeps([0,1,2,3,4,5,6,7]),import.meta.url)),{Text:_n}=pe,{useToken:X_}=xe,V_=({promptEnhancement:e,onPromptEnhancementChange:t,mermaidEnhancementEnabled:s,taskEnhancementEnabled:n,showCopilotConclusionWithOptionsEnhancement:o,copilotConclusionWithOptionsEnhancementEnabled:a,onMermaidToggle:i,onTaskToggle:l,onCopilotConclusionWithOptionsToggle:c,onSaveEnhancement:u})=>{const{t:d}=ie(),{token:h}=X_(),p=h.marginLG;return r.jsxs(V,{vertical:!0,gap:p,children:[r.jsx(te,{size:"small",className:"lotus-settings-card",children:r.jsx(m.Suspense,{fallback:r.jsx(Ss,{size:"small"}),children:r.jsx(Y_,{})})}),r.jsx(te,{size:"small",className:"lotus-settings-card",children:r.jsxs(U,{direction:"vertical",size:h.marginXS,style:{width:"100%"},children:[r.jsx(_n,{strong:!0,children:d("settings.promptsTab.title")}),r.jsxs(V,{align:"center",gap:h.marginSM,children:[r.jsx(_n,{strong:!0,children:d("settings.promptsTab.mermaidEnhancement")}),r.jsx(ft,{checked:s,onChange:i})]}),r.jsxs(V,{align:"center",gap:h.marginSM,children:[r.jsx(_n,{strong:!0,children:d("settings.promptsTab.taskListRules")}),r.jsx(ft,{checked:n,onChange:l})]}),o&&r.jsxs(U,{direction:"vertical",size:h.marginXXS,style:{width:"100%"},children:[r.jsxs(V,{align:"center",gap:h.marginSM,children:[r.jsx(_n,{strong:!0,children:d("settings.promptsTab.copilotConclusionWithOptionsBeforeFinish")}),r.jsx(ft,{checked:a,onChange:c})]}),r.jsx(_n,{type:"secondary",style:{fontSize:h.fontSizeSM},children:d("settings.promptsTab.copilotConclusionWithOptionsBeforeFinishDescription",{defaultValue:T_()})})]}),r.jsx(be.TextArea,{rows:6,placeholder:d("settings.promptsTab.enhancementPlaceholder"),value:e,onChange:f=>t(f.target.value)}),r.jsx(V,{justify:"flex-end",children:r.jsx(B,{type:"primary",onClick:u,children:d("settings.promptsTab.saveEnhancement")})}),r.jsx(_n,{type:"secondary",style:{fontSize:h.fontSizeSM},children:d("settings.promptsTab.description")})]})}),s&&r.jsx(ws,{size:"small",items:[{key:"mermaid",label:r.jsx(_n,{strong:!0,children:d("settings.mermaidTab.title")}),children:r.jsx(H_,{})}]})]})},Vd="bodhi_onboarding_complete",K_=()=>localStorage.getItem(Vd)==="true",G_=()=>localStorage.setItem(Vd,"true"),J_=()=>localStorage.removeItem(Vd),Q_=["new-session","task-templates","model-picker","sidebar","open-settings"],Z_=()=>{const e={};for(const t of Q_)e[t]=document.querySelector(`[data-tour-id="${t}"]`);return e},e0=({disabled:e=!1})=>{const{t}=ie(),[s,n]=m.useState(!1),[o,a]=m.useState(null);m.useEffect(()=>{if(e||K_())return;const c=setTimeout(()=>{const u=Z_();a(u),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=()=>{G_(),n(!1)};return r.jsx(gx,{open:s,onClose:l,steps:i})},{Text:Ps}=pe,{useToken:t0}=xe,s0=({autoGenerateTitles:e,isUpdatingAutoTitlePreference:t,onAutoTitleToggle:s,themeMode:n,onThemeModeChange:o,vdiSafeMode:a,onVdiSafeModeToggle:i,onClearLocalStorage:l,onResetApp:c,isResetting:u,darkModeKey:d})=>{const{t:h}=ie(),{token:p}=t0();return r.jsx(te,{size:"small",className:"lotus-settings-card",children:r.jsxs(U,{direction:"vertical",size:p.marginSM,style:{width:"100%"},children:[r.jsxs(V,{align:"center",gap:p.marginSM,children:[r.jsx(Ps,{strong:!0,children:h("settings.appTab.autoGenerateTitle")}),r.jsx(ft,{checked:e,loading:t,onChange:s})]}),r.jsx(Ps,{type:"secondary",style:{fontSize:p.fontSizeSM},children:h("settings.appTab.autoGenerateTitleDesc")}),r.jsxs(V,{align:"center",justify:"space-between",gap:p.marginSM,children:[r.jsx(Ps,{strong:!0,children:h("settings.appTab.runningVersion","Running version")}),r.jsxs(Ps,{code:!0,"data-testid":"settings-app-version",children:["v",vd]})]}),r.jsx(Ps,{type:"secondary",style:{fontSize:p.fontSizeSM},children:h("settings.appTab.runningVersionDesc","This is the currently running Lotus frontend version.")}),r.jsxs(V,{align:"center",gap:p.marginSM,children:[r.jsx(Ps,{strong:!0,children:h("settings.appTab.darkMode")}),r.jsx(ft,{"data-testid":"dark-mode-toggle",checked:n==="dark",onChange:f=>{const y=f?"dark":"light";o(y),localStorage.setItem(d,y)}})]}),r.jsxs(V,{align:"center",gap:p.marginSM,children:[r.jsx(Ps,{strong:!0,children:h("settings.appTab.vdiSafeMode","Graphics compatibility mode")}),r.jsx(ft,{"data-testid":"vdi-safe-mode-toggle",checked:a,onChange:i})]}),r.jsx(Ps,{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(B,{block:!0,icon:r.jsx(rd,{}),onClick:()=>{J_(),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(B,{danger:!0,block:!0,icon:r.jsx(gn,{}),children:h("settings.appTab.clearLocalStorageButton")})}),r.jsx($t,{style:{margin:`${p.marginSM}px 0`}}),r.jsxs(V,{align:"center",gap:p.marginSM,children:[r.jsx(ua,{style:{color:p.colorError}}),r.jsx(Ps,{strong:!0,style:{color:p.colorError},children:h("settings.appTab.dangerZone")})]}),r.jsx(Ps,{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(B,{"data-testid":"reset-to-defaults",danger:!0,block:!0,type:"primary",icon:r.jsx(Sf,{}),loading:u,children:h("settings.appTab.resetButton")})})]})})},{Text:Tn}=pe,{useToken:n0}=xe,_m=[{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,}"}],r0=(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:is.t("settings.keywordMaskingTab.invalidRegexPattern")}}},o0=()=>{const{t:e}=ie(),{message:t}=ut.useApp(),{token:s}=n0(),[n,o]=m.useState([]),[a,i]=m.useState(!1),[l,c]=m.useState(null),[u,d]=m.useState(""),[h,p]=m.useState("exact"),[f,y]=m.useState(!0),[g,S]=m.useState(),[v,x]=m.useState("My token is sk-123"),T=m.useCallback(async()=>{try{i(!0);const w=await vs.getInstance().getKeywordMaskingConfig();o(w.entries)}catch(b){t.error(e("settings.keywordMaskingTab.loadFailed")),console.error(b)}finally{i(!1)}},[e]);m.useEffect(()=>{T()},[T]);const _=async b=>{try{const w=vs.getInstance(),A=await w.validateKeywordEntries(b);if(!A.valid&&A.errors){const $=A.errors.map(W=>`Entry ${W.index+1}: ${W.message}`).join("; ");return t.error(`${e("settings.keywordMaskingTab.validationFailedPrefix")}: ${$}`),!1}const I=await w.updateKeywordMaskingConfig(b);return o(I.entries),t.success(e("settings.keywordMaskingTab.saveSuccess")),!0}catch(w){return t.error(w instanceof Error?w.message:e("settings.keywordMaskingTab.saveFailed")),!1}},j=async()=>{const b={pattern:"",match_type:"exact",enabled:!0},w=[...n,b];o(w),c(w.length-1),d(""),p("exact"),y(!0),S(void 0)},P=b=>{const w=n[b];c(b),d(w.pattern),p(w.match_type),y(w.enabled),S(void 0)},M=async()=>{if(l===null)return;if(!u.trim()){t.error(e("settings.keywordMaskingTab.patternRequired"));return}const b=[...n];b[l]={pattern:u.trim(),match_type:h,enabled:f},await _(b)&&c(null)},R=()=>{var b;l!==null&&!((b=n[l])!=null&&b.pattern)&&o(n.filter((w,A)=>A!==l)),c(null)},E=async b=>{const w=n.filter((A,I)=>I!==b);await _(w)},C=async(b,w)=>{const A=[...n];A[b]={...A[b],enabled:w},await _(A)},k=r0(v,u,h);return r.jsx(te,{className:"lotus-settings-card",title:e("settings.keywordMaskingTab.title"),extra:r.jsx(B,{"data-testid":"add-keyword",type:"primary",icon:r.jsx(Ks,{}),onClick:j,loading:a,children:e("settings.keywordMaskingTab.addKeyword")}),children:r.jsxs(U,{direction:"vertical",style:{width:"100%"},size:"large",children:[r.jsx(Tn,{type:"secondary",children:e("settings.keywordMaskingTab.description")}),r.jsx(lt,{loading:a,dataSource:n,locale:{emptyText:e("settings.keywordMaskingTab.empty")},renderItem:(b,w)=>r.jsx(lt.Item,{style:{backgroundColor:s.colorFillAlter,marginBottom:8,borderRadius:s.borderRadius,padding:12},actions:l===w?[r.jsx(B,{"data-testid":"save-keyword",type:"primary",icon:r.jsx(Di,{}),onClick:M,"aria-label":e("settings.keywordMaskingTab.save")},"save"),r.jsx(B,{onClick:R,children:e("settings.keywordMaskingTab.cancel")},"cancel")]:[r.jsx(B,{icon:r.jsx(ca,{}),onClick:()=>P(w),"aria-label":e("settings.keywordMaskingTab.edit")},"edit"),r.jsx(B,{"data-testid":`delete-keyword-${w}`,danger:!0,icon:r.jsx(gn,{}),onClick:()=>E(w),"aria-label":e("settings.keywordMaskingTab.delete")},"delete")],children:r.jsx(V,{vertical:!0,style:{width:"100%"},gap:8,children:l===w?r.jsxs(r.Fragment,{children:[r.jsx(be,{"data-testid":"keyword-pattern-input",placeholder:e("settings.keywordMaskingTab.patternPlaceholder"),value:u,onChange:A=>d(A.target.value),autoFocus:!0}),r.jsxs(V,{gap:8,align:"center",wrap:"wrap",children:[r.jsx(Le,{"data-testid":"keyword-examples-select","aria-label":e("settings.keywordMaskingTab.examples"),placeholder:e("settings.keywordMaskingTab.examples"),value:g,onChange:A=>{S(A);const I=_m.find($=>$.value===A);I&&(d(I.pattern),p(I.match_type))},options:_m.map(A=>({value:A.value,label:e(A.labelKey)})),style:{minWidth:220}}),r.jsx(Le,{value:h,onChange:p,options:[{value:"exact",label:e("settings.keywordMaskingTab.exactMatch")},{value:"regex",label:e("settings.keywordMaskingTab.regexPattern")}],style:{width:150}}),r.jsx(ft,{checked:f,onChange:y})]}),r.jsxs(V,{vertical:!0,gap:6,children:[r.jsx(Tn,{type:"secondary",children:e("settings.keywordMaskingTab.sampleText")}),r.jsx(be,{placeholder:e("settings.keywordMaskingTab.sampleTextPlaceholder"),value:v,onChange:A=>x(A.target.value)}),r.jsx(Tn,{type:"secondary",children:e("settings.keywordMaskingTab.maskedPreview")}),r.jsx(be,{readOnly:!0,value:k.masked,status:k.error?"error":void 0}),k.error&&r.jsx(Tn,{type:"danger",children:k.error})]})]}):r.jsxs(V,{justify:"space-between",align:"center",children:[r.jsxs(V,{vertical:!0,gap:4,children:[r.jsx(Tn,{strong:!0,children:b.pattern||e("settings.keywordMaskingTab.emptyPattern")}),r.jsxs(V,{gap:8,children:[r.jsx(Tn,{type:"secondary",style:{fontSize:12},children:b.match_type==="regex"?e("settings.keywordMaskingTab.regexPattern"):e("settings.keywordMaskingTab.exactMatch")}),!b.enabled&&r.jsx(Tn,{type:"warning",style:{fontSize:12},children:e("settings.keywordMaskingTab.disabled")})]})]}),r.jsx(ft,{checked:b.enabled,onChange:A=>C(w,A),size:"small"})]})})})})]})})},{Text:nr,Paragraph:a0}=pe,i0=/^[A-Za-z_][A-Za-z0-9_]*$/,l0=()=>{const{t:e}=ie(),{message:t}=ut.useApp(),[s,n]=m.useState([]),[o,a]=m.useState(!1),[i,l]=m.useState(!1),[c,u]=m.useState(null),[d]=ne.useForm(),h=m.useCallback(async()=>{a(!0);try{const x=await zt.getEnvVars();n(x.entries)}catch{t.error(e("settings.envVars.fetchError","Failed to load environment variables"))}finally{a(!1)}},[e]);m.useEffect(()=>{h()},[h]);const p=async x=>{var _;const T={name:x.name.trim(),value:x.value,secret:x.secret??!1,description:((_=x.description)==null?void 0:_.trim())||void 0};try{const j=await zt.upsertEnvVar(T);n(j.entries),t.success(c?e("settings.envVars.updated","Variable updated"):e("settings.envVars.created","Variable created")),S()}catch(j){t.error((j instanceof Error?j.message:void 0)||e("settings.envVars.saveError","Failed to save variable"))}},f=async x=>{try{const T=await zt.deleteEnvVar(x);n(T.entries),t.success(e("settings.envVars.deleted","Variable deleted"))}catch(T){t.error((T instanceof Error?T.message:void 0)||e("settings.envVars.deleteError","Failed to delete variable"))}},y=()=>{u(null),d.resetFields(),d.setFieldsValue({secret:!1}),l(!0)},g=x=>{u(x.name),d.setFieldsValue({name:x.name,value:"",secret:x.secret,description:x.description??""}),l(!0)},S=()=>{l(!1),u(null),d.resetFields()},v=[{title:e("settings.envVars.name","Name"),dataIndex:"name",key:"name",render:x=>r.jsx(nr,{code:!0,children:x})},{title:e("settings.envVars.value","Value"),dataIndex:"value",key:"value",render:(x,T)=>T.secret?r.jsxs(nr,{type:"secondary",children:[r.jsx(uu,{style:{marginRight:4}}),T.has_value?"••••••••":e("settings.envVars.notSet","(not set)")]}):r.jsx(nr,{children:x||r.jsx(nr,{type:"secondary",children:e("settings.envVars.empty","(empty)")})})},{title:e("settings.envVars.type","Type"),key:"secret",width:100,render:(x,T)=>T.secret?r.jsx(ue,{color:"warning",icon:r.jsx(uu,{}),children:e("settings.envVars.secret","Secret")}):r.jsx(ue,{color:"processing",children:e("settings.envVars.plain","Plain")})},{title:e("settings.envVars.descriptionCol","Description"),dataIndex:"description",key:"description",ellipsis:!0,render:x=>x?r.jsx(nr,{type:"secondary",children:x}):r.jsx(nr,{type:"secondary",italic:!0,children:"—"})},{title:e("settings.envVars.actions","Actions"),key:"actions",width:120,render:(x,T)=>r.jsxs(U,{size:"small",children:[r.jsx(B,{type:"text",size:"small",icon:r.jsx(ca,{}),onClick:()=>g(T),"aria-label":e("settings.envVars.edit","Edit")}),r.jsx(mi,{title:e("settings.envVars.deleteConfirm","Delete this variable?"),onConfirm:()=>f(T.name),okText:e("settings.envVars.yes","Yes"),cancelText:e("settings.envVars.no","No"),children:r.jsx(B,{type:"text",size:"small",danger:!0,icon:r.jsx(gn,{}),"aria-label":e("settings.envVars.delete","Delete")})})]})}];return r.jsxs("div",{style:{maxWidth:900},children:[r.jsxs(te,{className:"lotus-settings-card",title:e("settings.envVars.title","Environment Variables"),extra:r.jsx(B,{type:"primary",icon:r.jsx(Ks,{}),onClick:y,children:e("settings.envVars.addButton","Add Variable")}),children:[r.jsx(a0,{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(Gs,{dataSource:s,columns:v,rowKey:"name",size:"small",pagination:!1,loading:o,locale:{emptyText:e("settings.envVars.noVars","No environment variables configured")}})]}),r.jsx(Bt,{title:c?e("settings.envVars.editTitle","Edit Variable"):e("settings.envVars.addTitle","Add Environment Variable"),open:i,onCancel:S,onOk:()=>d.submit(),okText:e("settings.envVars.save","Save"),cancelText:e("settings.envVars.cancel","Cancel"),destroyOnClose:!0,children:r.jsxs(ne,{form:d,layout:"vertical",onFinish:p,initialValues:{secret:!1},children:[r.jsx(ne.Item,{name:"name",label:e("settings.envVars.name","Name"),rules:[{required:!0,message:e("settings.envVars.nameRequired","Variable name is required")},{pattern:i0,message:e("settings.envVars.nameInvalid","Must start with a letter or underscore, followed by letters, digits, or underscores")}],children:r.jsx(be,{placeholder:"GITHUB_TOKEN",disabled:c!==null,autoFocus:c===null})}),r.jsx(ne.Item,{name:"value",label:e("settings.envVars.value","Value"),rules:[{required:c===null,message:e("settings.envVars.valueRequired","Value is required for new variables")}],extra:c?e("settings.envVars.valueEditHint","Leave empty to keep the existing value"):void 0,children:r.jsx(be.Password,{placeholder:c?e("settings.envVars.valuePlaceholderEdit","Enter new value or leave empty"):e("settings.envVars.valuePlaceholder","Enter value"),visibilityToggle:!0})}),r.jsx(ne.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(ft,{})}),r.jsx(ne.Item,{name:"description",label:e("settings.envVars.descriptionField","Description"),children:r.jsx(be,{placeholder:e("settings.envVars.descriptionPlaceholder","Optional description")})})]})})]})},On=class On{constructor(){}static getInstance(){return On.instance||(On.instance=new On),On.instance}async listWorkflows(){try{it("[WorkflowManager]","[WorkflowManagerService] Listing workflows");const t=await je.get("bamboo/workflows"),s=Array.isArray(t)?t:[];return it("[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{it("[WorkflowManager]","[WorkflowManagerService] Getting workflow: "+t);const s=await je.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 it("[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),ES(s)&&s.status===404?new Error("Workflow '"+t+"' not found"):s instanceof Error&&s.message.includes("404")?new Error("Workflow '"+t+"' not found"):s}}};Je(On,"instance");let Ic=On;const{Text:vl}=pe,{TextArea:c0}=be,{useToken:d0}=xe,u0=e=>!(!e||e.includes("/")||e.includes("\\")||e.includes("..")),m0=()=>{const{t:e}=ie(),{token:t}=d0(),[s,n]=fn.useMessage(),[o,a]=m.useState([]),[i,l]=m.useState(!1),[c,u]=m.useState(!1),[d,h]=m.useState(!1),[p,f]=m.useState(null),[y,g]=m.useState(""),[S,v]=m.useState(""),[x,T]=m.useState(!1),_=m.useMemo(()=>Ic.getInstance(),[]),j=m.useCallback(async()=>{l(!0);try{const C=await _.listWorkflows();return a(C),C}catch{return s.error(e("settings.workflowsTab.loadFailed")),[]}finally{l(!1)}},[s,e,_]);m.useEffect(()=>{j()},[j]);const P=m.useCallback(async C=>{f(C),g(C.name),T(!1),u(!0);try{const k=await _.getWorkflow(C.name);v(k.content??"")}catch{s.error(e("settings.workflowsTab.loadContentFailed")),v("")}finally{u(!1)}},[s,e,_]),M=()=>{f(null),g(""),v(""),T(!1)},R=m.useCallback(async()=>{if(!u0(y)){s.error(e("settings.workflowsTab.invalidName"));return}const C=o.some(k=>k.name===y);if(!p&&C){s.error(e("settings.workflowsTab.nameAlreadyExists"));return}h(!0);try{await vs.getInstance().saveWorkflow(y,S),s.success(e("settings.workflowsTab.saved")),T(!1);const w=(await j()).find(A=>A.name===y);w&&f(w)}catch(k){s.error(k instanceof Error?k.message:e("settings.workflowsTab.saveFailed"))}finally{h(!1)}},[S,y,j,s,p,e,o]),E=m.useCallback(async C=>{try{await vs.getInstance().deleteWorkflow(C.name),s.success(e("settings.workflowsTab.deleted")),(p==null?void 0:p.name)===C.name&&M(),await j()}catch(k){s.error(k instanceof Error?k.message:e("settings.workflowsTab.deleteFailed"))}},[j,s,p,e]);return r.jsxs("div",{style:{padding:"24px"},children:[n,r.jsxs(te,{title:e("settings.workflowsTab.title"),extra:r.jsxs(U,{children:[r.jsx(B,{icon:r.jsx(Zs,{}),onClick:j,loading:i,children:e("settings.workflowsTab.refresh")}),r.jsx(B,{"data-testid":"create-workflow",icon:r.jsx(Ks,{}),onClick:M,children:e("settings.workflowsTab.newWorkflow")}),r.jsx(B,{"data-testid":"save-workflow",type:"primary",icon:r.jsx(Di,{}),onClick:R,loading:d,disabled:!x,children:e("settings.workflowsTab.save")})]}),children:[r.jsx(vl,{type:"secondary",children:e("settings.workflowsTab.description")}),r.jsxs(V,{gap:t.marginLG,style:{marginTop:t.marginLG},children:[r.jsx("div",{style:{width:320,flexShrink:0},children:r.jsx(lt,{loading:i,dataSource:o,locale:{emptyText:e("settings.workflowsTab.empty")},renderItem:C=>r.jsx(lt.Item,{style:{cursor:"pointer",backgroundColor:(p==null?void 0:p.name)===C.name?t.colorFillSecondary:"transparent",borderRadius:t.borderRadius,padding:t.paddingSM},onClick:()=>P(C),actions:[r.jsx(B,{"data-testid":`delete-workflow-${C.name}`,type:"text",danger:!0,size:"small",icon:r.jsx(gn,{}),onClick:k=>{k.stopPropagation(),E(C)},"aria-label":e("settings.workflowsTab.delete")},"delete")],children:r.jsxs(U,{direction:"vertical",size:0,children:[r.jsxs(vl,{strong:!0,children:["/",C.name]}),r.jsx(vl,{type:"secondary",style:{fontSize:12},children:C.filename})]})})})}),r.jsx("div",{style:{flex:1},children:r.jsxs(U,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx(be,{"data-testid":"workflow-name",placeholder:e("settings.workflowsTab.namePlaceholder"),value:y,onChange:C=>{g(C.target.value),T(!0)},disabled:!!p,prefix:r.jsx(ca,{})}),r.jsx(c0,{"data-testid":"workflow-content",placeholder:e("settings.workflowsTab.contentPlaceholder"),value:S,onChange:C=>{v(C.target.value),T(!0)},autoSize:{minRows:12},disabled:c})]})})]})]})]})};var ye=(e=>(e.Connecting="connecting",e.Ready="ready",e.Degraded="degraded",e.Stopped="stopped",e.Error="error",e))(ye||{});const Sa=6e4,va=3e4,aa=2e4,Ci=1e4,Vi=e=>({id:e,enabled:!0,transport:{type:"stdio",command:"",args:[],env:{},startup_timeout_ms:aa},request_timeout_ms:Sa,healthcheck_interval_ms:va,allowed_tools:[],denied_tools:[]}),h0=()=>({status:"stopped",tool_count:0,restart_count:0}),p0=e=>{switch(typeof e=="string"?e.trim().toLowerCase():""){case ye.Connecting:return ye.Connecting;case ye.Ready:return ye.Ready;case ye.Degraded:return ye.Degraded;case ye.Error:return ye.Error;case ye.Stopped:default:return ye.Stopped}},Ys=(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},f0=(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:Ys(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:Ys(s.startup_timeout_ms,aa)}},g0=(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:Ys(n.request_timeout_ms,Sa),healthcheck_interval_ms:Ys(n.healthcheck_interval_ms,va),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:Ys(n.reconnect.initial_backoff_ms,1e3),max_backoff_ms:Ys(n.reconnect.max_backoff_ms,3e4),max_attempts:Ys(n.reconnect.max_attempts,0)}:void 0,transport:f0(n.transport,s.transport)}},y0=e=>{const t=h0(),n=e.runtime??{},o=n.status??e.status;return{status:p0(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:Ys(n.tool_count??e.tool_count,t.tool_count),restart_count:Ys(n.restart_count??e.restart_count,t.restart_count),last_ping_at:typeof n.last_ping_at=="string"?n.last_ping_at:void 0}},b0=e=>{const t=g0(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:y0(e)}},x0=(e,t)=>`mcp__${e}__${t}`,S0=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}},v0=(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"?S0(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?x0(i,l):""),u=typeof n.description=="string"?n.description:"",d=n,h="parameters"in d?d.parameters:"inputSchema"in d?d.inputSchema:"input_schema"in d?d.input_schema:void 0,p=c||l||`mcp_tool_${s}`;return{alias:p,server_id:i||"unknown",original_name:l||p,description:u,parameters:h}};class w0{async getServers(){const t=await we.get("mcp/servers");return Array.isArray(t.servers)?t.servers.map(b0):[]}async addServer(t){return we.post("mcp/servers",t)}async updateServer(t,s){const n={...s,id:t};return we.put(`mcp/servers/${t}`,n)}async deleteServer(t){return we.delete(`mcp/servers/${t}`)}async connectServer(t){return we.post(`mcp/servers/${t}/connect`)}async disconnectServer(t){return we.post(`mcp/servers/${t}/disconnect`)}async refreshTools(t){return we.post(`mcp/servers/${t}/refresh`)}async getTools(t){const s=t?`mcp/servers/${t}/tools`:"mcp/tools",n=await we.get(s);return(Array.isArray(n.tools)?n.tools:[]).map((a,i)=>v0(a,t,i)).filter(a=>!!a)}async importServers(t){return we.post("mcp/servers/import",t)}}const Iy=new w0,_0=5e3,Bs=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,Tm=(e,t)=>`${e}:${t}`,T0=(e={})=>{const{service:t=Iy,autoRefreshMs:s=_0,autoRefreshEnabled:n=!0}=e,[o,a]=m.useState([]),[i,l]=m.useState(null),[c,u]=m.useState({}),[d,h]=m.useState({}),[p,f]=m.useState({}),[y,g]=m.useState(!1),[S,v]=m.useState(!1),[x,T]=m.useState(!1),[_,j]=m.useState(null),P=m.useRef({}),M=m.useCallback(X=>{const se=new Set(X.map(K=>K.id)),ee=X.map(K=>{const Y=P.current[K.id]??K.config,G={...Y,id:K.id,name:Y.name??K.name};return P.current[K.id]=G,{...K,name:K.name||G.name||K.id,enabled:K.enabled??G.enabled,config:G}});return Object.keys(P.current).forEach(K=>{se.has(K)||delete P.current[K]}),ee},[]),R=m.useCallback(async({silent:X=!1}={})=>{X||g(!0);try{const se=await t.getServers(),ee=M(se);a(ee),l(K=>{var F;return K&&ee.some(Y=>Y.id===K)?K:((F=ee[0])==null?void 0:F.id)??null}),j(null)}catch(se){throw j(Bs(se,"Failed to load MCP servers")),se}finally{X||g(!1)}},[M,t]),E=m.useCallback(async(X,se=!1)=>{if(!X)return[];if(!se&&c[X])return c[X];h(ee=>({...ee,[X]:!0}));try{const ee=await t.getTools(X);return u(K=>({...K,[X]:ee})),j(null),ee}catch(ee){throw j(Bs(ee,"Failed to load MCP tools")),ee}finally{h(ee=>({...ee,[X]:!1}))}},[t,c]),C=m.useCallback((X,se,ee)=>{const K=Tm(X,se);f(F=>({...F,[K]:ee}))},[]),k=m.useCallback(async X=>{v(!0);try{await t.addServer(X),P.current[X.id]=X,await R()}catch(se){throw j(Bs(se,"Failed to add MCP server")),se}finally{v(!1)}},[R,t]),b=m.useCallback(async(X,se)=>{v(!0);try{const ee={...se,id:X};await t.updateServer(X,ee),P.current[X]=ee,await R()}catch(ee){throw j(Bs(ee,"Failed to update MCP server")),ee}finally{v(!1)}},[R,t]),w=m.useCallback(async X=>{C(X,"delete",!0);try{await t.deleteServer(X),u(se=>{const ee={...se};return delete ee[X],ee}),delete P.current[X],await R()}catch(se){throw j(Bs(se,"Failed to delete MCP server")),se}finally{C(X,"delete",!1)}},[R,t,C]),A=m.useCallback(async X=>{C(X,"connect",!0);try{await t.connectServer(X),await R({silent:!0})}catch(se){throw j(Bs(se,"Failed to connect MCP server")),se}finally{C(X,"connect",!1)}},[R,t,C]),I=m.useCallback(async X=>{C(X,"disconnect",!0);try{await t.disconnectServer(X),await R({silent:!0})}catch(se){throw j(Bs(se,"Failed to disconnect MCP server")),se}finally{C(X,"disconnect",!1)}},[R,t,C]),$=m.useCallback(async X=>{C(X,"refresh",!0);try{await t.refreshTools(X),await E(X,!0),await R({silent:!0})}catch(se){throw j(Bs(se,"Failed to refresh MCP tools")),se}finally{C(X,"refresh",!1)}},[E,R,t,C]),W=m.useCallback(async()=>{T(!0);try{const X=o.map(se=>se.id);await Promise.all(X.map(async se=>{try{await t.refreshTools(se)}catch{}})),await R(),i&&await E(i,!0)}catch(X){throw j(Bs(X,"Failed to refresh MCP status")),X}finally{T(!1)}},[E,R,i,o,t]),O=m.useCallback(X=>{l(X)},[]),re=m.useCallback((X,se)=>!!p[Tm(X,se)],[p]),q=m.useMemo(()=>i?c[i]??[]:[],[i,c]),Z=m.useMemo(()=>i?!!d[i]:!1,[i,d]);return m.useEffect(()=>{R().catch(()=>{})},[R]),m.useEffect(()=>{if(!n||s<=0)return;const X=window.setInterval(()=>{R({silent:!0}).catch(()=>{})},s);return()=>{window.clearInterval(X)}},[n,s,R]),m.useEffect(()=>{i&&E(i).catch(()=>{})},[E,i]),{servers:o,selectedServerId:i,selectedServerTools:q,isLoadingServers:y,isMutatingConfig:S,isRefreshingAll:x,isSelectedServerToolsLoading:Z,error:_,setSelectedServerId:O,refreshServers:R,addServer:k,updateServer:b,deleteServer:w,connectServer:A,disconnectServer:I,refreshServerTools:$,refreshAll:W,isServerActionLoading:re}},k0={[ye.Connecting]:"blue",[ye.Ready]:"green",[ye.Degraded]:"orange",[ye.Stopped]:"default",[ye.Error]:"red"},j0=e=>e===ye.Connecting||e===ye.Ready||e===ye.Degraded,C0=e=>{if(!e)return;const t=e.replace(/\s+/g," ").trim();if(t)return t.length>180?`${t.slice(0,180)}...`:t},M0=({servers:e,loading:t=!1,selectedServerId:s,onSelectServer:n,onEditServer:o,onDeleteServer:a,onConnectServer:i,onDisconnectServer:l,onRefreshTools:c,isServerActionLoading:u})=>{const{t:d}=ie(),{token:h}=xe.useToken(),p=m.useMemo(()=>({[ye.Connecting]:d("settings.mcpTab.statusHelp.connecting"),[ye.Ready]:d("settings.mcpTab.statusHelp.ready"),[ye.Degraded]:d("settings.mcpTab.statusHelp.degraded"),[ye.Stopped]:d("settings.mcpTab.statusHelp.stopped"),[ye.Error]:d("settings.mcpTab.statusHelp.error")}),[d]),f=m.useMemo(()=>[{key:"name",title:d("settings.mcpServerTable.columns.name"),render:(y,g)=>g.name||g.id},{key:"transport",title:d("settings.mcpServerTable.columns.transportType"),render:(y,g)=>g.config.transport.type==="sse"?d("settings.mcpServerTable.transportOptions.sse"):d("settings.mcpServerTable.transportOptions.stdio"),width:140},{key:"status",title:d("settings.mcpServerTable.columns.status"),render:(y,g)=>{var _,j;const S=((_=g.runtime)==null?void 0:_.status)??ye.Stopped,v=C0((j=g.runtime)==null?void 0:j.last_error),x=p[S],T={[ye.Connecting]:d("settings.mcpTab.status.connecting"),[ye.Ready]:d("settings.mcpTab.status.ready"),[ye.Degraded]:d("settings.mcpTab.status.degraded"),[ye.Stopped]:d("settings.mcpTab.status.stopped"),[ye.Error]:d("settings.mcpTab.status.error")};return r.jsx(Re,{title:v?`${x} ${d("settings.mcpTab.statusLastError",{error:v})}`:x,children:r.jsx(ue,{color:S===ye.Stopped?void 0:k0[S],style:{marginInlineEnd:0,cursor:"help",...S===ye.Stopped?{background:h.colorFillSecondary,borderColor:h.colorBorderSecondary,color:h.colorTextSecondary}:void 0},children:T[S]})})},width:120},{key:"toolCount",title:d("settings.mcpServerTable.columns.toolCount"),render:(y,g)=>{var S;return((S=g.runtime)==null?void 0:S.tool_count)??0},width:100},{key:"actions",title:d("settings.mcpServerTable.columns.actions"),width:360,render:(y,g)=>{var x;const S=((x=g.runtime)==null?void 0:x.status)??ye.Stopped,v=j0(S);return r.jsxs(U,{size:h.marginXS,children:[r.jsx(B,{size:"small",onClick:T=>{T.stopPropagation(),o==null||o(g)},children:d("settings.mcpServerTable.actions.edit")}),r.jsx(mi,{title:d("settings.mcpServerTable.deleteTitle"),description:d("settings.mcpServerTable.deleteDescription",{name:g.name||g.id}),onConfirm:()=>a==null?void 0:a(g),okText:d("settings.mcpServerTable.actions.delete"),okButtonProps:{danger:!0,loading:u==null?void 0:u(g.id,"delete")},children:r.jsx(B,{size:"small",danger:!0,loading:u==null?void 0:u(g.id,"delete"),onClick:T=>T.stopPropagation(),children:d("settings.mcpServerTable.actions.delete")})}),v?r.jsx(B,{size:"small",onClick:T=>{T.stopPropagation(),l==null||l(g)},loading:u==null?void 0:u(g.id,"disconnect"),children:d("settings.mcpServerTable.actions.disconnect")}):r.jsx(B,{size:"small",type:"primary",ghost:!0,onClick:T=>{T.stopPropagation(),i==null||i(g)},loading:u==null?void 0:u(g.id,"connect"),children:d("settings.mcpServerTable.actions.connect")}),r.jsx(B,{size:"small",onClick:T=>{T.stopPropagation(),c==null||c(g)},loading:u==null?void 0:u(g.id,"refresh"),children:d("settings.mcpServerTable.actions.refreshTools")})]})}}],[u,i,a,l,o,c,p,d,h.colorBorderSecondary,h.colorFillSecondary,h.colorTextSecondary,h.marginXS]);return r.jsx(Gs,{rowKey:"id",columns:f,dataSource:e,loading:t,pagination:!1,locale:{emptyText:d("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:km}=pe,{TextArea:P0}=be,jm=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||Sa,healthcheckIntervalMs:t.healthcheck_interval_ms||va,allowedTools:t.allowed_tools||[],deniedTools:t.denied_tools||[]}},E0=e=>e.reduce((t,s)=>{var o;const n=(o=s.key)==null?void 0:o.trim();return n&&(t[n]=s.value??""),t},{}),R0=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??""}}),Cm=(e,t,s)=>{var d,h,p;const n=t==="edit"&&(s==null?void 0:s.id)||e.id,o=(d=e.name)==null?void 0:d.trim(),a=typeof e.requestTimeoutMs=="number"?e.requestTimeoutMs:(s==null?void 0:s.request_timeout_ms)??Sa,i=typeof e.healthcheckIntervalMs=="number"?e.healthcheckIntervalMs:(s==null?void 0:s.healthcheck_interval_ms)??va,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)??[],u=e.transportType==="sse"?{type:"sse",url:((h=e.url)==null?void 0:h.trim())||"",headers:R0(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:E0(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:u,request_timeout_ms:a,healthcheck_interval_ms:i,allowed_tools:l,denied_tools:c,reconnect:s==null?void 0:s.reconnect}},Mm=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:Sa,l=typeof n.healthcheck_interval_ms=="number"?n.healthcheck_interval_ms:va,c=Array.isArray(n.allowed_tools)?n.allowed_tools.filter(h=>typeof h=="string"):[],u=Array.isArray(n.denied_tools)?n.denied_tools.filter(h=>typeof h=="string"):[],d=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 g=y,S=typeof g.name=="string"?g.name:"",v=typeof g.value=="string"?g.value:"";return S.trim()?{name:S,value:v}:null}).filter(y=>!!y):h&&typeof h=="object"?Object.entries(h).filter(([y])=>y.trim()).map(([y,g])=>({name:y,value:typeof g=="string"?g:""})):[],f=typeof n.connect_timeout_ms=="number"?n.connect_timeout_ms:Ci;return{valid:!0,config:{id:o,name:d,enabled:a,transport:{type:"sse",url:n.url,headers:p,connect_timeout_ms:f},request_timeout_ms:i,healthcheck_interval_ms:l,allowed_tools:c,denied_tools:u,reconnect:void 0}}}if(typeof n.command=="string"){const h=Array.isArray(n.args)?n.args.filter(g=>typeof g=="string"):[],p=n.env,f=p&&typeof p=="object"?Object.entries(p).reduce((g,[S,v])=>(typeof v=="string"&&(g[S]=v),g),{}):{},y=typeof n.startup_timeout_ms=="number"?n.startup_timeout_ms:aa;return{valid:!0,config:{id:o,name:d,enabled:a,transport:{type:"stdio",command:n.command,args:h,cwd:typeof n.cwd=="string"?n.cwd:void 0,env:f,startup_timeout_ms:y},request_timeout_ms:i,healthcheck_interval_ms:l,allowed_tools:c,denied_tools:u,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")})}}},A0=({open:e,mode:t,initialConfig:s,confirmLoading:n=!1,onCancel:o,onSubmit:a})=>{const{t:i}=ie(),[l]=ne.useForm(),[c,u]=m.useState("form"),[d,h]=m.useState(""),[p,f]=m.useState(null),y=m.useMemo(()=>jm(s),[s]),g=ne.useWatch("transportType",l)??"stdio";m.useEffect(()=>{e&&(l.setFieldsValue(y),h(Mm(s)),f(null),u("form"))},[l,y,s,e]);const S=()=>{l.resetFields(),h(""),f(null),o()},v=async()=>{if(c==="json"){const _=wl(d,i);if(!_.valid){f(_.error);return}f(null);try{await a(_.config),h("")}catch(j){console.error("MCP server JSON submission error:",j)}return}try{const _=await l.validateFields(),j=Cm(_,t,s);await a(j),l.resetFields()}catch(_){console.error("MCP server form submission error:",_)}},x=_=>{h(_),p&&wl(_,i).valid&&f(null)},T=_=>{if(_==="json")try{const j=l.getFieldsValue(),P=Cm(j,t,s);h(JSON.stringify(P,null,2))}catch{h(Mm(s))}else{const j=wl(d,i);j.valid&&l.setFieldsValue(jm(j.config))}u(_),f(null)};return r.jsxs(Bt,{title:i(t==="edit"?"settings.mcpServerForm.editTitle":"settings.mcpServerForm.addTitle"),open:e,onCancel:S,onOk:()=>{v()},okText:i("settings.mcpServerForm.save"),destroyOnClose:!0,forceRender:!0,confirmLoading:n,width:720,children:[r.jsx("div",{style:{marginBottom:16},children:r.jsxs(ls.Group,{value:c,onChange:_=>T(_.target.value),optionType:"button",buttonStyle:"solid",children:[r.jsxs(ls.Button,{value:"form",children:[r.jsx(yx,{})," ",i("settings.mcpServerForm.modeForm")]}),r.jsxs(ls.Button,{value:"json",children:[r.jsx(Li,{})," ",i("settings.mcpServerForm.modeJson")]})]})}),c==="json"&&p&&r.jsx(tt,{type:"error",message:i("settings.mcpServerForm.jsonError"),description:p,showIcon:!0,style:{marginBottom:16},closable:!0,onClose:()=>f(null)}),c==="json"?r.jsx(P0,{value:d,onChange:_=>x(_.target.value),rows:20,style:{fontFamily:"monospace",fontSize:13},placeholder:JSON.stringify(Vi("example-server"),null,2)}):r.jsxs(ne,{layout:"vertical",form:l,preserve:!0,initialValues:y,children:[r.jsx(ne.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(be,{placeholder:"filesystem",disabled:t==="edit",autoComplete:"off"})}),r.jsx(ne.Item,{name:"name",label:i("settings.mcpServerForm.displayName"),children:r.jsx(be,{placeholder:"Filesystem MCP",autoComplete:"off"})}),r.jsx(ne.Item,{name:"enabled",label:i("settings.mcpServerForm.enabled"),valuePropName:"checked",extra:i("settings.mcpServerForm.enabledHelp"),children:r.jsx(ft,{})}),r.jsx(ne.Item,{name:"transportType",label:i("settings.mcpServerForm.transportType"),rules:[{required:!0,message:i("settings.mcpServerForm.transportTypeRequired")}],children:r.jsx(Le,{options:[{label:i("settings.mcpServerForm.transportOptions.stdio"),value:"stdio"},{label:i("settings.mcpServerForm.transportOptions.sse"),value:"sse"}]})}),g==="stdio"?r.jsxs(r.Fragment,{children:[r.jsx(ne.Item,{name:"command",label:i("settings.mcpServerForm.command"),rules:[{required:!0,message:i("settings.mcpServerForm.commandRequired")}],children:r.jsx(be,{placeholder:"npx",autoComplete:"off"})}),r.jsx(ne.Item,{name:"args",label:i("settings.mcpServerForm.arguments"),children:r.jsx(Le,{mode:"tags",tokenSeparators:[","],placeholder:i("settings.mcpServerForm.argumentsPlaceholder"),open:!1})}),r.jsx(ne.List,{name:"envEntries",children:(_,{add:j,remove:P})=>r.jsxs(U,{direction:"vertical",style:{width:"100%"},children:[r.jsxs(U,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[r.jsx(km,{strong:!0,children:i("settings.mcpServerForm.envVars")}),r.jsx(B,{icon:r.jsx(Ks,{}),onClick:()=>j({key:"",value:""}),type:"dashed",children:i("settings.mcpServerForm.addEnv")})]}),_.map(M=>r.jsxs(U,{align:"baseline",style:{display:"flex"},children:[r.jsx(ne.Item,{...M,name:[M.name,"key"],rules:[{required:!0,message:i("settings.mcpServerForm.keyRequired")}],children:r.jsx(be,{placeholder:"MCP_ROOT",autoComplete:"off"})}),r.jsx(ne.Item,{...M,name:[M.name,"value"],children:r.jsx(be,{placeholder:"/Users/me/workspace",autoComplete:"off"})}),r.jsx(B,{danger:!0,type:"text",icon:r.jsx(nc,{}),onClick:()=>P(M.name),"aria-label":i("settings.mcpServerForm.removeEnv","Remove environment variable")})]},M.key))]})})]}):r.jsxs(r.Fragment,{children:[r.jsx(ne.Item,{name:"url",label:i("settings.mcpServerForm.sseUrl"),rules:[{required:!0,message:i("settings.mcpServerForm.sseUrlRequired")},{validator:async(_,j)=>{if(j)try{new URL(j)}catch{throw new Error(i("settings.mcpServerForm.validUrlRequired"))}}}],children:r.jsx(be,{placeholder:"http://localhost:4000/sse",autoComplete:"off"})}),r.jsx(ne.List,{name:"headerEntries",children:(_,{add:j,remove:P})=>r.jsxs(U,{direction:"vertical",style:{width:"100%"},children:[r.jsxs(U,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[r.jsx(km,{strong:!0,children:i("settings.mcpServerForm.headers")}),r.jsx(B,{icon:r.jsx(Ks,{}),onClick:()=>j({name:"",value:""}),type:"dashed",children:i("settings.mcpServerForm.addHeader")})]}),_.map(M=>r.jsxs(U,{align:"baseline",style:{display:"flex"},children:[r.jsx(ne.Item,{...M,name:[M.name,"name"],rules:[{required:!0,message:i("settings.mcpServerForm.headerNameRequired")}],children:r.jsx(be,{placeholder:"Authorization",autoComplete:"off"})}),r.jsx(ne.Item,{...M,name:[M.name,"value"],children:r.jsx(be,{placeholder:"Bearer token",autoComplete:"off"})}),r.jsx(B,{danger:!0,type:"text",icon:r.jsx(nc,{}),onClick:()=>P(M.name),"aria-label":i("settings.mcpServerForm.removeHeader","Remove header")})]},M.key))]})})]})]})]})},I0={maxLines:8,maxCharacters:500},un=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),on=e=>typeof e=="string"?e:void 0,In=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Pm=e=>typeof e=="boolean"?e:void 0,Kd=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const s=JSON.parse(t);return un(s)?s:null}catch{return null}},$y=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,`
114
114
  `).replace(/\\t/g," ").replace(/\\r/g,"\r"):e,Ds=e=>Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>$y(t).trim()).filter(Boolean):[],_t=e=>{if(typeof e!="string")return;const t=$y(e).trim();return t.length>0?t:void 0},$0=e=>{if(!un(e))return;const t=_t(e.graph);if(t)return{title:_t(e.title),graph:t}},D0=e=>{if(!un(e))return;const t=_t(e.summary)??_t(e.conclusion);if(t)return{title:_t(e.title)||"Conclusion",summary:t,key_points:Ds(e.key_points),next_steps:Ds(e.next_steps),confidence:_t(e.confidence),mermaid:$0(e.mermaid)}},L0=e=>{const t=Kd(e);if(!t)return null;const s=_t(t.conclusion);return!s||t.type!=null&&t.type!=="conclusion"?null:{type:"conclusion",title:_t(t.title)||"Conclusion",conclusion:s,key_points:Ds(t.key_points),next_steps:Ds(t.next_steps),confidence:_t(t.confidence)}},O0=e=>{const t=Kd(e);if(!t)return null;const s=_t(t.question);if(!s)return null;const n=_t(t.status);return n&&n!=="awaiting_user_input"&&n!=="awaiting_permission_approval"?null:{question:s,options:Ds(t.options),allow_custom:typeof t.allow_custom=="boolean"?t.allow_custom:!0,conclusion:D0(t.conclusion)}},F0=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(`
115
115
  `)),e.next_steps.length>0&&t.push(["**Next steps**",...e.next_steps.map((n,o)=>`${o+1}. ${n}`)].join(`
116
116
  `)),(s=e.mermaid)!=null&&s.graph){const n=e.mermaid.title?`**${e.mermaid.title}**
@@ -172,7 +172,7 @@ ${n}
172
172
 
173
173
  `)}}if(!T&&!v&&(!g||g.length===0))return;const j=[x,T,v].filter(Boolean).join(`
174
174
 
175
- `);if(l(j),u(""),c(),o.size>0){const P=Array.from(j.matchAll(/@([^\\s]+)/g));if(P.length>0){const M=[];for(const R of P){const E=R[1],C=o.get(E);C&&M.push(C)}if(M.length>0){const R=JSON.stringify({type:"file_reference",paths:M.map(E=>E.path),display_text:j});await i(R,g,a,_)}else await i(j,g,a,_)}else await i(j,g,a,_)}else await i(j,g,a,_);d(null),h([]),p(new Map)},[e,c,o,n,l,a,s,i,h,u,p,d,t])}),tC=({currentSessionId:e,currentChat:t,currentMessages:s,reasoningEffort:n,retryLastTurn:o,navigate:a})=>{const i=m.useCallback(async(c="regenerate")=>{if(!e||!t)return;const u=[...s];u.length===0||[...u].reverse().findIndex(h=>h.role==="user")===-1||await o(n,c)},[t,e,s,n,o]),l=m.useCallback((c,u)=>{const d=a(c,u);return d.applied?d.value:null},[a]);return{retryLastMessage:i,handleHistoryNavigate:l}},sC=({referenceText:e,isToolSpecificMode:t,isRestrictConversation:s,allowedTools:n,autoToolPrefix:o,t:a})=>a(e?"chat.input.placeholderWithReference":"chat.input.placeholderWithWorkflows"),Bc="chat-toggle-batch-export-selection",Wc="chat-focus-input",yr="chat-pending-question-resolved",nC=m.lazy(()=>Dt(()=>import("./index-BAibvIVz.js"),__vite__mapDeps([8,1,2,3]),import.meta.url)),rC=m.lazy(()=>Dt(()=>import("./index-yMJRRs89.js"),__vite__mapDeps([9,1,2,3,4,5,6,7,10]),import.meta.url)),oC=m.lazy(()=>Dt(()=>import("./index-C9mV36Y0.js"),__vite__mapDeps([11,1,2,3,4,5,6,7]),import.meta.url)),aC=m.lazy(()=>Dt(()=>import("./index-BNcuFl0J.js"),__vite__mapDeps([12,1,2,3]),import.meta.url)),{useToken:iC}=xe,bh="chat-send-message",xh="reference-text",lC="chat-model-options-cache-v1",cC=24*60*60*1e3,dC=["low","medium","high","xhigh","max"],uC=[],Xy=e=>`${lC}:${e}`,mC=e=>{if(typeof window>"u")return null;try{const t=localStorage.getItem(Xy(e));if(!t)return null;const s=JSON.parse(t);return!s||!Array.isArray(s.options)||Date.now()-s.timestamp>cC?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}},hC=(e,t)=>{if(!(typeof window>"u"))try{const s={timestamp:Date.now(),options:t};localStorage.setItem(Xy(e),JSON.stringify(s))}catch{}},pC=({sessionId:e,onWorkflowDraftChange:t,statusIndicator:s})=>{var iu,lu;const{t:n}=ie(),o=m.useRef(null),{token:a}=iC(),i=hd(),l=Xs(Q=>Q.open),c=L(Q=>e??Q.currentSessionId),u=L(Q=>Q.currentSessionId),d=L(bn(c)),h=(d==null?void 0:d.messages)||[],p=L(Q=>Q.addMessage),f=L(Q=>Q.updateSession),y=L(Q=>Q.processingChats),g=L(Q=>Q.setSessionProcessing),S=L(Q=>Q.pendingQuestionRespond),v=L(Q=>Q.clearPendingQuestionRespondForSession),x=L(Q=>Q.clearPendingQuestionForSession),T=Hi(c),_=Ud((iu=d==null?void 0:d.config)==null?void 0:iu.model_ref),j=ze(Q=>Q.isProviderModelRefEnabled),P=L(Q=>c?Q.inputStates[c]:void 0),M=L(Q=>Q.setInputContent),R=L(Q=>Q.setReferenceText),E=L(Q=>Q.setInputReasoningEffort),C=ze(Q=>Q.currentProvider),k=ze(Q=>Q.providerConfig),[b,w]=m.useState([]),[A,I]=m.useState(!1),[$,W]=m.useState(null),[O,re]=m.useState(!1),q=(P==null?void 0:P.content)||"",Z=(P==null?void 0:P.referenceText)||null,X=m.useMemo(()=>{var Q;return(Q=k.providers[C])==null?void 0:Q.reasoning_effort},[k,C]),se=m.useMemo(()=>c?xd(c):void 0,[c]),ee=((lu=d==null?void 0:d.config)==null?void 0:lu.reasoningEffort)??(P==null?void 0:P.reasoningEffort)??se??X??"medium",K=m.useCallback(Q=>{c&&M(c,Q)},[c,M]),F=m.useCallback(Q=>{c&&R(c,Q)},[c,R]),Y=m.useCallback(async Q=>{if(c&&(E(c,Q),!!d))try{await fr.patchSession(c,{reasoning_effort:Q}),f(c,{config:{...d.config,reasoningEffort:Q}})}catch(He){console.warn("[InputContainer] Failed to persist reasoning effort:",He)}},[d,c,E,f]),G=c?y.has(c):!1,{sendMessage:he,retryLastTurn:fe,cancel:ve}=Ry({sessionId:c,addMessage:p,setSessionProcessing:g,updateSession:f});m.useEffect(()=>{if(typeof window>"u")return;const Q=pt=>pt?c===pt:c!==null&&c===u,He=pt=>{const Xe=pt;if(!Xe.detail||typeof Xe.detail.text!="string")return;const hs=typeof Xe.detail.sessionId=="string"?Xe.detail.sessionId:null;if(!Q(hs))return;const ps=Xe.detail.text.trim();ps&&(Xe.detail.handled=!0,F(ps),requestAnimationFrame(()=>{var Cs;(Cs=o.current)==null||Cs.focus()}))},st=pt=>{var ps;const Xe=pt,hs=typeof((ps=Xe.detail)==null?void 0:ps.sessionId)=="string"?Xe.detail.sessionId:null;Q(hs)&&(Xe.detail&&(Xe.detail.handled=!0),requestAnimationFrame(()=>{var Cs;(Cs=o.current)==null||Cs.focus()}))};return window.addEventListener(xh,He),window.addEventListener(Wc,st),()=>{window.removeEventListener(xh,He),window.removeEventListener(Wc,st)}},[u,c,F]);const ke=G,{message:H}=ut.useApp(),Se=!1,Ie=!1,Fe=uC,D=void 0,{recordEntry:Te,navigate:ge,acknowledgeManualInput:Qe}=Vj(c),{attachments:We,setAttachments:J,handleAttachmentsAdded:le,handleAttachmentRemove:Ee,handleClearAttachments:N}=Zj(),oe=Kj({setContent:K,onWorkflowDraftChange:t,acknowledgeManualInput:Qe,currentSessionId:c,textAreaRef:o,content:q}),ae=Qj({content:q,setContent:K,currentSessionId:c,currentChat:d,updateSession:f,messageApi:H}),{setShowFileSelector:ce}=ae;m.useEffect(()=>{oe.showCommandSelector&&ce(!1)},[oe.showCommandSelector,ce]);const{handleSubmit:$e}=eC({attachments:We,referenceText:Z,selectedWorkflow:oe.selectedCommand,matchesWorkflowToken:oe.matchesCommandToken,fileReferences:ae.fileReferences,reasoningEffort:ee,sendMessage:he,recordEntry:Te,clearWorkflowDraft:oe.clearCommandDraft,setContent:K,setReferenceText:F,setAttachments:J,setFileReferences:ae.setFileReferences}),Ze=S&&S.sessionId===c?S:null,Ge=!!Ze,ct=(Ze==null?void 0:Ze.options)||[],Ye=(Ze==null?void 0:Ze.allowCustom)??!0,Ke=m.useCallback(Q=>{if(!Q)return!1;const He=L.getState().pendingQuestionRespond;return(He==null?void 0:He.sessionId)===Q},[]),Et=m.useCallback(async Q=>{const He=Q.trim();if(!He||!c)return;const st=L.getState().pendingQuestionRespond,pt=(st==null?void 0:st.sessionId)===c?st:null;if(pt&&!pt.allowCustom&&pt.options.length>0&&!pt.options.includes(He)){H.warning(n("components.questionDialog.selectOptionWarning"));return}try{const Xe={response:He,reasoning_effort:ee};j()&&_&&(Xe.model_ref=_,Xe.provider=_.provider);const hs=await we.post(`respond/${c}`,Xe);H.success(n("components.questionDialog.responseSubmittedContinue")),K(""),x(c),v(c),typeof window<"u"&&window.dispatchEvent(new CustomEvent(yr,{detail:{sessionId:c}}));const ps=hs==null?void 0:hs.auto_resume_status;ps&&["started","already_running"].includes(ps)&&g(c,!0)}catch(Xe){console.error("[InputContainer] Failed to submit respond:",Xe),H.error(Xe instanceof Error?Xe.message:n("components.questionDialog.submitFailed"))}},[c,ee,_,j,H,K,x,v,g,n]),Lt=m.useCallback(async(Q,He)=>{if(Ke(c)){await Et(Q);return}await $e(Q,He)},[c,Ke,Et,$e]),Vt=m.useCallback(async(Q,He)=>{await Lt(Q,He)},[Lt]);m.useEffect(()=>{if(typeof window>"u")return;const Q=He=>{var ps,Cs,cu;const st=He;if(!st.detail)return;const pt=typeof st.detail.sessionId=="string"?st.detail.sessionId:null;if(!(pt?c===pt:c!==null&&c===u))return;st.detail.handled=!0;const hs=(ps=st.detail)==null?void 0:ps.content;if(typeof hs!="string"||hs.trim().length===0){(cu=(Cs=st.detail)==null?void 0:Cs.reject)==null||cu.call(Cs,new Error("External send message content is empty"));return}Lt(hs,void 0).then(()=>{var Qn,wn;(wn=(Qn=st.detail)==null?void 0:Qn.resolve)==null||wn.call(Qn)}).catch(Qn=>{var wn,du;(du=(wn=st.detail)==null?void 0:wn.reject)==null||du.call(wn,Qn)})};return window.addEventListener(bh,Q),()=>{window.removeEventListener(bh,Q)}},[u,c,Lt]);const{retryLastMessage:Kt,handleHistoryNavigate:Ot}=tC({currentSessionId:c,currentChat:d,currentMessages:h,reasoningEffort:ee,retryLastTurn:fe,navigate:ge}),Qi=()=>F(null),ms=m.useMemo(()=>k.providers[C],[k,C]),Ts=m.useMemo(()=>!ms||typeof ms!="object"?!1:C==="copilot"?Object.keys(ms).length>0:"api_key"in ms?typeof ms.api_key=="string"&&ms.api_key.trim().length>0:!1,[C,ms]),tn=m.useCallback(()=>Ts?!1:(l("chat"),H.warning("Please configure provider first"),!0),[Ts,H,l]);m.useEffect(()=>{const Q=mC(C);w(Q??[]),W(null)},[C]);const Os=m.useCallback(Q=>Q instanceof Error&&Q.message.trim()?Q.message:"Unknown error",[]),Sn=m.useMemo(()=>({openai:[...ik],anthropic:[...lk],gemini:[...ck],copilot:[...dk],bodhi:[]})[C]||[],[C]),Jn=m.useMemo(()=>{const He=[...b.length>0?b:Sn];return T&&!He.some(st=>st.value===T)&&He.unshift({value:T,label:T}),He},[b,Sn,T]),Ar=m.useCallback(async(Q,He)=>{if(!(!(He!=null&&He.force)&&b.length>0))try{I(!0),W(null);const pt=(Q==="copilot"?await Lf.getModels():Sn).map(Xe=>({value:typeof Xe=="string"?Xe:Xe.value,label:typeof Xe=="string"?Xe:Xe.label}));w(pt),hC(Q,pt)}catch(st){W(Os(st))}finally{I(!1)}},[Sn,Os,b.length]),de=m.useCallback(Q=>{Q&&(tn()||A||b.length>0||Ar(C))},[C,Ar,A,b.length,tn]),Ae=m.useCallback(async Q=>{var He,st,pt;if(!(!Q||Q===T)&&!O)try{if(tn())return;if(re(!0),!c||!d){c&&f(c,{config:{systemPromptId:((He=d==null?void 0:d.config)==null?void 0:He.systemPromptId)||"default",baseSystemPrompt:((st=d==null?void 0:d.config)==null?void 0:st.baseSystemPrompt)||"",lastUsedEnhancedPrompt:((pt=d==null?void 0:d.config)==null?void 0:pt.lastUsedEnhancedPrompt)??null,...(d==null?void 0:d.config)||{},model:Q}});return}await fr.patchSession(c,{model:Q}),f(c,{config:{...d.config,model:Q}}),H.success(n("settings.providerTab.modelUpdated"))}catch(Xe){H.error(`${n("settings.providerTab.updateModelErrorPrefix")}: ${Os(Xe)}`)}finally{re(!1)}},[T,d,Os,O,H,tn,c,n,f]),Ne=m.useCallback(async Q=>{if(!c||!(d!=null&&d.config)){ze.getState().setSelectedModelRef(Q);return}if(!O)try{re(!0),await fr.patchSession(c,{model:Q.model,model_ref:Q,provider:Q.provider}),ze.getState().setSelectedModelRef(Q),f(c,{config:{...d.config,model:Q.model,model_ref:Q}}),H.success(n("settings.providerTab.modelUpdated"))}catch(He){H.error(`${n("settings.providerTab.updateModelErrorPrefix")}: ${Os(He)}`)}finally{re(!1)}},[d==null?void 0:d.config,Os,O,H,c,n,f]),nt=m.useMemo(()=>sC({referenceText:Z,isToolSpecificMode:Se,isRestrictConversation:Ie,allowedTools:Fe,autoToolPrefix:D,t:n}),[Z,Se,Ie,Fe,D,n]),Rt=Ge&&Ye?n("chat.respond.customAnswerPlaceholder"):Ge?n("components.questionDialog.selectOptionWarning"):nt,vn=Ge?n("chat.respond.submitToolResult","Submit tool result"):void 0,ks=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]),Gt=m.useMemo(()=>ks[ee]??ee,[ee,ks]),Fs=r.jsx(qn,{trigger:["click"],placement:"topLeft",disabled:!T||ke,menu:{selectable:!0,selectedKeys:[ee],items:dC.map(Q=>({key:Q,label:ks[Q]})),onClick:({key:Q})=>{Y(Q)}},children:r.jsx(B,{type:"text",size:"small",disabled:!T||ke,style:{minWidth:i?74:88,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:ee==="medium"?a.colorTextSecondary:a.colorPrimary},title:n("chat.input.reasoningTitle",{label:Gt}),children:r.jsxs(U,{size:6,children:[r.jsx(wf,{}),r.jsx("span",{children:Gt}),r.jsx(Xt,{style:{fontSize:10}})]})})}),js=T||n(Ts?"chat.model.selectModel":"chat.model.configureProvider"),sn=m.useMemo(()=>Jn.length>0?Jn.map(Q=>({key:Q.value,label:Q.label})):[{key:"__no_models__",label:$||n("chat.model.noModelsAvailable"),disabled:!0}],[Jn,$,n]),au=r.jsx(B,{type:"text",size:"small",disabled:ke||O,onClick:()=>{Ts||tn()},style:{minWidth:i?112:146,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:$?a.colorError:a.colorTextSecondary},title:js,children:r.jsxs(U,{size:6,children:[A?r.jsx(xr,{}):r.jsx(id,{}),r.jsx("span",{style:{maxWidth:i?84:128,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:js}),r.jsx(Xt,{style:{fontSize:10}})]})}),ex=j()?r.jsx(Wy,{value:_,onChange:Ne,disabled:ke||O}):Ts?r.jsx(qn,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:T?[T]:[],items:sn,style:{maxHeight:"50vh",overflowY:"auto"},onClick:({key:Q})=>{Q!=="__no_models__"&&Ae(String(Q))}},onOpenChange:de,disabled:ke||O,children:au}):au;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:[!T&&r.jsx(tt,{type:"warning",showIcon:!0,icon:r.jsx(da,{}),message:n(Ts?"chat.model.noModelSelected":"chat.model.providerNotConfigured"),description:n(Ts?"chat.model.selectModelHint":"chat.model.configureProviderHint"),action:Ts?void 0:r.jsx(U,{children:r.jsx("a",{onClick:()=>l("chat"),children:n("chat.model.openSettings")})}),style:{marginBottom:a.marginSM}}),Se,Z&&r.jsx(Xj,{text:Z,onClose:Qi}),We.length>0&&r.jsx(m.Suspense,{fallback:r.jsx(Ss,{size:"small"}),children:r.jsx(nC,{files:We,onRemove:Ee,onClear:N})}),Ge&&ct.length>0&&r.jsx("div",{style:{marginBottom:a.marginSM},children:r.jsx(U,{wrap:!0,size:[8,8],children:ct.map(Q=>r.jsx(B,{size:"small",onClick:()=>{Et(Q)},disabled:ke,children:Q},Q))})}),r.jsx(Hj,{value:q,onChange:oe.handleInputChange,onSubmit:Vt,placeholder:Rt,allowImages:!0,disabled:!T||Ge&&!Ye&&ct.length>0,statusIndicator:s,submitButtonLabel:vn,isWorkflowSelectorVisible:oe.showCommandSelector,textAreaRef:o,validateMessage:Q=>({isValid:!0}),onAttachmentsAdded:le,onWorkflowCommandChange:oe.handleCommandChange,onFileReferenceChange:ae.handleFileReferenceChange,onFileReferenceButtonClick:ae.handleFileReferenceButtonClick,leftControlsExtra:r.jsxs(U,{size:0,wrap:!0,children:[ex,Fs]}),interaction:{isStreaming:ke,hasMessages:h.some(Q=>Q.role==="user"),allowRetry:!0,onRetry:Kt,onCancel:ve,onHistoryNavigate:Ot}}),r.jsx(m.Suspense,{fallback:null,children:r.jsx(rC,{visible:oe.showCommandSelector,onSelect:oe.handleCommandSelect,onCancel:oe.handleCommandSelectorCancel,onAutoComplete:oe.handleAutoComplete,searchText:oe.commandSearchText})}),ae.showFileSelector&&r.jsx(m.Suspense,{fallback:r.jsx(Ss,{size:"small"}),children:r.jsx(aC,{visible:ae.showFileSelector,files:ae.workspaceFiles,searchText:ae.fileSearchText,loading:ae.isWorkspaceLoading,error:ae.workspaceError,onSelect:ae.handleFileReferenceSelect,onCancel:ae.handleFileSelectorCancel,onChangeWorkspace:()=>{ae.setWorkspacePathInput((d==null?void 0:d.config.workspacePath)??""),ae.setIsWorkspaceModalVisible(!0)}})}),r.jsx(m.Suspense,{fallback:null,children:r.jsx(oC,{open:ae.isWorkspaceModalVisible,initialPath:ae.workspacePathInput,loading:ae.isSavingWorkspace,onSubmit:ae.handleWorkspaceModalSubmit,onCancel:ae.handleWorkspaceModalCancel})})]})},{Text:Us}=pe,fC=220,gC="chat-session-diff-collapse:",yC=e=>e.split(/[\\/]/).pop()||e,Vy=e=>`${gC}${e??"default"}`,Rl=e=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(Vy(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}},bC=(e,t)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Vy(e),JSON.stringify(t))}catch{}},xC=({sessionDiffSummary:e,sessionId:t})=>{const{token:s}=xe.useToken(),n=!!(e&&e.files.length>0),[o,a]=m.useState(n),[i,l]=m.useState(n),[c,u]=m.useState(()=>{var y;return((y=Rl(t))==null?void 0:y.isExpanded)??!0}),[d,h]=m.useState(()=>{var y;return new Set(((y=Rl(t))==null?void 0:y.expandedFiles)??[])});m.useEffect(()=>{if(n){a(!0);const g=window.setTimeout(()=>l(!0),0);return()=>window.clearTimeout(g)}l(!1);const y=window.setTimeout(()=>a(!1),fC);return()=>window.clearTimeout(y)},[n]);const p=m.useMemo(()=>e?e.files:[],[e]),f=m.useMemo(()=>{const y=new Map;return e&&e.files.forEach(g=>{y.set(g.filePath,Oy(g.unifiedDiff))}),y},[e]);return m.useEffect(()=>{const y=Rl(t);u((y==null?void 0:y.isExpanded)??!0),h(new Set((y==null?void 0:y.expandedFiles)??[]))},[t]),m.useEffect(()=>{bC(t,{isExpanded:c,expandedFiles:Array.from(d)})},[t,c,d]),m.useEffect(()=>{if(!e||e.files.length===0)return;const y=new Set(e.files.map(g=>g.filePath));h(g=>{const S=new Set;let v=!1;return g.forEach(x=>{y.has(x)?S.add(x):v=!0}),!v&&S.size===g.size?g:S})},[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(te,{size:"small",style:{width:"100%",borderRadius:s.borderRadiusLG,border:`1px solid ${s.colorBorderSecondary}`,background:s.colorBgContainer,boxShadow:s.boxShadowSecondary},styles:{body:{padding:`${s.paddingXS}px ${s.paddingSM}px`}},children:r.jsxs(U,{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:()=>u(y=>!y),"data-testid":"session-diff-toggle",children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:s.marginSM,minWidth:0},children:[r.jsx(_f,{style:{color:s.colorPrimary}}),r.jsx(Us,{strong:!0,style:{whiteSpace:"nowrap"},children:"Session diffs"}),r.jsxs(Us,{type:"secondary",style:{fontSize:s.fontSizeSM,whiteSpace:"nowrap"},children:["(",e.files.length," files / ",e.changedTools," tools)"]}),r.jsxs(U,{size:4,style:{marginInlineStart:s.marginXS},children:[r.jsxs(Us,{style:{color:s.colorSuccess,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",e.totalAdded]}),r.jsxs(Us,{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(Xt,{}):r.jsx(Vs,{})})]}),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 g=d.has(y.filePath),S=f.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(v=>{const x=new Set(v);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:g?r.jsx(Xt,{}):r.jsx(Vs,{})}),r.jsx(Us,{ellipsis:{tooltip:y.filePath},style:{flex:1,minWidth:0,fontSize:s.fontSizeSM},children:yC(y.filePath)})]}),r.jsxs(U,{size:4,children:[r.jsxs(Us,{style:{color:s.colorSuccess,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",y.added]}),r.jsxs(Us,{style:{color:s.colorError,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",y.removed]})]})]}),g&&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:[S.length>0?S.map((v,x)=>{const T={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 v.kind==="add"?T.background=s.colorSuccessBg:v.kind==="remove"?T.background=s.colorErrorBg:v.kind==="modified_add"?(T.background=s.colorWarningBg,T.borderLeft=`3px solid ${s.colorSuccess}`):v.kind==="modified_remove"?(T.background=s.colorWarningBg,T.borderLeft=`3px solid ${s.colorError}`):v.kind==="hunk"?(T.background=s.colorFillSecondary,T.color=s.colorTextSecondary):v.kind==="meta"&&(T.background=s.colorFillTertiary,T.color=s.colorTextSecondary),r.jsx("pre",{style:T,"data-testid":"session-diff-line","data-kind":v.kind,children:v.text||" "},`${y.filePath}-${x}`)}):r.jsx(Us,{type:"secondary",style:{display:"block",padding:"8px",fontSize:s.fontSizeSM},children:"No diff preview available."}),y.truncated&&r.jsx(Us,{type:"secondary",style:{display:"block",padding:"6px 8px 8px",fontSize:s.fontSizeSM},children:"Diff truncated for display."})]})]},y.filePath)})})]})})})},SC=e=>{if(!e)return;const{activeLeafId:t,setLeafSessionId:s,setActiveLeafId:n}=Oe.getState();s(t,e),n(t),L.getState().selectSession(e)},vC=["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(" "),wC=["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(" "),_C=["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(" "),TC=["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(" "),kC=["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(" "),jC=["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(" "),CC=["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(" "),MC=["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(" "),PC=["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(" "),EC=["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(" "),RC=["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(" "),AC=["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(" "),IC=["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(" "),$C=["development","debugging","analysis","documentation","operations"],DC={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"}},LC=(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)||""}},Ky=({sessionId:e=null,embedded:t=!1,hideHeader:s=!1,layoutMode:n="default"})=>{var k;const{t:o}=ie(),{token:a}=xe.useToken(),{message:i}=ut.useApp(),l=L(b=>e??b.currentSessionId),c=L(bn(l)),u=L(b=>b.addChat),d=L(b=>b.lastSelectedPromptId),h=L(b=>b.setInputContent),p=L(b=>b.systemPrompts),f=L(b=>b.chats),[y,g]=m.useState(null),[S,v]=m.useState(""),x=(c==null?void 0:c.config.workspacePath)??((k=f.find(b=>b.config.workspacePath))==null?void 0:k.config.workspacePath),T=m.useMemo(()=>[{id:"blank",icon:r.jsx(Ks,{}),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:vC,category:"development",recommendWorkspace:!0},{id:"implementFeature",icon:r.jsx(Tr,{}),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:_C,category:"development",recommendWorkspace:!0},{id:"refactor",icon:r.jsx(_f,{}),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:CC,category:"development",recommendWorkspace:!0},{id:"bugInvestigation",icon:r.jsx(vf,{}),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:wC,category:"debugging",recommendWorkspace:!0},{id:"explainError",icon:r.jsx(rd,{}),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:kC,category:"debugging"},{id:"tokenUsage",icon:r.jsx(jx,{}),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:IC,category:"debugging"},{id:"architectureReview",icon:r.jsx(Cx,{}),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:TC,category:"analysis",recommendWorkspace:!0},{id:"compareFiles",icon:r.jsx(Mx,{}),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:jC,category:"analysis",recommendWorkspace:!0},{id:"releaseNotes",icon:r.jsx(vr,{}),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:MC,category:"documentation",recommendWorkspace:!0},{id:"summarizeWork",icon:r.jsx(Px,{}),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:PC,category:"documentation"},{id:"writeDocs",icon:r.jsx(vr,{}),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:EC,category:"documentation",recommendWorkspace:!0},{id:"createSchedule",icon:r.jsx(Qs,{}),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:RC,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:AC,category:"operations"}],[o]),_=S.trim().toLowerCase(),j=m.useMemo(()=>_?T.filter(b=>b.title.toLowerCase().includes(_)||b.description.toLowerCase().includes(_)):T,[_,T]),P=m.useMemo(()=>{const b={};for(const w of j)b[w.category]||(b[w.category]=[]),b[w.category].push(w);return b},[j]),M=m.useCallback(b=>{typeof window>"u"||window.setTimeout(()=>{window.dispatchEvent(new CustomEvent(Wc,{detail:{sessionId:b}}))},0)},[]),R=m.useCallback(async b=>{if(!y){g(b.id);try{const w=LC(p,d),A=await u({title:b.sessionTitle,createdAt:Date.now(),messages:[],config:{systemPromptId:w.systemPromptId,baseSystemPrompt:b.baseSystemPrompt??w.baseSystemPrompt,lastUsedEnhancedPrompt:null,...x?{workspacePath:x}:{}},currentInteraction:null});SC(A),b.prefill.trim().length>0&&h(A,b.prefill),M(A)}catch(w){console.error("[EmptyTaskLauncher] Failed to create session",w),i.error(w instanceof Error?w.message:o("chat.emptyLauncher.errors.createFailed","Failed to create session"))}finally{g(null)}}},[u,d,i,y,M,h,p,o,x]),E=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]),C=!!x;return r.jsxs("div",{className:`lotus-empty-task-launcher ${t?"is-embedded":""} ${s?"is-headerless":""} ${n==="staggered"?"is-staggered":""}`,style:E,children:[!s&&r.jsxs("div",{className:"lotus-empty-task-launcher__header",children:[r.jsx(pe.Title,{level:t?4:3,style:{margin:0},children:o("chat.emptyLauncher.title","Start with a task")}),r.jsx(pe.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(pe.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(be,{placeholder:o("chat.emptyLauncher.searchPlaceholder","Search templates..."),prefix:r.jsx(sa,{style:{color:a.colorTextQuaternary}}),value:S,onChange:b=>v(b.target.value),allowClear:!0,size:"middle",variant:"filled"})}),r.jsxs("div",{className:"lotus-empty-task-launcher__categories",children:[$C.map(b=>{const w=P[b];if(!w||w.length===0)return null;const A=DC[b];return r.jsxs("div",{className:"lotus-empty-task-launcher__category",children:[r.jsx(pe.Text,{type:"secondary",className:"lotus-empty-task-launcher__category-label",children:o(A.titleKey,A.fallback)}),r.jsx("div",{className:"lotus-empty-task-launcher__grid",children:w.map(I=>{const $=y===I.id,W=I.recommendWorkspace&&C;return r.jsxs("button",{type:"button",className:"lotus-empty-task-card",onClick:()=>{R(I)},disabled:y!==null,"aria-busy":$,"aria-label":I.title,children:[r.jsx("div",{className:"lotus-empty-task-card__icon","aria-hidden":!0,children:$?r.jsx(xr,{}):I.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:I.title}),r.jsx(Ex,{className:"lotus-empty-task-card__arrow","aria-hidden":!0})]}),r.jsx("p",{className:"lotus-empty-task-card__description",children:I.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")]})})]})]},I.id)})})]},b)}),j.length===0&&r.jsx("div",{className:"lotus-empty-task-launcher__no-results",children:r.jsx(pe.Text,{type:"secondary",children:o("chat.emptyLauncher.noResults","No templates match your search. Try a different keyword or start a blank session.")})})]})]})},OC=({sessionId:e,isCenteredLayout:t,maxWidth:s,onWorkflowDraftChange:n,showMessagesView:o,sessionDiffSummary:a,contextUsageIndicator:i})=>r.jsx(V,{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(xC,{sessionDiffSummary:a,sessionId:e}),!o&&e&&r.jsx(Ky,{sessionId:e}),r.jsx(pC,{sessionId:e,isCenteredLayout:t,onWorkflowDraftChange:n,statusIndicator:i})]})});function or(e,t,s){let n=s.initialDeps??[],o;function a(){var i,l,c,u;let d;s.key&&((i=s.debug)!=null&&i.call(s))&&(d=Date.now());const h=e();if(!(h.length!==n.length||h.some((y,g)=>n[g]!==y)))return o;n=h;let f;if(s.key&&((l=s.debug)!=null&&l.call(s))&&(f=Date.now()),o=t(...h),s.key&&((c=s.debug)!=null&&c.call(s))){const y=Math.round((Date.now()-d)*100)/100,g=Math.round((Date.now()-f)*100)/100,S=g/16,v=(x,T)=>{for(x=String(x);x.length<T;)x=" "+x;return x};console.info(`%c⏱ ${v(g,5)} /${v(y,5)} ms`,`
175
+ `);if(l(j),u(""),c(),o.size>0){const P=Array.from(j.matchAll(/@([^\\s]+)/g));if(P.length>0){const M=[];for(const R of P){const E=R[1],C=o.get(E);C&&M.push(C)}if(M.length>0){const R=JSON.stringify({type:"file_reference",paths:M.map(E=>E.path),display_text:j});await i(R,g,a,_)}else await i(j,g,a,_)}else await i(j,g,a,_)}else await i(j,g,a,_);d(null),h([]),p(new Map)},[e,c,o,n,l,a,s,i,h,u,p,d,t])}),tC=({currentSessionId:e,currentChat:t,currentMessages:s,reasoningEffort:n,retryLastTurn:o,navigate:a})=>{const i=m.useCallback(async(c="regenerate")=>{if(!e||!t)return;const u=[...s];u.length===0||[...u].reverse().findIndex(h=>h.role==="user")===-1||await o(n,c)},[t,e,s,n,o]),l=m.useCallback((c,u)=>{const d=a(c,u);return d.applied?d.value:null},[a]);return{retryLastMessage:i,handleHistoryNavigate:l}},sC=({referenceText:e,isToolSpecificMode:t,isRestrictConversation:s,allowedTools:n,autoToolPrefix:o,t:a})=>a(e?"chat.input.placeholderWithReference":"chat.input.placeholderWithWorkflows"),Bc="chat-toggle-batch-export-selection",Wc="chat-focus-input",yr="chat-pending-question-resolved",nC=m.lazy(()=>Dt(()=>import("./index-BAibvIVz.js"),__vite__mapDeps([8,1,2,3]),import.meta.url)),rC=m.lazy(()=>Dt(()=>import("./index-DjUMzvjR.js"),__vite__mapDeps([9,1,2,3,4,5,6,7,10]),import.meta.url)),oC=m.lazy(()=>Dt(()=>import("./index-BrpQmT5J.js"),__vite__mapDeps([11,1,2,3,4,5,6,7]),import.meta.url)),aC=m.lazy(()=>Dt(()=>import("./index-BNcuFl0J.js"),__vite__mapDeps([12,1,2,3]),import.meta.url)),{useToken:iC}=xe,bh="chat-send-message",xh="reference-text",lC="chat-model-options-cache-v1",cC=24*60*60*1e3,dC=["low","medium","high","xhigh","max"],uC=[],Xy=e=>`${lC}:${e}`,mC=e=>{if(typeof window>"u")return null;try{const t=localStorage.getItem(Xy(e));if(!t)return null;const s=JSON.parse(t);return!s||!Array.isArray(s.options)||Date.now()-s.timestamp>cC?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}},hC=(e,t)=>{if(!(typeof window>"u"))try{const s={timestamp:Date.now(),options:t};localStorage.setItem(Xy(e),JSON.stringify(s))}catch{}},pC=({sessionId:e,onWorkflowDraftChange:t,statusIndicator:s})=>{var iu,lu;const{t:n}=ie(),o=m.useRef(null),{token:a}=iC(),i=hd(),l=Xs(Q=>Q.open),c=L(Q=>e??Q.currentSessionId),u=L(Q=>Q.currentSessionId),d=L(bn(c)),h=(d==null?void 0:d.messages)||[],p=L(Q=>Q.addMessage),f=L(Q=>Q.updateSession),y=L(Q=>Q.processingChats),g=L(Q=>Q.setSessionProcessing),S=L(Q=>Q.pendingQuestionRespond),v=L(Q=>Q.clearPendingQuestionRespondForSession),x=L(Q=>Q.clearPendingQuestionForSession),T=Hi(c),_=Ud((iu=d==null?void 0:d.config)==null?void 0:iu.model_ref),j=ze(Q=>Q.isProviderModelRefEnabled),P=L(Q=>c?Q.inputStates[c]:void 0),M=L(Q=>Q.setInputContent),R=L(Q=>Q.setReferenceText),E=L(Q=>Q.setInputReasoningEffort),C=ze(Q=>Q.currentProvider),k=ze(Q=>Q.providerConfig),[b,w]=m.useState([]),[A,I]=m.useState(!1),[$,W]=m.useState(null),[O,re]=m.useState(!1),q=(P==null?void 0:P.content)||"",Z=(P==null?void 0:P.referenceText)||null,X=m.useMemo(()=>{var Q;return(Q=k.providers[C])==null?void 0:Q.reasoning_effort},[k,C]),se=m.useMemo(()=>c?xd(c):void 0,[c]),ee=((lu=d==null?void 0:d.config)==null?void 0:lu.reasoningEffort)??(P==null?void 0:P.reasoningEffort)??se??X??"medium",K=m.useCallback(Q=>{c&&M(c,Q)},[c,M]),F=m.useCallback(Q=>{c&&R(c,Q)},[c,R]),Y=m.useCallback(async Q=>{if(c&&(E(c,Q),!!d))try{await fr.patchSession(c,{reasoning_effort:Q}),f(c,{config:{...d.config,reasoningEffort:Q}})}catch(He){console.warn("[InputContainer] Failed to persist reasoning effort:",He)}},[d,c,E,f]),G=c?y.has(c):!1,{sendMessage:he,retryLastTurn:fe,cancel:ve}=Ry({sessionId:c,addMessage:p,setSessionProcessing:g,updateSession:f});m.useEffect(()=>{if(typeof window>"u")return;const Q=pt=>pt?c===pt:c!==null&&c===u,He=pt=>{const Xe=pt;if(!Xe.detail||typeof Xe.detail.text!="string")return;const hs=typeof Xe.detail.sessionId=="string"?Xe.detail.sessionId:null;if(!Q(hs))return;const ps=Xe.detail.text.trim();ps&&(Xe.detail.handled=!0,F(ps),requestAnimationFrame(()=>{var Cs;(Cs=o.current)==null||Cs.focus()}))},st=pt=>{var ps;const Xe=pt,hs=typeof((ps=Xe.detail)==null?void 0:ps.sessionId)=="string"?Xe.detail.sessionId:null;Q(hs)&&(Xe.detail&&(Xe.detail.handled=!0),requestAnimationFrame(()=>{var Cs;(Cs=o.current)==null||Cs.focus()}))};return window.addEventListener(xh,He),window.addEventListener(Wc,st),()=>{window.removeEventListener(xh,He),window.removeEventListener(Wc,st)}},[u,c,F]);const ke=G,{message:H}=ut.useApp(),Se=!1,Ie=!1,Fe=uC,D=void 0,{recordEntry:Te,navigate:ge,acknowledgeManualInput:Qe}=Vj(c),{attachments:We,setAttachments:J,handleAttachmentsAdded:le,handleAttachmentRemove:Ee,handleClearAttachments:N}=Zj(),oe=Kj({setContent:K,onWorkflowDraftChange:t,acknowledgeManualInput:Qe,currentSessionId:c,textAreaRef:o,content:q}),ae=Qj({content:q,setContent:K,currentSessionId:c,currentChat:d,updateSession:f,messageApi:H}),{setShowFileSelector:ce}=ae;m.useEffect(()=>{oe.showCommandSelector&&ce(!1)},[oe.showCommandSelector,ce]);const{handleSubmit:$e}=eC({attachments:We,referenceText:Z,selectedWorkflow:oe.selectedCommand,matchesWorkflowToken:oe.matchesCommandToken,fileReferences:ae.fileReferences,reasoningEffort:ee,sendMessage:he,recordEntry:Te,clearWorkflowDraft:oe.clearCommandDraft,setContent:K,setReferenceText:F,setAttachments:J,setFileReferences:ae.setFileReferences}),Ze=S&&S.sessionId===c?S:null,Ge=!!Ze,ct=(Ze==null?void 0:Ze.options)||[],Ye=(Ze==null?void 0:Ze.allowCustom)??!0,Ke=m.useCallback(Q=>{if(!Q)return!1;const He=L.getState().pendingQuestionRespond;return(He==null?void 0:He.sessionId)===Q},[]),Et=m.useCallback(async Q=>{const He=Q.trim();if(!He||!c)return;const st=L.getState().pendingQuestionRespond,pt=(st==null?void 0:st.sessionId)===c?st:null;if(pt&&!pt.allowCustom&&pt.options.length>0&&!pt.options.includes(He)){H.warning(n("components.questionDialog.selectOptionWarning"));return}try{const Xe={response:He,reasoning_effort:ee};j()&&_&&(Xe.model_ref=_,Xe.provider=_.provider);const hs=await we.post(`respond/${c}`,Xe);H.success(n("components.questionDialog.responseSubmittedContinue")),K(""),x(c),v(c),typeof window<"u"&&window.dispatchEvent(new CustomEvent(yr,{detail:{sessionId:c}}));const ps=hs==null?void 0:hs.auto_resume_status;ps&&["started","already_running"].includes(ps)&&g(c,!0)}catch(Xe){console.error("[InputContainer] Failed to submit respond:",Xe),H.error(Xe instanceof Error?Xe.message:n("components.questionDialog.submitFailed"))}},[c,ee,_,j,H,K,x,v,g,n]),Lt=m.useCallback(async(Q,He)=>{if(Ke(c)){await Et(Q);return}await $e(Q,He)},[c,Ke,Et,$e]),Vt=m.useCallback(async(Q,He)=>{await Lt(Q,He)},[Lt]);m.useEffect(()=>{if(typeof window>"u")return;const Q=He=>{var ps,Cs,cu;const st=He;if(!st.detail)return;const pt=typeof st.detail.sessionId=="string"?st.detail.sessionId:null;if(!(pt?c===pt:c!==null&&c===u))return;st.detail.handled=!0;const hs=(ps=st.detail)==null?void 0:ps.content;if(typeof hs!="string"||hs.trim().length===0){(cu=(Cs=st.detail)==null?void 0:Cs.reject)==null||cu.call(Cs,new Error("External send message content is empty"));return}Lt(hs,void 0).then(()=>{var Qn,wn;(wn=(Qn=st.detail)==null?void 0:Qn.resolve)==null||wn.call(Qn)}).catch(Qn=>{var wn,du;(du=(wn=st.detail)==null?void 0:wn.reject)==null||du.call(wn,Qn)})};return window.addEventListener(bh,Q),()=>{window.removeEventListener(bh,Q)}},[u,c,Lt]);const{retryLastMessage:Kt,handleHistoryNavigate:Ot}=tC({currentSessionId:c,currentChat:d,currentMessages:h,reasoningEffort:ee,retryLastTurn:fe,navigate:ge}),Qi=()=>F(null),ms=m.useMemo(()=>k.providers[C],[k,C]),Ts=m.useMemo(()=>!ms||typeof ms!="object"?!1:C==="copilot"?Object.keys(ms).length>0:"api_key"in ms?typeof ms.api_key=="string"&&ms.api_key.trim().length>0:!1,[C,ms]),tn=m.useCallback(()=>Ts?!1:(l("chat"),H.warning("Please configure provider first"),!0),[Ts,H,l]);m.useEffect(()=>{const Q=mC(C);w(Q??[]),W(null)},[C]);const Os=m.useCallback(Q=>Q instanceof Error&&Q.message.trim()?Q.message:"Unknown error",[]),Sn=m.useMemo(()=>({openai:[...ik],anthropic:[...lk],gemini:[...ck],copilot:[...dk],bodhi:[]})[C]||[],[C]),Jn=m.useMemo(()=>{const He=[...b.length>0?b:Sn];return T&&!He.some(st=>st.value===T)&&He.unshift({value:T,label:T}),He},[b,Sn,T]),Ar=m.useCallback(async(Q,He)=>{if(!(!(He!=null&&He.force)&&b.length>0))try{I(!0),W(null);const pt=(Q==="copilot"?await Lf.getModels():Sn).map(Xe=>({value:typeof Xe=="string"?Xe:Xe.value,label:typeof Xe=="string"?Xe:Xe.label}));w(pt),hC(Q,pt)}catch(st){W(Os(st))}finally{I(!1)}},[Sn,Os,b.length]),de=m.useCallback(Q=>{Q&&(tn()||A||b.length>0||Ar(C))},[C,Ar,A,b.length,tn]),Ae=m.useCallback(async Q=>{var He,st,pt;if(!(!Q||Q===T)&&!O)try{if(tn())return;if(re(!0),!c||!d){c&&f(c,{config:{systemPromptId:((He=d==null?void 0:d.config)==null?void 0:He.systemPromptId)||"default",baseSystemPrompt:((st=d==null?void 0:d.config)==null?void 0:st.baseSystemPrompt)||"",lastUsedEnhancedPrompt:((pt=d==null?void 0:d.config)==null?void 0:pt.lastUsedEnhancedPrompt)??null,...(d==null?void 0:d.config)||{},model:Q}});return}await fr.patchSession(c,{model:Q}),f(c,{config:{...d.config,model:Q}}),H.success(n("settings.providerTab.modelUpdated"))}catch(Xe){H.error(`${n("settings.providerTab.updateModelErrorPrefix")}: ${Os(Xe)}`)}finally{re(!1)}},[T,d,Os,O,H,tn,c,n,f]),Ne=m.useCallback(async Q=>{if(!c||!(d!=null&&d.config)){ze.getState().setSelectedModelRef(Q);return}if(!O)try{re(!0),await fr.patchSession(c,{model:Q.model,model_ref:Q,provider:Q.provider}),ze.getState().setSelectedModelRef(Q),f(c,{config:{...d.config,model:Q.model,model_ref:Q}}),H.success(n("settings.providerTab.modelUpdated"))}catch(He){H.error(`${n("settings.providerTab.updateModelErrorPrefix")}: ${Os(He)}`)}finally{re(!1)}},[d==null?void 0:d.config,Os,O,H,c,n,f]),nt=m.useMemo(()=>sC({referenceText:Z,isToolSpecificMode:Se,isRestrictConversation:Ie,allowedTools:Fe,autoToolPrefix:D,t:n}),[Z,Se,Ie,Fe,D,n]),Rt=Ge&&Ye?n("chat.respond.customAnswerPlaceholder"):Ge?n("components.questionDialog.selectOptionWarning"):nt,vn=Ge?n("chat.respond.submitToolResult","Submit tool result"):void 0,ks=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]),Gt=m.useMemo(()=>ks[ee]??ee,[ee,ks]),Fs=r.jsx(qn,{trigger:["click"],placement:"topLeft",disabled:!T||ke,menu:{selectable:!0,selectedKeys:[ee],items:dC.map(Q=>({key:Q,label:ks[Q]})),onClick:({key:Q})=>{Y(Q)}},children:r.jsx(B,{type:"text",size:"small",disabled:!T||ke,style:{minWidth:i?74:88,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:ee==="medium"?a.colorTextSecondary:a.colorPrimary},title:n("chat.input.reasoningTitle",{label:Gt}),children:r.jsxs(U,{size:6,children:[r.jsx(wf,{}),r.jsx("span",{children:Gt}),r.jsx(Xt,{style:{fontSize:10}})]})})}),js=T||n(Ts?"chat.model.selectModel":"chat.model.configureProvider"),sn=m.useMemo(()=>Jn.length>0?Jn.map(Q=>({key:Q.value,label:Q.label})):[{key:"__no_models__",label:$||n("chat.model.noModelsAvailable"),disabled:!0}],[Jn,$,n]),au=r.jsx(B,{type:"text",size:"small",disabled:ke||O,onClick:()=>{Ts||tn()},style:{minWidth:i?112:146,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:$?a.colorError:a.colorTextSecondary},title:js,children:r.jsxs(U,{size:6,children:[A?r.jsx(xr,{}):r.jsx(id,{}),r.jsx("span",{style:{maxWidth:i?84:128,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:js}),r.jsx(Xt,{style:{fontSize:10}})]})}),ex=j()?r.jsx(Wy,{value:_,onChange:Ne,disabled:ke||O}):Ts?r.jsx(qn,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:T?[T]:[],items:sn,style:{maxHeight:"50vh",overflowY:"auto"},onClick:({key:Q})=>{Q!=="__no_models__"&&Ae(String(Q))}},onOpenChange:de,disabled:ke||O,children:au}):au;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:[!T&&r.jsx(tt,{type:"warning",showIcon:!0,icon:r.jsx(da,{}),message:n(Ts?"chat.model.noModelSelected":"chat.model.providerNotConfigured"),description:n(Ts?"chat.model.selectModelHint":"chat.model.configureProviderHint"),action:Ts?void 0:r.jsx(U,{children:r.jsx("a",{onClick:()=>l("chat"),children:n("chat.model.openSettings")})}),style:{marginBottom:a.marginSM}}),Se,Z&&r.jsx(Xj,{text:Z,onClose:Qi}),We.length>0&&r.jsx(m.Suspense,{fallback:r.jsx(Ss,{size:"small"}),children:r.jsx(nC,{files:We,onRemove:Ee,onClear:N})}),Ge&&ct.length>0&&r.jsx("div",{style:{marginBottom:a.marginSM},children:r.jsx(U,{wrap:!0,size:[8,8],children:ct.map(Q=>r.jsx(B,{size:"small",onClick:()=>{Et(Q)},disabled:ke,children:Q},Q))})}),r.jsx(Hj,{value:q,onChange:oe.handleInputChange,onSubmit:Vt,placeholder:Rt,allowImages:!0,disabled:!T||Ge&&!Ye&&ct.length>0,statusIndicator:s,submitButtonLabel:vn,isWorkflowSelectorVisible:oe.showCommandSelector,textAreaRef:o,validateMessage:Q=>({isValid:!0}),onAttachmentsAdded:le,onWorkflowCommandChange:oe.handleCommandChange,onFileReferenceChange:ae.handleFileReferenceChange,onFileReferenceButtonClick:ae.handleFileReferenceButtonClick,leftControlsExtra:r.jsxs(U,{size:0,wrap:!0,children:[ex,Fs]}),interaction:{isStreaming:ke,hasMessages:h.some(Q=>Q.role==="user"),allowRetry:!0,onRetry:Kt,onCancel:ve,onHistoryNavigate:Ot}}),r.jsx(m.Suspense,{fallback:null,children:r.jsx(rC,{visible:oe.showCommandSelector,onSelect:oe.handleCommandSelect,onCancel:oe.handleCommandSelectorCancel,onAutoComplete:oe.handleAutoComplete,searchText:oe.commandSearchText})}),ae.showFileSelector&&r.jsx(m.Suspense,{fallback:r.jsx(Ss,{size:"small"}),children:r.jsx(aC,{visible:ae.showFileSelector,files:ae.workspaceFiles,searchText:ae.fileSearchText,loading:ae.isWorkspaceLoading,error:ae.workspaceError,onSelect:ae.handleFileReferenceSelect,onCancel:ae.handleFileSelectorCancel,onChangeWorkspace:()=>{ae.setWorkspacePathInput((d==null?void 0:d.config.workspacePath)??""),ae.setIsWorkspaceModalVisible(!0)}})}),r.jsx(m.Suspense,{fallback:null,children:r.jsx(oC,{open:ae.isWorkspaceModalVisible,initialPath:ae.workspacePathInput,loading:ae.isSavingWorkspace,onSubmit:ae.handleWorkspaceModalSubmit,onCancel:ae.handleWorkspaceModalCancel})})]})},{Text:Us}=pe,fC=220,gC="chat-session-diff-collapse:",yC=e=>e.split(/[\\/]/).pop()||e,Vy=e=>`${gC}${e??"default"}`,Rl=e=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(Vy(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}},bC=(e,t)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Vy(e),JSON.stringify(t))}catch{}},xC=({sessionDiffSummary:e,sessionId:t})=>{const{token:s}=xe.useToken(),n=!!(e&&e.files.length>0),[o,a]=m.useState(n),[i,l]=m.useState(n),[c,u]=m.useState(()=>{var y;return((y=Rl(t))==null?void 0:y.isExpanded)??!0}),[d,h]=m.useState(()=>{var y;return new Set(((y=Rl(t))==null?void 0:y.expandedFiles)??[])});m.useEffect(()=>{if(n){a(!0);const g=window.setTimeout(()=>l(!0),0);return()=>window.clearTimeout(g)}l(!1);const y=window.setTimeout(()=>a(!1),fC);return()=>window.clearTimeout(y)},[n]);const p=m.useMemo(()=>e?e.files:[],[e]),f=m.useMemo(()=>{const y=new Map;return e&&e.files.forEach(g=>{y.set(g.filePath,Oy(g.unifiedDiff))}),y},[e]);return m.useEffect(()=>{const y=Rl(t);u((y==null?void 0:y.isExpanded)??!0),h(new Set((y==null?void 0:y.expandedFiles)??[]))},[t]),m.useEffect(()=>{bC(t,{isExpanded:c,expandedFiles:Array.from(d)})},[t,c,d]),m.useEffect(()=>{if(!e||e.files.length===0)return;const y=new Set(e.files.map(g=>g.filePath));h(g=>{const S=new Set;let v=!1;return g.forEach(x=>{y.has(x)?S.add(x):v=!0}),!v&&S.size===g.size?g:S})},[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(te,{size:"small",style:{width:"100%",borderRadius:s.borderRadiusLG,border:`1px solid ${s.colorBorderSecondary}`,background:s.colorBgContainer,boxShadow:s.boxShadowSecondary},styles:{body:{padding:`${s.paddingXS}px ${s.paddingSM}px`}},children:r.jsxs(U,{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:()=>u(y=>!y),"data-testid":"session-diff-toggle",children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:s.marginSM,minWidth:0},children:[r.jsx(_f,{style:{color:s.colorPrimary}}),r.jsx(Us,{strong:!0,style:{whiteSpace:"nowrap"},children:"Session diffs"}),r.jsxs(Us,{type:"secondary",style:{fontSize:s.fontSizeSM,whiteSpace:"nowrap"},children:["(",e.files.length," files / ",e.changedTools," tools)"]}),r.jsxs(U,{size:4,style:{marginInlineStart:s.marginXS},children:[r.jsxs(Us,{style:{color:s.colorSuccess,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",e.totalAdded]}),r.jsxs(Us,{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(Xt,{}):r.jsx(Vs,{})})]}),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 g=d.has(y.filePath),S=f.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(v=>{const x=new Set(v);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:g?r.jsx(Xt,{}):r.jsx(Vs,{})}),r.jsx(Us,{ellipsis:{tooltip:y.filePath},style:{flex:1,minWidth:0,fontSize:s.fontSizeSM},children:yC(y.filePath)})]}),r.jsxs(U,{size:4,children:[r.jsxs(Us,{style:{color:s.colorSuccess,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",y.added]}),r.jsxs(Us,{style:{color:s.colorError,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",y.removed]})]})]}),g&&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:[S.length>0?S.map((v,x)=>{const T={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 v.kind==="add"?T.background=s.colorSuccessBg:v.kind==="remove"?T.background=s.colorErrorBg:v.kind==="modified_add"?(T.background=s.colorWarningBg,T.borderLeft=`3px solid ${s.colorSuccess}`):v.kind==="modified_remove"?(T.background=s.colorWarningBg,T.borderLeft=`3px solid ${s.colorError}`):v.kind==="hunk"?(T.background=s.colorFillSecondary,T.color=s.colorTextSecondary):v.kind==="meta"&&(T.background=s.colorFillTertiary,T.color=s.colorTextSecondary),r.jsx("pre",{style:T,"data-testid":"session-diff-line","data-kind":v.kind,children:v.text||" "},`${y.filePath}-${x}`)}):r.jsx(Us,{type:"secondary",style:{display:"block",padding:"8px",fontSize:s.fontSizeSM},children:"No diff preview available."}),y.truncated&&r.jsx(Us,{type:"secondary",style:{display:"block",padding:"6px 8px 8px",fontSize:s.fontSizeSM},children:"Diff truncated for display."})]})]},y.filePath)})})]})})})},SC=e=>{if(!e)return;const{activeLeafId:t,setLeafSessionId:s,setActiveLeafId:n}=Oe.getState();s(t,e),n(t),L.getState().selectSession(e)},vC=["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(" "),wC=["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(" "),_C=["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(" "),TC=["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(" "),kC=["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(" "),jC=["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(" "),CC=["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(" "),MC=["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(" "),PC=["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(" "),EC=["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(" "),RC=["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(" "),AC=["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(" "),IC=["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(" "),$C=["development","debugging","analysis","documentation","operations"],DC={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"}},LC=(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)||""}},Ky=({sessionId:e=null,embedded:t=!1,hideHeader:s=!1,layoutMode:n="default"})=>{var k;const{t:o}=ie(),{token:a}=xe.useToken(),{message:i}=ut.useApp(),l=L(b=>e??b.currentSessionId),c=L(bn(l)),u=L(b=>b.addChat),d=L(b=>b.lastSelectedPromptId),h=L(b=>b.setInputContent),p=L(b=>b.systemPrompts),f=L(b=>b.chats),[y,g]=m.useState(null),[S,v]=m.useState(""),x=(c==null?void 0:c.config.workspacePath)??((k=f.find(b=>b.config.workspacePath))==null?void 0:k.config.workspacePath),T=m.useMemo(()=>[{id:"blank",icon:r.jsx(Ks,{}),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:vC,category:"development",recommendWorkspace:!0},{id:"implementFeature",icon:r.jsx(Tr,{}),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:_C,category:"development",recommendWorkspace:!0},{id:"refactor",icon:r.jsx(_f,{}),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:CC,category:"development",recommendWorkspace:!0},{id:"bugInvestigation",icon:r.jsx(vf,{}),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:wC,category:"debugging",recommendWorkspace:!0},{id:"explainError",icon:r.jsx(rd,{}),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:kC,category:"debugging"},{id:"tokenUsage",icon:r.jsx(jx,{}),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:IC,category:"debugging"},{id:"architectureReview",icon:r.jsx(Cx,{}),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:TC,category:"analysis",recommendWorkspace:!0},{id:"compareFiles",icon:r.jsx(Mx,{}),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:jC,category:"analysis",recommendWorkspace:!0},{id:"releaseNotes",icon:r.jsx(vr,{}),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:MC,category:"documentation",recommendWorkspace:!0},{id:"summarizeWork",icon:r.jsx(Px,{}),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:PC,category:"documentation"},{id:"writeDocs",icon:r.jsx(vr,{}),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:EC,category:"documentation",recommendWorkspace:!0},{id:"createSchedule",icon:r.jsx(Qs,{}),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:RC,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:AC,category:"operations"}],[o]),_=S.trim().toLowerCase(),j=m.useMemo(()=>_?T.filter(b=>b.title.toLowerCase().includes(_)||b.description.toLowerCase().includes(_)):T,[_,T]),P=m.useMemo(()=>{const b={};for(const w of j)b[w.category]||(b[w.category]=[]),b[w.category].push(w);return b},[j]),M=m.useCallback(b=>{typeof window>"u"||window.setTimeout(()=>{window.dispatchEvent(new CustomEvent(Wc,{detail:{sessionId:b}}))},0)},[]),R=m.useCallback(async b=>{if(!y){g(b.id);try{const w=LC(p,d),A=await u({title:b.sessionTitle,createdAt:Date.now(),messages:[],config:{systemPromptId:w.systemPromptId,baseSystemPrompt:b.baseSystemPrompt??w.baseSystemPrompt,lastUsedEnhancedPrompt:null,...x?{workspacePath:x}:{}},currentInteraction:null});SC(A),b.prefill.trim().length>0&&h(A,b.prefill),M(A)}catch(w){console.error("[EmptyTaskLauncher] Failed to create session",w),i.error(w instanceof Error?w.message:o("chat.emptyLauncher.errors.createFailed","Failed to create session"))}finally{g(null)}}},[u,d,i,y,M,h,p,o,x]),E=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]),C=!!x;return r.jsxs("div",{className:`lotus-empty-task-launcher ${t?"is-embedded":""} ${s?"is-headerless":""} ${n==="staggered"?"is-staggered":""}`,style:E,children:[!s&&r.jsxs("div",{className:"lotus-empty-task-launcher__header",children:[r.jsx(pe.Title,{level:t?4:3,style:{margin:0},children:o("chat.emptyLauncher.title","Start with a task")}),r.jsx(pe.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(pe.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(be,{placeholder:o("chat.emptyLauncher.searchPlaceholder","Search templates..."),prefix:r.jsx(sa,{style:{color:a.colorTextQuaternary}}),value:S,onChange:b=>v(b.target.value),allowClear:!0,size:"middle",variant:"filled"})}),r.jsxs("div",{className:"lotus-empty-task-launcher__categories",children:[$C.map(b=>{const w=P[b];if(!w||w.length===0)return null;const A=DC[b];return r.jsxs("div",{className:"lotus-empty-task-launcher__category",children:[r.jsx(pe.Text,{type:"secondary",className:"lotus-empty-task-launcher__category-label",children:o(A.titleKey,A.fallback)}),r.jsx("div",{className:"lotus-empty-task-launcher__grid",children:w.map(I=>{const $=y===I.id,W=I.recommendWorkspace&&C;return r.jsxs("button",{type:"button",className:"lotus-empty-task-card",onClick:()=>{R(I)},disabled:y!==null,"aria-busy":$,"aria-label":I.title,children:[r.jsx("div",{className:"lotus-empty-task-card__icon","aria-hidden":!0,children:$?r.jsx(xr,{}):I.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:I.title}),r.jsx(Ex,{className:"lotus-empty-task-card__arrow","aria-hidden":!0})]}),r.jsx("p",{className:"lotus-empty-task-card__description",children:I.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")]})})]})]},I.id)})})]},b)}),j.length===0&&r.jsx("div",{className:"lotus-empty-task-launcher__no-results",children:r.jsx(pe.Text,{type:"secondary",children:o("chat.emptyLauncher.noResults","No templates match your search. Try a different keyword or start a blank session.")})})]})]})},OC=({sessionId:e,isCenteredLayout:t,maxWidth:s,onWorkflowDraftChange:n,showMessagesView:o,sessionDiffSummary:a,contextUsageIndicator:i})=>r.jsx(V,{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(xC,{sessionDiffSummary:a,sessionId:e}),!o&&e&&r.jsx(Ky,{sessionId:e}),r.jsx(pC,{sessionId:e,isCenteredLayout:t,onWorkflowDraftChange:n,statusIndicator:i})]})});function or(e,t,s){let n=s.initialDeps??[],o;function a(){var i,l,c,u;let d;s.key&&((i=s.debug)!=null&&i.call(s))&&(d=Date.now());const h=e();if(!(h.length!==n.length||h.some((y,g)=>n[g]!==y)))return o;n=h;let f;if(s.key&&((l=s.debug)!=null&&l.call(s))&&(f=Date.now()),o=t(...h),s.key&&((c=s.debug)!=null&&c.call(s))){const y=Math.round((Date.now()-d)*100)/100,g=Math.round((Date.now()-f)*100)/100,S=g/16,v=(x,T)=>{for(x=String(x);x.length<T;)x=" "+x;return x};console.info(`%c⏱ ${v(g,5)} /${v(y,5)} ms`,`
176
176
  font-size: .6rem;
177
177
  font-weight: bold;
178
178
  color: hsl(${Math.max(0,Math.min(120-120*S,120))}deg 100% 31%);`,s==null?void 0:s.key)}return(u=s==null?void 0:s.onChange)==null||u.call(s,o),o}return a.updateDeps=i=>{n=i},a}function Sh(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const FC=(e,t)=>Math.abs(e-t)<1.01,zC=(e,t,s)=>{let n;return function(...o){e.clearTimeout(n),n=e.setTimeout(()=>t.apply(this,o),s)}},vh=e=>{const{offsetWidth:t,offsetHeight:s}=e;return{width:t,height:s}},NC=e=>e,BC=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},WC=(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(vh(s)),!n.ResizeObserver)return()=>{};const a=new n.ResizeObserver(i=>{const l=()=>{const c=i[0];if(c!=null&&c.borderBoxSize){const u=c.borderBoxSize[0];if(u){o({width:u.inlineSize,height:u.blockSize});return}}o(vh(s))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return a.observe(s,{box:"border-box"}),()=>{a.unobserve(s)}},wh={passive:!0},_h=typeof window>"u"?!0:"onscrollend"in window,UC=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;let o=0;const a=e.options.useScrollendEvent&&_h?()=>{}:zC(n,()=>{t(o,!1)},e.options.isScrollingResetDelay),i=d=>()=>{const{horizontal:h,isRtl:p}=e.options;o=h?s.scrollLeft*(p&&-1||1):s.scrollTop,a(),t(o,d)},l=i(!0),c=i(!1);c(),s.addEventListener("scroll",l,wh);const u=e.options.useScrollendEvent&&_h;return u&&s.addEventListener("scrollend",c,wh),()=>{s.removeEventListener("scroll",l),u&&s.removeEventListener("scrollend",c)}},qC=(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"]},HC=(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 YC{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:NC,rangeExtractor:BC,onChange:()=>{},measureElement:qC,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=or(()=>(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=or(()=>[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=or(()=>[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(d=>{this.itemSizeCache.set(d.key,d.size)}));const c=this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[];const u=this.measurementsCache.slice(0,c);for(let d=c;d<s;d++){const h=a(d),p=this.options.lanes===1?u[d-1]:this.getFurthestMeasurement(u,d),f=p?p.end+this.options.gap:n+o,y=l.get(h),g=typeof y=="number"?y:this.options.estimateSize(d),S=f+g,v=p?p.lane:d%this.options.lanes;u[d]={index:d,start:f,size:g,end:S,key:h,lane:v}}return this.measurementsCache=u,u},{key:!1,debug:()=>this.options.debug}),this.calculateRange=or(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(s,n,o,a)=>this.range=s.length>0&&n>0?XC({measurements:s,outerSize:n,scrollOffset:o,lanes:a}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=or(()=>{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=or(()=>[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 Sh(n[Gy(0,n.length-1,o=>Sh(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=u=>{if(!this.targetWindow)return;const d=this.getOffsetForIndex(s,u);if(!d){console.warn("Failed to get offset for index:",s);return}const[h,p]=d;this._scrollToOffset(h,{adjustments:void 0,behavior:o}),this.targetWindow.requestAnimationFrame(()=>{const f=this.getScrollOffset(),y=this.getOffsetForIndex(s,p);if(!y){console.warn("Failed to get offset for index:",s);return}FC(y[0],f)||c(p)})},c=u=>{this.targetWindow&&(a++,a<i?this.targetWindow.requestAnimationFrame(()=>l(u)):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 Gy=(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 XC({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=Gy(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(d=>d<s+t);){const d=e[l];c[d.lane]=d.end,l++}const u=Array(n).fill(s+t);for(;i>=0&&u.some(d=>d>=s);){const d=e[i];u[d.lane]=d.start,i--}i=Math.max(0,i-i%n),l=Math.min(o,l+(n-1-l%n))}return{startIndex:i,endIndex:l}}const Th=typeof document<"u"?m.useLayoutEffect:m.useEffect;function VC(e){const t=m.useReducer(()=>({}),{})[1],s={...e,onChange:(o,a)=>{var i;a?Rx.flushSync(t):t(),(i=e.onChange)==null||i.call(e,o,a)}},[n]=m.useState(()=>new YC(s));return n.setOptions(s),Th(()=>n._didMount(),[]),Th(()=>n._willUpdate()),n}function KC(e){return VC({observeElementRect:WC,observeElementOffset:UC,scrollToFn:HC,...e})}const{Text:kh,Paragraph:GC}=pe,JC=({content:e,token:t,headingColor:s})=>r.jsx(xs,{components:{p:({children:n})=>r.jsx(GC,{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(kh,{strong:!0,style:{fontSize:t.fontSizeHeading3,marginBottom:t.marginSM,display:"block",color:s},children:n}),h2:({children:n})=>r.jsx(kh,{strong:!0,style:{fontSize:t.fontSizeHeading4,marginBottom:t.marginSM,display:"block",color:s},children:n})},children:e}),jh=m.memo(JC),QC=e=>{if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null},ZC=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=QC(n);return o?[{key:s,content:o}]:[]}):[],eM=({currentChat:e,message:t,systemPrompts:s})=>{var C;const[n,o]=m.useState(null),[a,i]=m.useState(null),[l,c]=m.useState(null),[u,d]=m.useState(!1),[h,p]=m.useState(!1),f=m.useMemo(()=>yi.getInstance(),[]),y=m.useMemo(()=>ds.getInstance(),[]),g=t.role==="system"&&typeof t.content=="string"?t.content:"",S=t.role==="system"&&!t.id.startsWith("system-prompt-")&&g.trim().length>0;m.useEffect(()=>{t.role==="system"&&(i(null),c(null),p(!1))},[t.id,t.role,g]);const v=(e==null?void 0:e.id)??null,x=((C=e==null?void 0:e.config)==null?void 0:C.systemPromptId)??null,T=m.useMemo(()=>x?s.find(k=>k.id===x)??null:null,[x,s]),_=(T==null?void 0:T.content)??(n==null?void 0:n.content)??"",j=(T==null?void 0:T.description)??(n==null?void 0:n.description)??"",P=m.useRef(null);m.useEffect(()=>{o(null),P.current=null},[v,x]),m.useEffect(()=>{if(!x)return;const k=x;if(T!=null&&T.content)return;const b=`${v??"no-chat"}:${k}`;if(P.current===b)return;P.current=b;let w=!1;return(async()=>{try{const I=await f.findPresetById(k);if(w)return;const $=I?{content:I.content,description:I.description}:null;o(W=>!W&&!$||W&&$&&W.content===$.content&&W.description===$.description?W:$)}catch(I){console.error("Failed to load preset prompt:",I)}})(),()=>{w=!0}},[v,x,f,T==null?void 0:T.content]);const M=m.useCallback(async()=>{var k;if(!u){d(!0);try{if(v)try{const b=await y.getSessionSystemPrompt(v);c(b);const w=(k=b.effective_system_prompt)==null?void 0:k.trim();if(w){i(w),p(!0);return}}catch(b){console.warn("Failed to load backend prompt snapshot:",b)}if(S){c(null),i(g),p(!0);return}console.warn("Enhanced prompt snapshot unavailable; keeping base prompt view.")}catch(b){console.error("Failed to load enhanced prompt:",b)}finally{d(!1)}}},[y,v,S,u,g]),R=m.useMemo(()=>h&&a?a:_||j||(t.role==="system"?g:"System prompt is being prepared..."),[h,a,_,j,t.role,g]),E=m.useMemo(()=>ZC(l),[l]);return{basePrompt:_,categoryDescription:j,enhancedPrompt:a,loadingEnhanced:u,loadEnhancedPrompt:M,promptSnapshot:l,promptToDisplay:R,showEnhanced:h,setShowEnhanced:p,snapshotSections:E,systemMessageContent:g}},{Text:Ch}=pe,{useToken:tM}=xe,sM=(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],nM=({currentChat:e,message:t})=>{const{token:s}=tM(),{t:n}=ie(),o=L(y=>y.systemPrompts),{basePrompt:a,loadingEnhanced:i,loadEnhancedPrompt:l,promptSnapshot:c,promptToDisplay:u,showEnhanced:d,setShowEnhanced:h,snapshotSections:p}=eM({currentChat:e,message:t,systemPrompts:o}),f=m.useCallback(async y=>{try{await us(y)}catch(g){console.error("Failed to copy text:",g)}},[]);return r.jsx(te,{style:{width:"100%",maxWidth:"100%",background:s.colorBgContainer,borderRadius:s.borderRadiusLG,boxShadow:"none"},children:r.jsxs(U,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[r.jsxs(V,{justify:"space-between",align:"center",children:[r.jsx(V,{align:"center",gap:s.marginXS,children:r.jsx(Ch,{type:"secondary",strong:!0,style:{fontSize:s.fontSizeSM},children:n("chat.prompt.systemCard.title")})}),r.jsxs(U,{children:[a&&!d?r.jsx(B,{type:"text",size:"small",icon:r.jsx(sd,{}),onClick:l,loading:i,children:n("chat.prompt.systemCard.viewEnhanced")}):null,a&&d?r.jsx(B,{type:"text",size:"small",onClick:()=>h(!1),children:n("chat.prompt.systemCard.viewBase")}):null,r.jsx(B,{type:"text",size:"small",icon:r.jsx(cs,{}),onClick:()=>f(u),children:n("chat.prompt.systemCard.copy")})]})]}),r.jsx(V,{vertical:!0,style:{maxHeight:d?400:300,overflowY:"auto",paddingRight:s.paddingXS},children:r.jsx(jh,{content:u,token:s,headingColor:s.colorPrimary})}),c&&p.length>0?r.jsxs(r.Fragment,{children:[r.jsx($t,{style:{margin:`${s.marginXS}px 0`}}),r.jsxs(U,{direction:"vertical",size:s.marginXS,style:{width:"100%"},children:[r.jsx(Ch,{type:"secondary",strong:!0,style:{fontSize:s.fontSizeSM},children:n("chat.prompt.systemCard.snapshotTitle")}),r.jsx(ws,{defaultActiveKey:p.map(y=>y.key),items:p.map(y=>({key:y.key,label:sM(n,y.key),children:r.jsx(jh,{content:y.content,token:s,headingColor:s.colorPrimary})}))})]})]}):null]})})},Jy=m.memo(nM);Jy.displayName="SystemMessageCard";const Qy=6048e5,rM=864e5,Mh=Symbol.for("constructDateFrom");function hn(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&Mh in e?e[Mh](t):e instanceof Date?new e.constructor(t):new Date(t)}function _s(e,t){return hn(t||e,e)}let oM={};function Ki(){return oM}function la(e,t){var l,c,u,d;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??((d=(u=s.locale)==null?void 0:u.options)==null?void 0:d.weekStartsOn)??0,o=_s(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 Zy(e,t){const s=_s(e,t==null?void 0:t.in),n=s.getFullYear(),o=hn(s,0);o.setFullYear(n+1,0,4),o.setHours(0,0,0,0);const a=Ei(o),i=hn(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 Ph(e){const t=_s(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 aM(e,...t){const s=hn.bind(null,t.find(n=>typeof n=="object"));return t.map(s)}function Eh(e,t){const s=_s(e,t==null?void 0:t.in);return s.setHours(0,0,0,0),s}function iM(e,t,s){const[n,o]=aM(s==null?void 0:s.in,e,t),a=Eh(n),i=Eh(o),l=+a-Ph(a),c=+i-Ph(i);return Math.round((l-c)/rM)}function lM(e,t){const s=Zy(e,t),n=hn(e,0);return n.setFullYear(s,0,4),n.setHours(0,0,0,0),Ei(n)}function cM(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function dM(e){return!(!cM(e)&&typeof e!="number"||isNaN(+_s(e)))}function uM(e,t){const s=_s(e,t==null?void 0:t.in);return s.setFullYear(s.getFullYear(),0,1),s.setHours(0,0,0,0),s}const mM={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"}},hM=(e,t,s)=>{let n;const o=mM[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 Al(e){return(t={})=>{const s=t.width?String(t.width):e.defaultWidth;return e.formats[s]||e.formats[e.defaultWidth]}}const pM={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},fM={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},gM={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},yM={date:Al({formats:pM,defaultWidth:"full"}),time:Al({formats:fM,defaultWidth:"full"}),dateTime:Al({formats:gM,defaultWidth:"full"})},bM={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},xM=(e,t,s,n)=>bM[e];function Vr(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 SM={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},vM={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},wM={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"]},_M={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"]},TM={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"}},kM={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"}},jM=(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"},CM={ordinalNumber:jM,era:Vr({values:SM,defaultWidth:"wide"}),quarter:Vr({values:vM,defaultWidth:"wide",argumentCallback:e=>e-1}),month:Vr({values:wM,defaultWidth:"wide"}),day:Vr({values:_M,defaultWidth:"wide"}),dayPeriod:Vr({values:TM,defaultWidth:"wide",formattingValues:kM,defaultFormattingWidth:"wide"})};function Kr(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)?PM(l,h=>h.test(i)):MM(l,h=>h.test(i));let u;u=e.valueCallback?e.valueCallback(c):c,u=s.valueCallback?s.valueCallback(u):u;const d=t.slice(i.length);return{value:u,rest:d}}}function MM(e,t){for(const s in e)if(Object.prototype.hasOwnProperty.call(e,s)&&t(e[s]))return s}function PM(e,t){for(let s=0;s<e.length;s++)if(t(e[s]))return s}function EM(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 RM=/^(\d+)(th|st|nd|rd)?/i,AM=/\d+/i,IM={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},$M={any:[/^b/i,/^(a|c)/i]},DM={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},LM={any:[/1/i,/2/i,/3/i,/4/i]},OM={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},FM={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]},zM={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},NM={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]},BM={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},WM={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}},UM={ordinalNumber:EM({matchPattern:RM,parsePattern:AM,valueCallback:e=>parseInt(e,10)}),era:Kr({matchPatterns:IM,defaultMatchWidth:"wide",parsePatterns:$M,defaultParseWidth:"any"}),quarter:Kr({matchPatterns:DM,defaultMatchWidth:"wide",parsePatterns:LM,defaultParseWidth:"any",valueCallback:e=>e+1}),month:Kr({matchPatterns:OM,defaultMatchWidth:"wide",parsePatterns:FM,defaultParseWidth:"any"}),day:Kr({matchPatterns:zM,defaultMatchWidth:"wide",parsePatterns:NM,defaultParseWidth:"any"}),dayPeriod:Kr({matchPatterns:BM,defaultMatchWidth:"any",parsePatterns:WM,defaultParseWidth:"any"})},qM={code:"en-US",formatDistance:hM,formatLong:yM,formatRelative:xM,localize:CM,match:UM,options:{weekStartsOn:0,firstWeekContainsDate:1}};function HM(e,t){const s=_s(e,t==null?void 0:t.in);return iM(s,uM(s))+1}function YM(e,t){const s=_s(e,t==null?void 0:t.in),n=+Ei(s)-+lM(s);return Math.round(n/Qy)+1}function eb(e,t){var d,h,p,f;const s=_s(e,t==null?void 0:t.in),n=s.getFullYear(),o=Ki(),a=(t==null?void 0:t.firstWeekContainsDate)??((h=(d=t==null?void 0:t.locale)==null?void 0:d.options)==null?void 0:h.firstWeekContainsDate)??o.firstWeekContainsDate??((f=(p=o.locale)==null?void 0:p.options)==null?void 0:f.firstWeekContainsDate)??1,i=hn((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=hn((t==null?void 0:t.in)||e,0);c.setFullYear(n,0,a),c.setHours(0,0,0,0);const u=la(c,t);return+s>=+l?n+1:+s>=+u?n:n-1}function XM(e,t){var l,c,u,d;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??((d=(u=s.locale)==null?void 0:u.options)==null?void 0:d.firstWeekContainsDate)??1,o=eb(e,t),a=hn((t==null?void 0:t.in)||e,0);return a.setFullYear(o,0,n),a.setHours(0,0,0,0),la(a,t)}function VM(e,t){const s=_s(e,t==null?void 0:t.in),n=+la(s,t)-+XM(s,t);return Math.round(n/Qy)+1}function Ve(e,t){const s=e<0?"-":"",n=Math.abs(e).toString().padStart(t,"0");return s+n}const an={y(e,t){const s=e.getFullYear(),n=s>0?s:1-s;return Ve(t==="yy"?n%100:n,t.length)},M(e,t){const s=e.getMonth();return t==="M"?String(s+1):Ve(s+1,2)},d(e,t){return Ve(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 Ve(e.getHours()%12||12,t.length)},H(e,t){return Ve(e.getHours(),t.length)},m(e,t){return Ve(e.getMinutes(),t.length)},s(e,t){return Ve(e.getSeconds(),t.length)},S(e,t){const s=t.length,n=e.getMilliseconds(),o=Math.trunc(n*Math.pow(10,s-3));return Ve(o,t.length)}},ar={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Rh={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 an.y(e,t)},Y:function(e,t,s,n){const o=eb(e,n),a=o>0?o:1-o;if(t==="YY"){const i=a%100;return Ve(i,2)}return t==="Yo"?s.ordinalNumber(a,{unit:"year"}):Ve(a,t.length)},R:function(e,t){const s=Zy(e);return Ve(s,t.length)},u:function(e,t){const s=e.getFullYear();return Ve(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 Ve(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 Ve(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 an.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 Ve(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=VM(e,n);return t==="wo"?s.ordinalNumber(o,{unit:"week"}):Ve(o,t.length)},I:function(e,t,s){const n=YM(e);return t==="Io"?s.ordinalNumber(n,{unit:"week"}):Ve(n,t.length)},d:function(e,t,s){return t==="do"?s.ordinalNumber(e.getDate(),{unit:"date"}):an.d(e,t)},D:function(e,t,s){const n=HM(e);return t==="Do"?s.ordinalNumber(n,{unit:"dayOfYear"}):Ve(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 Ve(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 Ve(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 Ve(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=ar.noon:n===0?o=ar.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=ar.evening:n>=12?o=ar.afternoon:n>=4?o=ar.morning:o=ar.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 an.h(e,t)},H:function(e,t,s){return t==="Ho"?s.ordinalNumber(e.getHours(),{unit:"hour"}):an.H(e,t)},K:function(e,t,s){const n=e.getHours()%12;return t==="Ko"?s.ordinalNumber(n,{unit:"hour"}):Ve(n,t.length)},k:function(e,t,s){let n=e.getHours();return n===0&&(n=24),t==="ko"?s.ordinalNumber(n,{unit:"hour"}):Ve(n,t.length)},m:function(e,t,s){return t==="mo"?s.ordinalNumber(e.getMinutes(),{unit:"minute"}):an.m(e,t)},s:function(e,t,s){return t==="so"?s.ordinalNumber(e.getSeconds(),{unit:"second"}):an.s(e,t)},S:function(e,t){return an.S(e,t)},X:function(e,t,s){const n=e.getTimezoneOffset();if(n===0)return"Z";switch(t){case"X":return Ih(n);case"XXXX":case"XX":return Pn(n);case"XXXXX":case"XXX":default:return Pn(n,":")}},x:function(e,t,s){const n=e.getTimezoneOffset();switch(t){case"x":return Ih(n);case"xxxx":case"xx":return Pn(n);case"xxxxx":case"xxx":default:return Pn(n,":")}},O:function(e,t,s){const n=e.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+Ah(n,":");case"OOOO":default:return"GMT"+Pn(n,":")}},z:function(e,t,s){const n=e.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+Ah(n,":");case"zzzz":default:return"GMT"+Pn(n,":")}},t:function(e,t,s){const n=Math.trunc(+e/1e3);return Ve(n,t.length)},T:function(e,t,s){return Ve(+e,t.length)}};function Ah(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+Ve(a,2)}function Ih(e,t){return e%60===0?(e>0?"-":"+")+Ve(Math.abs(e)/60,2):Pn(e,t)}function Pn(e,t=""){const s=e>0?"-":"+",n=Math.abs(e),o=Ve(Math.trunc(n/60),2),a=Ve(n%60,2);return s+o+t+a}const $h=(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"})}},tb=(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"})}},KM=(e,t)=>{const s=e.match(/(P+)(p+)?/)||[],n=s[1],o=s[2];if(!o)return $h(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}}",$h(n,t)).replace("{{time}}",tb(o,t))},GM={p:tb,P:KM},JM=/^D+$/,QM=/^Y+$/,ZM=["D","DD","YY","YYYY"];function eP(e){return JM.test(e)}function tP(e){return QM.test(e)}function sP(e,t,s){const n=nP(e,t,s);if(console.warn(n),ZM.includes(e))throw new RangeError(n)}function nP(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 rP=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,oP=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,aP=/^'([^]*?)'?$/,iP=/''/g,lP=/[a-zA-Z]/;function cP(e,t,s){var d,h,p,f;const n=Ki(),o=n.locale??qM,a=n.firstWeekContainsDate??((h=(d=n.locale)==null?void 0:d.options)==null?void 0:h.firstWeekContainsDate)??1,i=n.weekStartsOn??((f=(p=n.locale)==null?void 0:p.options)==null?void 0:f.weekStartsOn)??0,l=_s(e,s==null?void 0:s.in);if(!dM(l))throw new RangeError("Invalid time value");let c=t.match(oP).map(y=>{const g=y[0];if(g==="p"||g==="P"){const S=GM[g];return S(y,o.formatLong)}return y}).join("").match(rP).map(y=>{if(y==="''")return{isToken:!1,value:"'"};const g=y[0];if(g==="'")return{isToken:!1,value:dP(y)};if(Rh[g])return{isToken:!0,value:y};if(g.match(lP))throw new RangeError("Format string contains an unescaped latin alphabet character `"+g+"`");return{isToken:!1,value:y}});o.localize.preprocessor&&(c=o.localize.preprocessor(l,c));const u={firstWeekContainsDate:a,weekStartsOn:i,locale:o};return c.map(y=>{if(!y.isToken)return y.value;const g=y.value;(tP(g)||eP(g))&&sP(g,t,String(e));const S=Rh[g[0]];return S(l,g,o.localize,u)}).join("")}function dP(e){const t=e.match(aP);return t?t[1].replace(iP,"'"):e}const{useToken:uP}=xe,{Text:Ua}=pe,mP=({images:e,className:t,style:s,maxHeight:n={single:400,multiple:200}})=>{const{token:o}=uP(),{t:a}=ie();return!e||e.length===0?null:r.jsx(te,{className:t,style:{marginBottom:o.marginMD,...s},styles:{body:{padding:0}},variant:"borderless",children:r.jsx(V,{wrap:"wrap",gap:o.marginSM,style:{width:"100%"},children:e.map(i=>r.jsxs(te,{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(Ax,{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(V,{align:"center",justify:"center",gap:o.marginXS,style:{color:o.colorTextLightSolid},children:[r.jsx(sd,{}),r.jsx(Ua,{style:{color:o.colorTextLightSolid},children:a("components.imageGrid.preview")})]})}}),r.jsxs(V,{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(ws,{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(pe.Paragraph,{style:{marginTop:i.ocrError?o.marginXS:0,marginBottom:0,whiteSpace:"pre-wrap"},children:i.ocrText})]})}]})})]},i.id))})})},{useToken:hP}=xe,{useBreakpoint:pP}=$i,fP=({buttons:e,isVisible:t,className:s,style:n,position:o={bottom:"8px",right:"8px"}})=>{const{token:a}=hP(),i=pP(),l=()=>(i.xs,"small");return r.jsx(V,{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(Re,{title:c.title,children:r.jsx(B,{"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))})},gP=(e,t)=>({key:"copy","data-testid":"copy-message",icon:r.jsx(cs,{}),title:t||"Copy message",onClick:e}),yP=(e,t)=>({key:"reference",icon:r.jsx(Tf,{}),title:t||"Reference message",onClick:e}),{Title:Dh,Text:Zt,Paragraph:Lh}=pe,{useToken:bP}=xe,xP=({plan:e,contextId:t,onExecute:s,onRefine:n,timestamp:o})=>{const{t:a}=ie(),{token:i}=bP(),[l,c]=m.useState(!1),[u,d]=m.useState(""),h=()=>{u.trim()&&(n(u),d(""),c(!1))};return r.jsxs(te,{style:{marginBottom:i.marginMD,borderColor:i.colorPrimary,borderWidth:2,backgroundColor:i.colorPrimaryBg},title:r.jsxs(U,{children:[r.jsx(Js,{style:{color:i.colorPrimary}}),r.jsx(Zt,{strong:!0,style:{color:i.colorPrimary},children:a("components.plan.executionPlan")})]}),extra:o?r.jsx(Zt,{type:"secondary",style:{fontSize:i.fontSizeSM},children:o}):void 0,children:[r.jsxs(V,{vertical:!0,style:{marginBottom:i.marginLG},children:[r.jsx(Dh,{level:5,style:{marginBottom:i.marginXS},children:a("components.plan.goal")}),r.jsx(Lh,{style:{fontSize:15,marginBottom:0},children:e.goal})]}),r.jsxs(V,{vertical:!0,style:{marginBottom:i.marginLG},children:[r.jsx(Dh,{level:5,style:{marginBottom:i.marginMD},children:a("components.plan.steps")}),r.jsx(Ix,{direction:"vertical",current:-1,items:e.steps.map(p=>({title:r.jsxs(Zt,{strong:!0,children:[a("components.plan.stepTitle",{number:p.step_number}),": ",p.action]}),description:r.jsxs(V,{vertical:!0,children:[r.jsxs(Lh,{style:{marginBottom:i.marginXS},children:[r.jsxs(Zt,{type:"secondary",children:[a("components.plan.reason"),":"]})," ",p.reason]}),r.jsxs(U,{wrap:!0,children:[r.jsxs(Zt,{type:"secondary",children:[r.jsx(Tr,{})," ",a("components.plan.tools"),":"]}),p.tools_needed.map((f,y)=>r.jsx(ue,{color:"processing",children:f},y))]}),r.jsx(V,{style:{marginTop:i.marginXS},children:r.jsxs(Zt,{type:"secondary",children:[r.jsx(Qs,{})," ",a("components.plan.estimated"),": ",p.estimated_time]})})]}),icon:r.jsx(Zt,{children:p.step_number})}))})]}),r.jsxs(U,{direction:"vertical",style:{width:"100%",marginBottom:i.marginLG},children:[r.jsxs(V,{align:"center",gap:i.marginXS,wrap:"wrap",children:[r.jsxs(Zt,{type:"secondary",children:[r.jsx(Qs,{})," ",a("components.plan.totalEstimatedTime")," "]}),r.jsx(ue,{color:"processing",children:e.estimated_total_time})]}),e.prerequisites&&e.prerequisites.length>0&&r.jsxs(V,{vertical:!0,children:[r.jsxs(Zt,{type:"secondary",children:[a("components.plan.prerequisites"),":"]}),r.jsx(lt,{size:"small",dataSource:e.prerequisites,renderItem:(p,f)=>r.jsx(lt.Item,{style:{padding:0},children:r.jsx(Zt,{children:p})},`${p}-${f}`)})]})]}),e.risks&&e.risks.length>0&&r.jsx(ws,{ghost:!0,style:{marginBottom:i.marginLG},items:[{key:"risks",label:r.jsxs(U,{children:[r.jsx(ua,{style:{color:i.colorWarning}}),r.jsx(Zt,{strong:!0,children:a("components.plan.potentialRisks",{count:e.risks.length})})]}),children:r.jsx(lt,{size:"small",dataSource:e.risks,renderItem:(p,f)=>r.jsx(lt.Item,{style:{padding:0},children:r.jsx(Zt,{children:p})},`${p}-${f}`)})}]}),r.jsx(U,{style:{width:"100%",justifyContent:"flex-end"},children:l?r.jsxs(r.Fragment,{children:[r.jsx(B,{onClick:()=>c(!1),children:a("common.cancel")}),r.jsx(B,{type:"primary",onClick:h,disabled:!u.trim(),children:a("components.plan.sendFeedback")})]}):r.jsxs(r.Fragment,{children:[r.jsx(B,{onClick:()=>c(!0),children:a("components.plan.refinePlan")}),r.jsx(B,{type:"primary",icon:r.jsx(kf,{}),onClick:s,children:a("components.plan.executePlan")})]})}),l&&r.jsx(V,{vertical:!0,style:{marginTop:i.marginMD},children:r.jsx(be.TextArea,{value:u,onChange:p=>d(p.target.value),placeholder:a("components.plan.feedbackPlaceholder"),autoSize:{minRows:4,maxRows:10}})})]})},sb=m.memo(xP);sb.displayName="PlanMessageCard";const{Title:SP,Text:ir,Paragraph:vP}=pe,{useToken:wP}=xe,_P=({question:e,contextId:t,onAnswer:s,disabled:n=!1,timestamp:o})=>{const{t:a}=ie(),{token:i}=wP(),[l,c]=m.useState(e.default),[u,d]=m.useState(!1),h=async()=>{if(l){d(!0);try{await s(l)}catch(g){console.error("Failed to submit answer:",g)}finally{d(!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(Ft,{style:{color:i.colorInfo}});default:return r.jsx(rd,{style:{color:i.colorPrimary}})}},f=()=>{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(te,{style:{marginBottom:i.marginMD,borderColor:y(),borderWidth:2,backgroundColor:f()},title:r.jsxs(U,{children:[p(),r.jsx(ir,{strong:!0,style:{color:y()},children:a("components.question.agentQuestion")}),r.jsxs(ir,{type:"secondary",style:{fontSize:12},children:["(",e.severity,")"]})]}),extra:o?r.jsx(ir,{type:"secondary",style:{fontSize:i.fontSizeSM},children:o}):void 0,children:[r.jsx(V,{vertical:!0,style:{marginBottom:i.marginLG},children:r.jsx(SP,{level:5,style:{marginBottom:i.marginXS},children:e.question})}),e.context&&r.jsx(tt,{message:a("components.question.context"),description:e.context,type:"info",showIcon:!0,style:{marginBottom:i.marginLG}}),r.jsxs(V,{vertical:!0,style:{marginBottom:i.marginLG},children:[r.jsx(ir,{strong:!0,style:{display:"block",marginBottom:i.marginSM},children:a("components.question.chooseOption")}),r.jsx(ls.Group,{value:l,onChange:g=>c(g.target.value),disabled:n||u,style:{width:"100%"},children:r.jsx(U,{direction:"vertical",style:{width:"100%"},children:e.options.map(g=>r.jsx(te,{size:"small",hoverable:!n&&!u,style:{borderColor:l===g.value?i.colorPrimary:i.colorBorder,backgroundColor:l===g.value?i.colorPrimaryBg:i.colorBgContainer,cursor:n||u?"not-allowed":"pointer"},onClick:()=>!n&&!u&&c(g.value),children:r.jsx(ls,{value:g.value,style:{width:"100%"},children:r.jsxs(V,{vertical:!0,children:[r.jsxs(V,{align:"center",gap:i.marginXS,wrap:"wrap",children:[r.jsx(ir,{strong:!0,children:g.label}),g.value===e.default&&r.jsx(ue,{color:"processing",style:{marginLeft:i.marginXS},children:a("components.question.recommended")})]}),r.jsx(vP,{type:"secondary",style:{marginTop:i.marginXXS,marginBottom:0},children:g.description})]})})},g.value))})})]}),e.allow_custom&&r.jsxs(V,{vertical:!0,style:{marginBottom:i.marginMD},children:[r.jsx(ir,{type:"secondary",style:{fontSize:12},children:a("components.question.customAnswerHint")}),r.jsx(be.TextArea,{value:l&&!e.options.find(g=>g.value===l)?l:"",onChange:g=>c(g.target.value),placeholder:a("components.question.customAnswerPlaceholder"),disabled:n||u,autoSize:{minRows:3,maxRows:8},style:{marginTop:i.marginXS}})]}),r.jsx(V,{justify:"flex-end",children:r.jsx(B,{type:"primary",icon:r.jsx(Js,{}),onClick:h,loading:u,disabled:n||!l,children:a("components.question.submitAnswer")})})]})},nb=m.memo(_P);nb.displayName="QuestionMessageCard";const{Text:Oh}=pe,TP=({paths:e,displayText:t})=>{const{token:s}=xe.useToken(),n=t.replace(/@[^\s]+/g,"").trim();return r.jsxs(te,{size:"small",styles:{body:{padding:`${s.paddingSM}px ${s.paddingMD}px`}},style:{maxWidth:"100%"},children:[r.jsx(U,{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(V,{vertical:!0,children:[r.jsxs(U,{size:s.marginXS,align:"center",wrap:!0,children:[c?r.jsx(hi,{style:{color:s.colorWarning,fontSize:s.fontSizeLG}}):r.jsx(vr,{style:{color:s.colorPrimary,fontSize:s.fontSizeLG}}),r.jsx(ue,{color:c?"warning":"processing",style:{margin:0,fontFamily:s.fontFamilyCode,fontSize:s.fontSize},children:i})]}),l&&r.jsx(Re,{title:o,children:r.jsxs(U,{size:4,align:"center",style:{marginTop:4},children:[r.jsx(hi,{style:{color:s.colorTextTertiary,fontSize:s.fontSizeSM}}),r.jsx(Oh,{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(Oh,{style:{fontSize:s.fontSize,color:s.colorText,marginTop:s.marginXS,paddingTop:s.marginXS,borderTop:`1px solid ${s.colorBorderSecondary}`},children:n})]})},rb=m.memo(TP);rb.displayName="FileReferenceCard";const kP=({taskList:e})=>{const{token:t}=xe.useToken(),{Text:s}=pe,n=l=>{switch(l){case"pending":return r.jsx(ue,{icon:r.jsx(Qs,{}),color:"default",children:"Pending"});case"in_progress":return r.jsx(ue,{icon:r.jsx(xr,{spin:!0}),color:"processing",children:"In Progress"});case"completed":return r.jsx(ue,{icon:r.jsx(Js,{}),color:"success",children:"Completed"});case"skipped":return r.jsx(ue,{icon:r.jsx(nc,{}),color:"default",children:"Skipped"});case"failed":return r.jsx(ue,{icon:r.jsx(rc,{}),color:"error",children:"Failed"});default:return null}},o=()=>{switch(e.status){case"active":return r.jsx(ue,{color:"processing",children:"Active"});case"completed":return r.jsx(ue,{color:"success",children:"Completed"});case"abandoned":return r.jsx(ue,{color:"error",children:"Abandoned"});default:return null}},a=xt.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=xt.useMemo(()=>e.items.find(l=>l.status==="in_progress"),[e.items]);return r.jsx(te,{size:"small",styles:{body:{padding:t.paddingSM}},style:{borderRadius:t.borderRadiusLG},children:r.jsxs(V,{vertical:!0,gap:t.marginSM,children:[r.jsxs(V,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[r.jsxs(U,{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(U,{direction:"vertical",size:4,children:[r.jsx(ld,{percent:a,status:e.status==="completed"?"success":e.status==="abandoned"?"exception":"active",showInfo:!0}),r.jsxs(s,{type:"secondary",children:[a,"% Complete"]})]}),r.jsx(lt,{size:"small",dataSource:e.items,renderItem:l=>{var u;const c=(i==null?void 0:i.id)===l.id;return r.jsx(lt.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(V,{vertical:!0,style:{width:"100%"},gap:4,children:[r.jsxs(V,{align:"center",justify:"space-between",wrap:"wrap",gap:8,children:[r.jsx(s,{children:l.description}),n(l.status)]}),l.status==="failed"&&((u=l.metadata)!=null&&u.error)?r.jsx(s,{type:"danger",style:{fontSize:12},children:l.metadata.error}):null,l.status==="completed"&&l.summary?r.jsx(s,{type:"success",style:{fontSize:12},children:l.summary}):null]})})}}),r.jsxs(V,{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]})]})})},jP=100,En=new Set;function CP(e){if(En.has(e)&&En.delete(e),En.add(e),En.size>jP){const t=En.values().next().value;t&&En.delete(t)}}function MP(e){let t=2166136261;for(let s=0;s<e.length;s++)t=(t^e.charCodeAt(s))*16777619;return(t>>>0).toString(36)}const PP=e=>{const{t}=ie(),s=MP(e.chart),[n,o]=m.useState(()=>En.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(u=>u.isIntersecting)&&(CP(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(xt.Suspense,{fallback:r.jsx(Ss,{size:"small",tip:t("components.mermaid.loadingDiagram")}),children:r.jsx(EP,{...e})}):r.jsx("div",{style:{minHeight:"200px"}})})},EP=e=>{const{t}=ie(),[s,n]=m.useState(null);return m.useEffect(()=>{let o=!1;return Dt(()=>Promise.resolve().then(()=>n1),void 0,import.meta.url).then(a=>{o||n(()=>a.MermaidChart)}),()=>{o=!0}},[]),s?r.jsx(s,{...e}):r.jsx(Ss,{size:"small",tip:t("components.mermaid.loadingDiagram")})},RP=xt.memo(PP),AP=({error:e,className:t,style:s,token:n,onFix:o,isFixing:a,fixError:i})=>{const{t:l}=ie(),c=e.split(`
@@ -219,7 +219,7 @@ ${o}`:`${n}
219
219
  ${t}`},m1=(e,t)=>{const s=l1[e];if(!s)return null;const n=t.trim();if(!n)return"";if(e==="mermaid")return n;const o=d1(n);return c1.test(o)?n:u1(n,s)},wb=(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=m1(a,t);if(i!==null){const l=i.trim();return l?o==="eager"?r.jsx(Ri,{chart:l,onFix:n}):r.jsx(RP,{chart:l,onFix:n}):(console.warn("Empty Mermaid chart content"),null)}return r.jsx(a1,{language:a,codeString:t,token:s})}catch(a){return console.warn("Syntax highlighting failed:",a),r.jsx(i1,{codeString:t,token:s})}},Yh=(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)},_b=async e=>{const t=e.trim();if(!t)return;if(xb()){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)}Yh(t,{allowLocationFallback:!1});return}Yh(t)},{Text:Xh}=pe,Tb=(e,t)=>({p:({children:s})=>r.jsx(Xh,{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),u=n?String(n).replace(/\n$/,""):"";return c?r.jsx(Xh,{code:!0,className:s,...a,children:n}):u.trim()?wb(l,u,e,t==null?void 0:t.onFixMermaid,t==null?void 0:t.mermaidRenderMode):null},blockquote:({children:s})=>r.jsx(te,{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(),_b(o)},style:{color:e.colorLink,textDecoration:"underline",overflowWrap:"anywhere"},children:s}):r.jsx(r.Fragment,{children:s})},table:({children:s})=>r.jsx(te,{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:Ue}=pe,Vh=e=>{if(!e)return;const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},h1=({content:e,toolName:t,status:s="success",timestamp:n,defaultCollapsed:o=!0,isLoading:a,errorMessage:i})=>{var v;const{t:l}=ie(),{token:c}=xe.useToken(),u=m.useMemo(()=>Fc(e),[e]),d=m.useMemo(()=>typeof a=="boolean"?a:u.formattedText.trim().length===0,[u.formattedText,a]),h=m.useMemo(()=>W0(u.formattedText),[u.formattedText]),p=m.useMemo(()=>wa(e),[e]),f=m.useMemo(()=>Ly(e),[e]),y=m.useMemo(()=>p?Oy(p.diff.unified):[],[p]),g=async()=>{try{const x=u.isJson?wr(u.parsedJson):u.formattedText;await us(x)}catch(x){console.error("[ToolResultCard] Failed to copy result:",x)}},S=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(ws,{defaultActiveKey:o?[]:[S],style:{backgroundColor:c.colorBgContainer,borderColor:c.colorBorderSecondary,borderWidth:1,borderStyle:"solid",borderRadius:c.borderRadiusLG},items:[{key:S,label:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:c.marginSM,width:"100%"},children:[r.jsx(id,{style:{color:c.colorPrimary,flexShrink:0}}),r.jsx(Ue,{strong:!0,style:{color:c.colorText,flexShrink:0},children:t}),r.jsx(Ue,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:c.fontSizeSM},children:d?l("components.toolResult.waiting"):h}),r.jsx(ue,{color:Fy(s),style:{flexShrink:0,margin:0},children:s})]}),children:r.jsxs(U,{direction:"vertical",style:{width:"100%"},size:c.marginSM,children:[n&&r.jsx(Ue,{type:"secondary",style:{fontSize:c.fontSizeSM},children:new Date(n).toLocaleString()}),i&&r.jsx(tt,{type:"error",message:l("components.toolResult.executionFailed"),description:i,showIcon:!0}),r.jsxs("div",{style:{position:"relative"},children:[r.jsx(Re,{title:l("components.toolResult.copyResult"),children:r.jsx(B,{type:"text",size:"small",icon:r.jsx(cs,{}),"aria-label":l("components.toolResult.copyResult"),onClick:x=>{x.stopPropagation(),g()},style:{position:"absolute",top:8,right:8,zIndex:1}})}),d?r.jsx(Ue,{type:"secondary",children:l("components.toolResult.waitingForResult")}):f?r.jsxs(U,{direction:"vertical",style:{width:"100%"},size:10,children:[r.jsxs(U,{wrap:!0,children:[r.jsx(ue,{color:f.action==="rebuild"?"gold":"blue",children:l(`components.toolResult.memory.action.${f.action}`)}),r.jsx(ue,{children:f.data.scope}),f.data.project_key?r.jsx(ue,{children:f.data.project_key}):null,r.jsx(ue,{color:"green",children:l("components.toolResult.memory.totalMemories",{count:f.data.total_memories})}),r.jsx(ue,{color:f.data.stale_candidate_count>0?"orange":"default",children:l("components.toolResult.memory.staleCandidates",{count:f.data.stale_candidate_count})})]}),r.jsxs("div",{children:[r.jsx(Ue,{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(f.data.by_type).map(([x,T])=>r.jsx(ue,{children:`${x}: ${T}`},`type-${x}`)),Object.entries(f.data.by_status).map(([x,T])=>r.jsx(ue,{color:"processing",children:`${x}: ${T}`},`status-${x}`))]})]}),r.jsx($t,{style:{margin:`${c.marginXS}px 0`}}),r.jsxs("div",{style:{display:"grid",gap:c.marginXS},children:[r.jsxs(Ue,{style:{fontSize:c.fontSizeSM},children:[r.jsx(Ue,{strong:!0,children:l("components.toolResult.memory.viewsLabel")})," ",f.data.view_files.length]}),r.jsxs(Ue,{style:{fontSize:c.fontSizeSM},children:[r.jsx(Ue,{strong:!0,children:l("components.toolResult.memory.indexesLabel")})," ",f.data.index_files.length]}),r.jsxs(Ue,{style:{fontSize:c.fontSizeSM},children:[r.jsx(Ue,{strong:!0,children:l("components.toolResult.memory.stateFilesLabel")})," ",f.data.state_files.length]}),f.data.last_reindex_at?r.jsxs(Ue,{style:{fontSize:c.fontSizeSM},children:[r.jsx(Ue,{strong:!0,children:l("components.toolResult.memory.lastReindexLabel")})," ",Vh(f.data.last_reindex_at)]}):null,f.data.last_dream_at?r.jsxs(Ue,{style:{fontSize:c.fontSizeSM},children:[r.jsx(Ue,{strong:!0,children:l("components.toolResult.memory.lastDreamLabel")})," ",Vh(f.data.last_dream_at)]}):null]}),f.data.view_files.length>0?r.jsxs("div",{children:[r.jsx(Ue,{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:f.data.view_files.map(x=>r.jsx(ue,{children:x},`view-${x}`))})]}):null,f.data.index_files.length>0?r.jsxs("div",{children:[r.jsx(Ue,{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:f.data.index_files.map(x=>r.jsx(ue,{children:x},`index-${x}`))})]}):null,f.data.state_files.length>0?r.jsxs("div",{children:[r.jsx(Ue,{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:f.data.state_files.map(x=>r.jsx(ue,{children:x},`state-${x}`))})]}):null,f.data.topic_paths.length>0?r.jsxs("div",{children:[r.jsx(Ue,{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:f.data.topic_paths.map(x=>r.jsx(ue,{children:x},`topic-${x}`))})]}):null,f.data.recent_ids.length>0?r.jsxs("div",{children:[r.jsx(Ue,{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:f.data.recent_ids.map(x=>r.jsx(ue,{color:"default",children:x},`recent-${x}`))})]}):null]}):p?r.jsxs(U,{direction:"vertical",style:{width:"100%"},size:8,children:[p.message&&r.jsx(Ue,{style:{fontSize:c.fontSizeSM},children:p.message}),r.jsxs(Ue,{style:{fontSize:c.fontSizeSM},children:[r.jsxs(Ue,{strong:!0,children:[l("common.file"),":"]})," ",r.jsx(Ue,{code:!0,children:p.file_path})]}),p.workspace&&r.jsxs(Ue,{style:{fontSize:c.fontSizeSM},children:[r.jsxs(Ue,{strong:!0,children:[l("common.workspace"),":"]})," ",r.jsx(Ue,{code:!0,children:p.workspace})]}),(v=p.checkpoint)!=null&&v.created?r.jsxs(Ue,{style:{fontSize:c.fontSizeSM},children:[r.jsxs(Ue,{strong:!0,children:[l("components.toolResult.checkpoint"),":"]})," ",r.jsx(Ue,{code:!0,children:p.checkpoint.path})]}):r.jsx(Ue,{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,T)=>{const _={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"?_.background=c.colorSuccessBg:x.kind==="remove"?_.background=c.colorErrorBg:x.kind==="modified_add"?(_.background=c.colorWarningBg,_.borderLeft=`3px solid ${c.colorSuccess}`):x.kind==="modified_remove"?(_.background=c.colorWarningBg,_.borderLeft=`3px solid ${c.colorError}`):x.kind==="hunk"?(_.background=c.colorFillSecondary,_.color=c.colorTextSecondary):x.kind==="meta"&&(_.background=c.colorFillTertiary,_.color=c.colorTextSecondary),r.jsx("pre",{style:_,children:x.text||" "},`${T}-${x.kind}`)})}),p.diff.truncated&&r.jsx(Ue,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l("components.toolResult.diffTruncated")})]}):u.isJson?r.jsx(br,{language:"json",style:Xn,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:u.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:u.formattedText})]})]})}]})},su=m.memo(h1);su.displayName="ToolResultCard";const{Text:Rs}=pe;function p1(e,t){const s=Gn(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 f1=({toolName:e,parameters:t,toolCallId:s,streamingOutput:n,defaultExpanded:o=!1,metadata:a})=>{const{t:i}=ie(),{token:l}=xe.useToken(),c=m.useMemo(()=>Gn(e),[e]),[u,d]=m.useState(o?[s]:[]),h=m.useRef(!1),p=m.useRef(null);m.useEffect(()=>{h.current||!n||n.trim().length===0||(d(v=>v.includes(s)?v:[s]),h.current=!0)},[n,s]),m.useEffect(()=>{if(!n||n.trim().length===0||!u.includes(s))return;const v=p.current;v&&(v.scrollTop=v.scrollHeight)},[n,u,s]);const f=m.useMemo(()=>p1(e,t),[e,t]),y=m.useMemo(()=>wr(t,2),[t]),g=async()=>{try{await us(y)}catch(v){console.error("[ToolCallCard] Failed to copy parameters:",v)}},S=m.useMemo(()=>{const v=["path","file_path","command","pattern","query","limit"];return Object.entries(t).sort((_,j)=>{const P=v.indexOf(_[0]),M=v.indexOf(j[0]);return P!==-1&&M!==-1?P-M:P!==-1?-1:M!==-1?1:0}).slice(0,3)},[t]);return r.jsx(ws,{activeKey:u,onChange:v=>{const x=Array.isArray(v)?v.map(String):v==null?[]:[String(v)];d(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(Tr,{style:{color:l.colorPrimary,flexShrink:0}})}),c?r.jsxs(U,{size:"small",wrap:!1,children:[r.jsx(ue,{color:"purple",style:{marginInlineEnd:0,borderRadius:999,paddingInline:8,fontWeight:700,boxShadow:"var(--lotus-purple-shadow)"},children:"MCP"}),r.jsx(Rs,{strong:!0,style:{color:l.colorText},children:c.toolName}),r.jsx(Rs,{type:"secondary",style:{fontSize:l.fontSizeSM},children:r.jsx(Rs,{code:!0,style:{fontSize:l.fontSizeSM},children:c.serverId})})]}):r.jsx(Rs,{strong:!0,style:{color:l.colorText,flexShrink:0},children:e}),r.jsx(Rs,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:l.fontSizeSM},children:f}),(a==null?void 0:a.elapsed_ms)!=null&&r.jsx(Re,{title:a.is_mutating?"Mutating tool":"Read-only tool",children:r.jsx(ue,{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(U,{direction:"vertical",style:{width:"100%"},size:l.marginSM,children:[n&&n.trim().length>0&&r.jsxs("div",{children:[r.jsx(Rs,{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(br,{language:"text",style:Xn,wrapLongLines:!0,customStyle:{margin:0,backgroundColor:"transparent",fontSize:l.fontSizeSM},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"}},children:n})})]}),S.length>0&&r.jsxs("div",{children:[r.jsx(Rs,{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:S.map(([v,x])=>r.jsxs("li",{children:[r.jsx(Rs,{code:!0,style:{fontSize:l.fontSizeSM},children:v}),r.jsxs(Rs,{style:{fontSize:l.fontSizeSM},children:[": ",typeof x=="string"?x:JSON.stringify(x)]})]},v))})]}),r.jsxs("div",{children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:l.marginXS},children:[r.jsx(Rs,{strong:!0,style:{fontSize:l.fontSizeSM},children:i("components.toolCall.fullParameters")}),r.jsx(Re,{title:i("components.toolCall.copyParameters"),children:r.jsx(B,{type:"text",size:"small",icon:r.jsx(cs,{}),"aria-label":i("components.toolCall.copyParameters"),onClick:v=>{v.stopPropagation(),g()}})})]}),r.jsx(br,{language:"json",style:Xn,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})]})]})}]})},nu=m.memo(f1);nu.displayName="ToolCallCard";const{Text:Dl}=pe,g1=({content:e,workflowName:t,parameters:s,status:n="success",timestamp:o,onRetry:a,isLoading:i,errorMessage:l})=>{const{t:c}=ie(),{token:u}=xe.useToken(),[d,h]=m.useState(!1),p=m.useMemo(()=>Fc(e),[e]),f=m.useMemo(()=>typeof i=="boolean"?i:p.formattedText.trim().length===0,[p.formattedText,i]),y=m.useMemo(()=>N0(p.formattedText),[p.formattedText]),g=p.isJson||y,S=!g||d,v=m.useMemo(()=>B0(p.formattedText),[p.formattedText]),x=m.useMemo(()=>{if(s==null)return null;if(typeof s=="string")return Fc(s);try{return{isJson:!0,formattedText:JSON.stringify(s,null,2),parsedJson:s}}catch(j){return console.error("[WorkflowResultCard] Failed to stringify parameters:",j),{isJson:!1,formattedText:String(s)}}},[s]),T=async()=>{try{const j=p.isJson?wr(p.parsedJson):p.formattedText;await us(j)}catch(j){console.error("[WorkflowResultCard] Failed to copy content:",j)}},_=async()=>{if(x)try{const j=x.isJson?wr(x.parsedJson):x.formattedText;await us(j)}catch(j){console.error("[WorkflowResultCard] Failed to copy parameters:",j)}};return r.jsx(te,{size:"small",variant:"outlined",style:{borderRadius:u.borderRadiusLG,borderColor:u.colorBorderSecondary,backgroundColor:u.colorBgContainer},styles:{body:{padding:u.paddingMD}},children:r.jsxs(U,{direction:"vertical",style:{width:"100%"},size:u.marginSM,children:[r.jsxs(V,{align:"center",justify:"space-between",children:[r.jsxs(U,{size:u.marginXS,align:"center",children:[r.jsx($x,{style:{color:u.colorWarning}}),r.jsx(Dl,{strong:!0,children:c("components.workflowResult.userWorkflow")}),r.jsx(ue,{color:u.colorWarning,children:t}),r.jsx(ue,{color:Fy(n),children:n})]}),r.jsxs(U,{size:"small",children:[r.jsx(Re,{title:c(d?"components.workflowResult.collapseResult":"components.workflowResult.expandResult"),children:g&&r.jsx(B,{type:"text",size:"small",icon:d?r.jsx(Dx,{}):r.jsx(Lx,{}),onClick:()=>h(j=>!j)})}),r.jsx(Re,{title:c("components.workflowResult.copyResult"),children:r.jsx(B,{type:"text",size:"small",icon:r.jsx(cs,{}),onClick:T,"aria-label":c("components.workflowResult.copyContent")})}),a&&r.jsx(Re,{title:c("components.workflowResult.retryWorkflow"),children:r.jsx(B,{type:"text",size:"small",icon:r.jsx(Zs,{}),onClick:a,"aria-label":c("components.workflowResult.retryWorkflow")})})]})]}),o&&r.jsx(Dl,{type:"secondary",style:{fontSize:u.fontSizeSM},children:new Date(o).toLocaleString()}),r.jsx($t,{style:{margin:`${u.marginXS}px 0`}}),l&&r.jsx(tt,{type:"error",message:c("components.workflowResult.executionFailed"),description:l,showIcon:!0,style:{marginBottom:u.marginXS}}),r.jsx(V,{vertical:!0,style:{width:"100%"},children:f?r.jsx(Ss,{tip:c("components.workflowResult.waitingForResult")}):p.isJson?r.jsx(br,{language:"json",style:Xn,wrapLongLines:!0,customStyle:{margin:0,borderRadius:u.borderRadiusSM,backgroundColor:u.colorBgContainer,fontSize:u.fontSizeSM,maxHeight:S?"none":280,overflow:S?"auto":"hidden"},children:p.formattedText}):r.jsxs("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:u.fontSizeSM,maxHeight:S?"none":280,overflow:S?"visible":"hidden",marginBottom:0},children:[S?p.formattedText:v.preview,!S&&v.isTruncated&&`
220
220
  …`]})}),x&&r.jsxs(V,{vertical:!0,style:{width:"100%"},children:[r.jsx($t,{style:{margin:`${u.marginXS}px 0`},children:r.jsxs(U,{size:"small",children:[r.jsx(Dl,{strong:!0,children:c("common.parameters")}),r.jsx(Re,{title:c("components.workflowResult.copyParameters"),children:r.jsx(B,{type:"text",size:"small",icon:r.jsx(cs,{}),onClick:_,"aria-label":c("components.workflowResult.copyParameters")})})]})}),x.isJson?r.jsx(br,{language:"json",style:Xn,wrapLongLines:!0,customStyle:{margin:0,borderRadius:u.borderRadiusSM,backgroundColor:u.colorBgContainer,fontSize:u.fontSizeSM,maxHeight:220,overflow:"auto"},children:x.formattedText}):r.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:u.fontSizeSM,marginBottom:0},children:x.formattedText})]})]})})},kb=m.memo(g1);kb.displayName="WorkflowResultCard";const{Text:Ll}=pe,y1=({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:o,conclusionMarkdown:a,markdownComponents:i,markdownPlugins:l,rehypePlugins:c})=>{const{t:u}=ie(),[d,h]=m.useState(null),p=m.useMemo(()=>Ka({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:o}),[e,t,s,n,o]),f=d===p,y=L(S=>S.setPendingQuestionRespond),g=L(S=>S.clearPendingQuestionRespondForSession);return m.useEffect(()=>{if(typeof window>"u")return;const S=v=>{var _;const T=((_=v.detail)==null?void 0:_.sessionId)??null;!e||T!==e||(h(p),g(e))};return window.addEventListener(yr,S),()=>{window.removeEventListener(yr,S)}},[e,p,g]),m.useEffect(()=>{!e||f||y({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:o??null})},[e,f,p,t,s,n,o,y]),m.useEffect(()=>()=>{e&&g(e)},[e,g]),r.jsxs(U,{direction:"vertical",size:"middle",style:{width:"100%"},children:[a?r.jsx(xs,{remarkPlugins:l,rehypePlugins:c,components:i,children:a}):null,r.jsxs("div",{children:[r.jsx(Ll,{strong:!0,children:u("components.questionDialog.questionLabel","Question")}),r.jsx("div",{style:{marginTop:8},children:r.jsx(xs,{remarkPlugins:l,rehypePlugins:c,components:i,children:t})})]}),f?r.jsx(Ll,{type:"secondary",children:u("components.questionDialog.responseSubmittedContinue","Response submitted. Continuing...")}):r.jsx(Ll,{type:"secondary",children:n?u("components.questionDialog.responseInInputHint","Use the options or input box below to respond."):u("components.questionDialog.responseByOptionHint","Please respond using the options below the input box.")})]})},{Text:fs}=pe,b1=e=>{var a;if(!e)return{cleanText:e,hints:[]};const t=e.split(`
221
221
  `),s=[],n=[];for(const i of t){const l=i.trim(),c=l.match(/^\[User explicitly selected MCP tool:\s*(.+?)\s*\]$/);if(c){const d=c[1]??"",h=Gn(d);s.push({type:"mcp",label:d,serverId:h==null?void 0:h.serverId,toolName:h==null?void 0:h.toolName});continue}const u=l.match(/^\[User explicitly selected skill:\s*(.+?)\s*\]$/);if(u){const d=u[1]??"",h=d.match(/\(ID:\s*([^)]+)\)\s*$/i),p=(a=h==null?void 0:h[1])==null?void 0:a.trim(),f=h?d.replace(/\(ID:\s*([^)]+)\)\s*$/i,"").trim():d;s.push({type:"skill",label:f||d,skillId:p});continue}n.push(i)}return{cleanText:n.join(`
222
- `).trimStart(),hints:s}},x1=({sessionId:e,message:t,messageText:s,isUserToolCall:n,formatUserToolCall:o,markdownComponents:a,markdownPlugins:i,rehypePlugins:l})=>{var y;const{t:c}=ie(),u=g=>(g??"").trim().toLowerCase()==="conclusion";if(qy(t)){const g=t.result.result??"",S=t.isError?g||c("components.toolResult.executionFailed"):void 0,v=!S&&g.trim().length===0;if(t.result.display_preference==="Hidden")return null;const x=(t.toolName??"").trim().toLowerCase(),T=x==="conclusion",_=O0(g),j=(x==="conclusion_with_options"||x==="exitplanmode"||x==="request_permissions")&&!t.isError&&_,P=x==="conclusion"?Dy(g):null;return j&&_?r.jsx(y1,{sessionId:e,question:_.question,options:_.options,allowCustom:_.allow_custom,toolCallId:t.toolCallId,conclusionMarkdown:F0(_.conclusion),markdownComponents:a,markdownPlugins:i,rehypePlugins:l}):P?r.jsx(U,{direction:"vertical",style:{width:"100%"},size:"small",children:r.jsx(xs,{remarkPlugins:i,rehypePlugins:l,components:a,children:P})}):r.jsx(su,{content:g,toolName:t.toolName,status:t.isError?"error":v?"warning":"success",timestamp:t.createdAt,defaultCollapsed:!T,isLoading:v,errorMessage:S})}if(Xk(t)){const g=t.content??"",S=t.status==="error"?g||c("components.workflowResult.executionFailed"):void 0,v=!S&&g.trim().length===0;return r.jsx(kb,{content:g,workflowName:t.workflowName,parameters:t.parameters,status:v?"warning":t.status??"success",timestamp:t.createdAt,isLoading:v,errorMessage:S})}if(Yk(t)){const g=t.toolCalls.filter(S=>!u(S.toolName));return g.length===0?null:r.jsx(U,{direction:"vertical",style:{width:"100%"},children:g.map(S=>r.jsx(nu,{toolName:S.toolName,parameters:S.parameters,toolCallId:S.toolCallId,streamingOutput:S.streamingOutput,defaultExpanded:!1,metadata:t.metadata},S.toolCallId))})}if(t.isAuthError)return r.jsxs(U,{direction:"vertical",style:{width:"100%"},size:"middle",children:[r.jsx(tt,{message:c("chat.messageCard.authRequired"),description:r.jsx(xs,{remarkPlugins:i,rehypePlugins:l,components:a,children:s}),type:"error",showIcon:!0}),r.jsx(B,{type:"primary",icon:r.jsx(da,{}),onClick:()=>{window.location.hash="/settings"},children:c("chat.messageCard.goToSettings")})]});const{cleanText:d,hints:h}=t.role==="user"?b1(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:"",f=p.trim().length>0;return t.role==="assistant"&&!s&&!f?r.jsx(fs,{italic:!0,children:c("chat.messageCard.assistantThinking")}):r.jsxs(U,{direction:"vertical",style:{width:"100%"},size:"small",children:[f?r.jsx(ws,{size:"small",defaultActiveKey:["reasoning"],items:[{key:"reasoning",label:r.jsx(fs,{strong:!0,children:c("chat.messageCard.reasoning")}),children:r.jsx(xs,{remarkPlugins:i,rehypePlugins:l,components:a,children:p})}]}):null,h.map((g,S)=>g.type==="mcp"?r.jsx(tt,{type:"info",showIcon:!1,message:r.jsxs(U,{wrap:!0,size:"small",children:[r.jsx(ue,{color:"purple",children:"MCP"}),r.jsx(fs,{strong:!0,children:c("chat.messageCard.selectedTool")}),g.serverId&&r.jsx(fs,{type:"secondary",children:r.jsx(fs,{code:!0,children:g.serverId})}),g.toolName&&r.jsx(fs,{type:"secondary",children:r.jsx(fs,{code:!0,children:g.toolName})})]}),style:{marginBottom:0}},`hint-mcp-${S}`):r.jsx(tt,{type:"success",showIcon:!1,message:r.jsxs(U,{wrap:!0,size:"small",children:[r.jsx(ue,{color:"success",children:"Skill"}),r.jsx(fs,{strong:!0,children:c("chat.messageCard.selected")}),g.label&&r.jsx(fs,{children:g.label}),g.skillId&&r.jsx(fs,{type:"secondary",children:r.jsx(fs,{code:!0,children:g.skillId})})]}),style:{marginBottom:0}},`hint-skill-${S}`)),d?r.jsx(xs,{remarkPlugins:i,rehypePlugins:l,components:a,children:n?o(d):d}):null]})},S1=m.memo(x1),{Text:Ol}=pe,v1=({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(V,{align:"center",justify:"space-between",gap:s.marginXS,style:{marginBottom:s.marginXS},children:[r.jsxs(V,{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(V,{vertical:!0,gap:0,children:[r.jsx(Ol,{strong:!0,style:{fontSize:13,color:n?"var(--lotus-primary)":s.colorText,letterSpacing:"0.2px",lineHeight:1.1},children:a}),r.jsx(Ol,{type:"secondary",style:{fontSize:11,lineHeight:1.1},children:n?"Prompt":o?"Assistant":"System"})]})]}),t&&r.jsx(Ol,{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})]})},ru=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},w1=e=>e==="text"||e==="plan"||e==="question"||e==="tool_call"||e==="tool_result",_1=(e,t)=>{if(t)return t;if("message_type"in e&&e.message_type){const s=e.message_type;if(w1(s))return s}if(e.role==="assistant"&&e.type==="text"){const s=typeof e.content=="string"?e.content:"";try{const n=ru(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"},T1=(e,t)=>{if(t!=="plan"||e.role!=="assistant"||e.type!=="text")return null;const s=e.content??"";try{const n=ru(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},k1=(e,t)=>{if(t!=="question"||e.role!=="assistant"||e.type!=="text")return null;const s=e.content??"";try{const n=ru(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},jb=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"?Dy(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""},j1=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}`},Kh=e=>e.map(t=>({name:t.name,extensions:[...t.extensions]})),Gh=e=>e.trim().slice(0,64).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-")||"message",C1={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"},M1='[data-mermaid-loading="true"]';class Cb{static async exportMessageText(t){const{format:s,content:n,sessionId:o=null,messageId:a=null,filenamePrefix:i}=t,l=i||["chat-message",o?Gh(o.slice(0,8)):null,a?Gh(a.slice(0,8)):null].filter(Boolean).join("-"),c=s==="markdown"?$s.generateTimestampedFilename(l,"md"):$s.generateTimestampedFilename(l,"pdf");if(s==="markdown"){const u=await $s.saveTextFile(n,Kh($s.FILTERS.MARKDOWN),c);return u.success?{success:!0,filename:u.filename}:{success:!1,error:u.error}}try{const u=await this.generatePdfFromText(n),d=await $s.saveBinaryFile(u,Kh($s.FILTERS.PDF),c);return d.success?{success:!0,filename:d.filename}:{success:!1,error:d.error}}catch(u){return{success:!1,error:u instanceof Error?u.message:is.t("chat.messageActions.exportFailed")}}}static async generatePdfFromText(t){if(typeof document>"u")throw new Error(is.t("chat.messageActions.pdfUnavailable"));const s=(await Dt(async()=>{const{default:f}=await import("./vendor-pdf-wx1tMujY.js").then(y=>y.h);return{default:f}},__vite__mapDeps([16,1,2,3]),import.meta.url)).default,{jsPDF:n}=await Dt(async()=>{const{jsPDF:f}=await import("./vendor-pdf-wx1tMujY.js").then(y=>y.j);return{jsPDF:f}},__vite__mapDeps([16,1,2,3]),import.meta.url),{createRoot:o}=await Dt(async()=>{const{createRoot:f}=await import("./main-BgGBpmTu.js").then(y=>y.c);return{createRoot:f}},__vite__mapDeps([4,1,2,3,5]),import.meta.url),{flushSync:a}=await Dt(async()=>{const{flushSync:f}=await import("./vendor-antd-Dvkx9eba.js").then(y=>y.R);return{flushSync:f}},__vite__mapDeps([3,2]),import.meta.url),i=Tb(C1,{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=is.t("chat.messageActions.exportingPdf"),l.appendChild(c);const u=document.createElement("div");u.style.position="fixed",u.style.left="0",u.style.top="0",u.style.zIndex="2147483646",u.style.pointerEvents="none",u.style.width="794px",u.style.background="#fff",u.style.color="#111",u.style.padding="24px",u.style.boxSizing="border-box",u.style.fontFamily="system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",u.style.fontSize="14px",u.style.lineHeight="1.35";const d=document.createElement("style");d.textContent=`
222
+ `).trimStart(),hints:s}},x1=({sessionId:e,message:t,messageText:s,isUserToolCall:n,formatUserToolCall:o,markdownComponents:a,markdownPlugins:i,rehypePlugins:l})=>{var y;const{t:c}=ie(),u=g=>(g??"").trim().toLowerCase()==="conclusion";if(qy(t)){const g=t.result.result??"",S=t.isError?g||c("components.toolResult.executionFailed"):void 0,v=!S&&g.trim().length===0;if(t.result.display_preference==="Hidden")return null;const x=(t.toolName??"").trim().toLowerCase(),T=x==="conclusion",_=O0(g),j=(x==="conclusion_with_options"||x==="exitplanmode"||x==="request_permissions")&&!t.isError&&_,P=x==="conclusion"?Dy(g):null;return j&&_?r.jsx(y1,{sessionId:e,question:_.question,options:_.options,allowCustom:_.allow_custom,toolCallId:t.toolCallId,conclusionMarkdown:F0(_.conclusion),markdownComponents:a,markdownPlugins:i,rehypePlugins:l}):P?r.jsx(U,{direction:"vertical",style:{width:"100%"},size:"small",children:r.jsx(xs,{remarkPlugins:i,rehypePlugins:l,components:a,children:P})}):r.jsx(su,{content:g,toolName:t.toolName,status:t.isError?"error":v?"warning":"success",timestamp:t.createdAt,defaultCollapsed:!T,isLoading:v,errorMessage:S})}if(Xk(t)){const g=t.content??"",S=t.status==="error"?g||c("components.workflowResult.executionFailed"):void 0,v=!S&&g.trim().length===0;return r.jsx(kb,{content:g,workflowName:t.workflowName,parameters:t.parameters,status:v?"warning":t.status??"success",timestamp:t.createdAt,isLoading:v,errorMessage:S})}if(Yk(t)){const g=t.toolCalls.filter(S=>!u(S.toolName));return g.length===0?null:r.jsx(U,{direction:"vertical",style:{width:"100%"},children:g.map(S=>r.jsx(nu,{toolName:S.toolName,parameters:S.parameters,toolCallId:S.toolCallId,streamingOutput:S.streamingOutput,defaultExpanded:!1,metadata:t.metadata},S.toolCallId))})}if(t.isAuthError)return r.jsxs(U,{direction:"vertical",style:{width:"100%"},size:"middle",children:[r.jsx(tt,{message:c("chat.messageCard.authRequired"),description:r.jsx(xs,{remarkPlugins:i,rehypePlugins:l,components:a,children:s}),type:"error",showIcon:!0}),r.jsx(B,{type:"primary",icon:r.jsx(da,{}),onClick:()=>{window.location.hash="/settings"},children:c("chat.messageCard.goToSettings")})]});const{cleanText:d,hints:h}=t.role==="user"?b1(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:"",f=p.trim().length>0;return t.role==="assistant"&&!s&&!f?r.jsx(fs,{italic:!0,children:c("chat.messageCard.assistantThinking")}):r.jsxs(U,{direction:"vertical",style:{width:"100%"},size:"small",children:[f?r.jsx(ws,{size:"small",defaultActiveKey:["reasoning"],items:[{key:"reasoning",label:r.jsx(fs,{strong:!0,children:c("chat.messageCard.reasoning")}),children:r.jsx(xs,{remarkPlugins:i,rehypePlugins:l,components:a,children:p})}]}):null,h.map((g,S)=>g.type==="mcp"?r.jsx(tt,{type:"info",showIcon:!1,message:r.jsxs(U,{wrap:!0,size:"small",children:[r.jsx(ue,{color:"purple",children:"MCP"}),r.jsx(fs,{strong:!0,children:c("chat.messageCard.selectedTool")}),g.serverId&&r.jsx(fs,{type:"secondary",children:r.jsx(fs,{code:!0,children:g.serverId})}),g.toolName&&r.jsx(fs,{type:"secondary",children:r.jsx(fs,{code:!0,children:g.toolName})})]}),style:{marginBottom:0}},`hint-mcp-${S}`):r.jsx(tt,{type:"success",showIcon:!1,message:r.jsxs(U,{wrap:!0,size:"small",children:[r.jsx(ue,{color:"success",children:"Skill"}),r.jsx(fs,{strong:!0,children:c("chat.messageCard.selected")}),g.label&&r.jsx(fs,{children:g.label}),g.skillId&&r.jsx(fs,{type:"secondary",children:r.jsx(fs,{code:!0,children:g.skillId})})]}),style:{marginBottom:0}},`hint-skill-${S}`)),d?r.jsx(xs,{remarkPlugins:i,rehypePlugins:l,components:a,children:n?o(d):d}):null]})},S1=m.memo(x1),{Text:Ol}=pe,v1=({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(V,{align:"center",justify:"space-between",gap:s.marginXS,style:{marginBottom:s.marginXS},children:[r.jsxs(V,{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(V,{vertical:!0,gap:0,children:[r.jsx(Ol,{strong:!0,style:{fontSize:13,color:n?"var(--lotus-primary)":s.colorText,letterSpacing:"0.2px",lineHeight:1.1},children:a}),r.jsx(Ol,{type:"secondary",style:{fontSize:11,lineHeight:1.1},children:n?"Prompt":o?"Assistant":"System"})]})]}),t&&r.jsx(Ol,{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})]})},ru=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},w1=e=>e==="text"||e==="plan"||e==="question"||e==="tool_call"||e==="tool_result",_1=(e,t)=>{if(t)return t;if("message_type"in e&&e.message_type){const s=e.message_type;if(w1(s))return s}if(e.role==="assistant"&&e.type==="text"){const s=typeof e.content=="string"?e.content:"";try{const n=ru(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"},T1=(e,t)=>{if(t!=="plan"||e.role!=="assistant"||e.type!=="text")return null;const s=e.content??"";try{const n=ru(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},k1=(e,t)=>{if(t!=="question"||e.role!=="assistant"||e.type!=="text")return null;const s=e.content??"";try{const n=ru(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},jb=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"?Dy(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""},j1=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}`},Kh=e=>e.map(t=>({name:t.name,extensions:[...t.extensions]})),Gh=e=>e.trim().slice(0,64).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-")||"message",C1={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"},M1='[data-mermaid-loading="true"]';class Cb{static async exportMessageText(t){const{format:s,content:n,sessionId:o=null,messageId:a=null,filenamePrefix:i}=t,l=i||["chat-message",o?Gh(o.slice(0,8)):null,a?Gh(a.slice(0,8)):null].filter(Boolean).join("-"),c=s==="markdown"?$s.generateTimestampedFilename(l,"md"):$s.generateTimestampedFilename(l,"pdf");if(s==="markdown"){const u=await $s.saveTextFile(n,Kh($s.FILTERS.MARKDOWN),c);return u.success?{success:!0,filename:u.filename}:{success:!1,error:u.error}}try{const u=await this.generatePdfFromText(n),d=await $s.saveBinaryFile(u,Kh($s.FILTERS.PDF),c);return d.success?{success:!0,filename:d.filename}:{success:!1,error:d.error}}catch(u){return{success:!1,error:u instanceof Error?u.message:is.t("chat.messageActions.exportFailed")}}}static async generatePdfFromText(t){if(typeof document>"u")throw new Error(is.t("chat.messageActions.pdfUnavailable"));const s=(await Dt(async()=>{const{default:f}=await import("./vendor-pdf-wx1tMujY.js").then(y=>y.h);return{default:f}},__vite__mapDeps([16,1,2,3]),import.meta.url)).default,{jsPDF:n}=await Dt(async()=>{const{jsPDF:f}=await import("./vendor-pdf-wx1tMujY.js").then(y=>y.j);return{jsPDF:f}},__vite__mapDeps([16,1,2,3]),import.meta.url),{createRoot:o}=await Dt(async()=>{const{createRoot:f}=await import("./main-tzCacohH.js").then(y=>y.c);return{createRoot:f}},__vite__mapDeps([4,1,2,3,5]),import.meta.url),{flushSync:a}=await Dt(async()=>{const{flushSync:f}=await import("./vendor-antd-Dvkx9eba.js").then(y=>y.R);return{flushSync:f}},__vite__mapDeps([3,2]),import.meta.url),i=Tb(C1,{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=is.t("chat.messageActions.exportingPdf"),l.appendChild(c);const u=document.createElement("div");u.style.position="fixed",u.style.left="0",u.style.top="0",u.style.zIndex="2147483646",u.style.pointerEvents="none",u.style.width="794px",u.style.background="#fff",u.style.color="#111",u.style.padding="24px",u.style.boxSizing="border-box",u.style.fontFamily="system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",u.style.fontSize="14px",u.style.lineHeight="1.35";const d=document.createElement("style");d.textContent=`
223
223
  .md-export { color: #111; }
224
224
  .md-export h1 { font-size: 24px; margin: 0 0 16px; }
225
225
  .md-export h2 { font-size: 18px; margin: 18px 0 12px; }