@runfusion/fusion 0.37.0 → 0.38.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.
Files changed (57) hide show
  1. package/dist/bin.js +1510 -234
  2. package/dist/client/.vite/manifest.json +58 -58
  3. package/dist/client/assets/AgentDetailView-DuRYmHK3.js +18 -0
  4. package/dist/client/assets/{AgentPermissionPolicyEditor-niLSqGAE.js → AgentPermissionPolicyEditor-ClY32kYN.js} +1 -1
  5. package/dist/client/assets/AgentsView-UbCAHs_i.js +29 -0
  6. package/dist/client/assets/ChatView-DDDjYRKc.js +6 -0
  7. package/dist/client/assets/{DevServerView-0Gb44WOb.js → DevServerView-DY5GlJcD.js} +1 -1
  8. package/dist/client/assets/{DirectoryPicker-BSQA0XM9.js → DirectoryPicker-B4VRL2BH.js} +1 -1
  9. package/dist/client/assets/{DocumentsView-XZbaqEFF.js → DocumentsView-tqpIZ9t9.js} +1 -1
  10. package/dist/client/assets/{EvalsView-CJNtXxX9.js → EvalsView-C_Br3ry8.js} +1 -1
  11. package/dist/client/assets/{ExperimentalAgentOnboardingModal-DR8E3i36.js → ExperimentalAgentOnboardingModal-lXM--LV-.js} +1 -1
  12. package/dist/client/assets/GoalsView-B65urz9k.css +1 -0
  13. package/dist/client/assets/{GoalsView-CN1zQ_Ax.js → GoalsView-CI3Bzs1b.js} +1 -1
  14. package/dist/client/assets/{InsightsView-D_jRaMyn.js → InsightsView-BYfsVobi.js} +2 -2
  15. package/dist/client/assets/{MemoryView-D90vdPnp.js → MemoryView-DT4vIhaW.js} +1 -1
  16. package/dist/client/assets/{NodesView-C1zuedAe.js → NodesView-Dx6HFqjI.js} +1 -1
  17. package/dist/client/assets/{PiExtensionsManager-DBJDDVfM.js → PiExtensionsManager-BcGBnNiC.js} +2 -2
  18. package/dist/client/assets/{PluginManager-Ceg64P2Z.js → PluginManager-T_XZ7iNI.js} +1 -1
  19. package/dist/client/assets/{ResearchView-XRwWdczc.js → ResearchView-Bv4igpnv.js} +1 -1
  20. package/dist/client/assets/{SecretsView-TCrKyCme.js → SecretsView-C4VX2ZTa.js} +1 -1
  21. package/dist/client/assets/SettingsModal-CLEkhLK_.js +31 -0
  22. package/dist/client/assets/{SettingsModal-C1TczsEr.js → SettingsModal-Cy42vswI.js} +1 -1
  23. package/dist/client/assets/SettingsModal-D_uIvf6n.css +1 -0
  24. package/dist/client/assets/{SetupWizardModal-D6moSTT3.js → SetupWizardModal-LqloAL4J.js} +1 -1
  25. package/dist/client/assets/{SkillsView-BDHLPVBi.js → SkillsView-I1SDKaRz.js} +1 -1
  26. package/dist/client/assets/{StashRecoveryView-DZGa591R.js → StashRecoveryView-DMUUR3cy.js} +1 -1
  27. package/dist/client/assets/{TodoView-nr_SnCJv.js → TodoView-PKvJKjtV.js} +2 -2
  28. package/dist/client/assets/{dashboard-view-0XeZ1FTR.js → dashboard-view-D4XVI1XP.js} +2 -2
  29. package/dist/client/assets/{folder-open-iURwQbEg.js → folder-open-Doam5g-y.js} +1 -1
  30. package/dist/client/assets/index-BS-jSWPW.js +742 -0
  31. package/dist/client/assets/index-ktpD_W3I.css +1 -0
  32. package/dist/client/assets/{upload-Beqg4S4L.js → upload-BUfrZl69.js} +1 -1
  33. package/dist/client/assets/{users-C2o86ZCR.js → users-XNGnYBJb.js} +1 -1
  34. package/dist/client/index.html +40 -3
  35. package/dist/client/version.json +1 -1
  36. package/dist/droid-cli/package.json +1 -1
  37. package/dist/extension.js +1326 -182
  38. package/dist/pi-claude-cli/package.json +1 -1
  39. package/dist/plugins/fusion-plugin-cli-printing-press/package.json +1 -1
  40. package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
  41. package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
  42. package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
  43. package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
  44. package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
  45. package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
  46. package/dist/plugins/fusion-plugin-reports/package.json +1 -1
  47. package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
  48. package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
  49. package/package.json +1 -1
  50. package/dist/client/assets/AgentDetailView-T_AHPxcG.js +0 -18
  51. package/dist/client/assets/AgentsView-CQhaLHz_.js +0 -29
  52. package/dist/client/assets/ChatView-B60kYfdk.js +0 -6
  53. package/dist/client/assets/GoalsView-CtWi0fxE.css +0 -1
  54. package/dist/client/assets/SettingsModal-0gevFhXV.css +0 -1
  55. package/dist/client/assets/SettingsModal-B8fRuWdQ.js +0 -31
  56. package/dist/client/assets/index-CjuQj4qe.js +0 -742
  57. package/dist/client/assets/index-DmrpDn7c.css +0 -1
@@ -0,0 +1,29 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentDetailView-DuRYmHK3.js","assets/vendor-react-K0fH_qHe.js","assets/index-BS-jSWPW.js","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/vendor-codemirror-jBKmHyH0.js","assets/index-ktpD_W3I.css","assets/AgentPermissionPolicyEditor-ClY32kYN.js","assets/AgentPermissionPolicyEditor-CGxjOr6G.css","assets/ExperimentalAgentOnboardingModal-lXM--LV-.js","assets/ExperimentalAgentOnboardingModal-BNpveCEk.css","assets/AgentDetailView-CY-O6VkV.css"])))=>i.map(i=>d[i]);
2
+ import{c as pt,A as Je,C as gt,Z as Is,s as Ps,r as Et,F as Mt,f as zs,a as Fs,b as us,B as _t,u as ms,d as Nt,e as Os,g as Ds,h as Hs,i as Bs,j as Lt,k as ht,P as Ws,l as Gs,m as Vs,n as Ks,o as qt,G as Us,S as Ys,L as yt,T as kt,R as Ze,X as Zt,p as Xs,q as qs,t as ct,v as Zs,w as Jt,x as Js,y as Qs,z as pe,D as at,E as ea,M as ta,H as sa,I as Qt,N as es,J as ts,K as aa,O as Ct,Q as dt,U as na,V as la,W as ia,Y as ra,_ as oa,$ as ss,a0 as ca,a1 as da,a2 as ut,a3 as ua,a4 as as,a5 as ma,a6 as ga}from"./index-BS-jSWPW.js";import{r as s,j as e,a as ha}from"./vendor-react-K0fH_qHe.js";import{A as pa,S as xa,E as ba,f as va}from"./ExperimentalAgentOnboardingModal-lXM--LV-.js";import{U as It}from"./upload-BUfrZl69.js";import{F as fa}from"./folder-open-Doam5g-y.js";import"./vendor-xterm-DzcZoU0P.js";import"./vendor-codemirror-jBKmHyH0.js";/**
3
+ * @license lucide-react v1.7.0 - ISC
4
+ *
5
+ * This source code is licensed under the ISC license.
6
+ * See the LICENSE file in the root directory of this source tree.
7
+ */const ja=[["path",{d:"M13 5h8",key:"a7qcls"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 19h8",key:"c3s6r1"}],["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["rect",{x:"3",y:"4",width:"6",height:"6",rx:"1",key:"cif1o7"}]],Na=pt("list-todo",ja);/**
8
+ * @license lucide-react v1.7.0 - ISC
9
+ *
10
+ * This source code is licensed under the ISC license.
11
+ * See the LICENSE file in the root directory of this source tree.
12
+ */const ya=[["path",{d:"M10 5H3",key:"1qgfaw"}],["path",{d:"M12 19H3",key:"yhmn1j"}],["path",{d:"M14 3v4",key:"1sua03"}],["path",{d:"M16 17v4",key:"1q0r14"}],["path",{d:"M21 12h-9",key:"1o4lsq"}],["path",{d:"M21 19h-5",key:"1rlt1p"}],["path",{d:"M21 5h-7",key:"1oszz2"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M8 12H3",key:"a7s4jb"}]],ka=pt("sliders-horizontal",ya);/**
13
+ * @license lucide-react v1.7.0 - ISC
14
+ *
15
+ * This source code is licensed under the ISC license.
16
+ * See the LICENSE file in the root directory of this source tree.
17
+ */const Ca=[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]],wa=pt("zoom-in",Ca);/**
18
+ * @license lucide-react v1.7.0 - ISC
19
+ *
20
+ * This source code is licensed under the ISC license.
21
+ * See the LICENSE file in the root directory of this source tree.
22
+ */const Sa=[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]],Aa=pt("zoom-out",Sa);function ns(a){return typeof a=="number"&&Number.isFinite(a)?a:0}function Xe(a){return a.toLocaleString()}function Ra({agents:a}){const{rows:r,totalInputTokens:x,totalOutputTokens:g,totalTokens:h}=s.useMemo(()=>{const o=a.map(d=>{const f=ns(d.totalInputTokens),j=ns(d.totalOutputTokens);return{id:d.id,name:d.name,inputTokens:f,outputTokens:j,totalTokens:f+j}}).sort((d,f)=>f.totalTokens-d.totalTokens||d.name.localeCompare(f.name)||d.id.localeCompare(f.id));return{rows:o,totalInputTokens:o.reduce((d,f)=>d+f.inputTokens,0),totalOutputTokens:o.reduce((d,f)=>d+f.outputTokens,0),totalTokens:o.reduce((d,f)=>d+f.totalTokens,0)}},[a]),b=h>0;return e.jsxs("section",{className:"agent-token-stats-panel","aria-label":"Agent token usage statistics",children:[e.jsx("header",{className:"agent-token-stats-panel__header",children:e.jsx("h3",{className:"agent-token-stats-panel__title",children:"Token Usage by Agent"})}),e.jsxs("div",{className:"agent-token-stats-panel__totals",role:"list","aria-label":"Token usage totals",children:[e.jsxs("div",{className:"agent-token-stats-panel__total-card",role:"listitem",children:[e.jsx("span",{className:"agent-token-stats-panel__total-label",children:"Input Tokens"}),e.jsx("span",{className:"agent-token-stats-panel__total-value",children:Xe(x)})]}),e.jsxs("div",{className:"agent-token-stats-panel__total-card",role:"listitem",children:[e.jsx("span",{className:"agent-token-stats-panel__total-label",children:"Output Tokens"}),e.jsx("span",{className:"agent-token-stats-panel__total-value",children:Xe(g)})]}),e.jsxs("div",{className:"agent-token-stats-panel__total-card",role:"listitem",children:[e.jsx("span",{className:"agent-token-stats-panel__total-label",children:"Combined Tokens"}),e.jsx("span",{className:"agent-token-stats-panel__total-value",children:Xe(h)})]})]}),b?e.jsx("div",{className:"agent-token-stats-panel__table-wrapper",children:e.jsxs("table",{className:"agent-token-stats-panel__table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Agent"}),e.jsx("th",{scope:"col",children:"Input"}),e.jsx("th",{scope:"col",children:"Output"}),e.jsx("th",{scope:"col",children:"Total"})]})}),e.jsx("tbody",{children:r.map(o=>e.jsxs("tr",{children:[e.jsxs("th",{scope:"row",className:"agent-token-stats-panel__agent-cell",children:[e.jsx("span",{className:"agent-token-stats-panel__agent-name",children:o.name}),e.jsx("span",{className:"agent-token-stats-panel__agent-id",children:o.id})]}),e.jsx("td",{children:Xe(o.inputTokens)}),e.jsx("td",{children:Xe(o.outputTokens)}),e.jsx("td",{className:"agent-token-stats-panel__total-cell",children:Xe(o.totalTokens)})]},o.id))})]})}):e.jsx("div",{className:"agent-token-stats-panel__empty",role:"status",children:"No token usage recorded yet. Token totals appear here once agents run."})]})}const $a=[{icon:Je,label:"Active Agents",valueKey:"activeCount",className:"agent-metric-card--active"},{icon:Na,label:"Assigned Tasks",valueKey:"assignedTaskCount",className:"agent-metric-card--tasks"},{icon:gt,label:"Success Rate",valueKey:"successRate",className:"agent-metric-card--success"},{icon:Is,label:"Total Runs",valueKey:"completedRuns",className:"agent-metric-card--runs"}];function Ta({stats:a,className:r=""}){return a?e.jsx("div",{className:`agent-metrics-bar ${r}`.trim(),children:$a.map(x=>{const g=x.valueKey==="successRate"?`${Math.round(a.successRate*100)}%`:a[x.valueKey];return e.jsxs("div",{className:`agent-metric-card ${x.className}`,children:[e.jsx(x.icon,{size:18}),e.jsxs("div",{className:"agent-metric-info",children:[e.jsx("span",{className:"agent-metric-value",children:g}),e.jsx("span",{className:"agent-metric-label",children:x.label})]})]},x.label)})}):null}const ls=200;function Ea(a,r){const[x,g]=s.useState([]),[h,b]=s.useState(!1),o=s.useRef(null),d=s.useRef(0),f=s.useRef(a),j=s.useRef(r);return(f.current!==a||j.current!==r)&&(f.current=a,j.current=r,d.current++,o.current&&(o.current(),o.current=null),g([]),b(!1)),s.useEffect(()=>{if(!a){g([]),b(!1);return}const R=d.current;let y=`/api/tasks/${encodeURIComponent(a)}/logs/stream`;r&&(y+=`?projectId=${encodeURIComponent(r)}`);const C=Ps(y,{events:{"agent:log":E=>{if(d.current===R)try{const L=JSON.parse(E.data),W={type:L.type??"text",text:L.text??L.content??"",timestamp:L.timestamp,content:L.content};g($=>{const _=[W,...$];return _.length>ls?_.slice(0,ls):_})}catch{}}},onOpen:()=>{d.current===R&&b(!0)},onError:()=>{d.current===R&&b(!1)}});return o.current=C,()=>{C(),o.current=null,d.current===R&&b(!1)}},[a,r]),{entries:x,isConnected:h}}const Ma=5e3;function _a({agent:a,projectId:r,onSelect:x,onOpenTaskLogs:g}){const{entries:h,isConnected:b}=Ea(a.taskId,r),[o,d]=s.useState(null);s.useEffect(()=>{if(!a.taskId){d(null);return}let $=!1,_;const v=async()=>{try{const F=await zs(a.taskId,r);$||d(F)}catch{}finally{$||(_=setTimeout(v,Ma))}};return v(),()=>{$=!0,_&&clearTimeout(_)}},[a.taskId,r]);const f=a.lastHeartbeatAt?Math.floor((Date.now()-new Date(a.lastHeartbeatAt).getTime())/1e3):0,j=(()=>{if(!a.lastHeartbeatAt)return null;const $=Et(a.runtimeConfig?.heartbeatIntervalMs),_=new Date(a.lastHeartbeatAt).getTime()+$,v=Math.round((_-Date.now())/1e3);return Number.isFinite(v)?v<=0?`Heartbeat overdue ${wt(-v)}`:`Next heartbeat in ${wt(v)}`:null})(),k=o?.steps?.[o.currentStep??0],R=o?.steps?.length??0,y=(o?.currentStep??0)+1,C=o?.modelId,E=()=>{x&&x(a.id)},L=$=>{$.stopPropagation(),a.taskId&&g&&g(a.taskId)},W=$=>{($.key==="Enter"||$.key===" ")&&($.preventDefault(),E())};return e.jsxs("div",{className:"live-agent-card",onClick:E,onKeyDown:W,role:"button",tabIndex:0,"aria-label":`Select agent ${a.name}`,children:[e.jsxs("div",{className:"live-agent-card-header",children:[e.jsxs("div",{className:"live-agent-card-name",children:[e.jsx("span",{className:`status-dot ${a.state==="running"?"status-dot--pending":"status-dot--online"}`,"aria-hidden":"true"}),e.jsx("span",{children:a.name})]}),a.taskId&&e.jsx("span",{className:"live-agent-task badge",children:a.taskId})]}),e.jsx("div",{className:"live-agent-card-transcript",children:h.length===0?e.jsx("div",{className:"live-agent-card-empty",children:a.taskId?k?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"live-agent-card-status",children:["Step ",y,R?`/${R}`:"",": ",k.name]}),C&&e.jsx("div",{className:"live-agent-card-status-sub",children:C}),e.jsx("div",{className:"live-agent-card-status-sub",children:b?"Waiting for output...":"Connecting to log stream..."})]}):e.jsx("span",{children:b?"Waiting for output...":"Connecting..."}):e.jsx("span",{children:a.state==="running"?"Starting...":"Idle — no task assigned"})}):h.slice(0,20).map(($,_)=>e.jsx("div",{className:"live-agent-card-line",children:$.text},_))}),e.jsxs("div",{className:"live-agent-card-footer",children:[e.jsxs("div",{className:"live-agent-card-footer-meta",children:[e.jsx("span",{className:"text-secondary",title:"Time since last heartbeat",children:wt(f)}),j&&e.jsx("span",{className:"live-agent-card-next-heartbeat",title:j,children:j})]}),e.jsxs("div",{className:"live-agent-card-footer-actions",children:[a.taskId&&g&&e.jsxs("button",{type:"button",className:"live-agent-card-logs-btn",onClick:L,title:"View live run logs","aria-label":`View live logs for ${a.taskId}`,children:[e.jsx(Mt,{size:12}),e.jsx("span",{children:"Live logs"})]}),b&&e.jsx(Je,{size:12,className:"live-agent-streaming-dot"})]})]})]})}function wt(a){return a<60?`${a}s`:a<3600?`${Math.floor(a/60)}m ${a%60}s`:`${Math.floor(a/3600)}h ${Math.floor(a%3600/60)}m`}function La({agents:a,projectId:r,onAgentSelect:x,onOpenTaskLogs:g,className:h=""}){const b=Array.from(new Map(a.map(o=>[o.id,o])).values());return b.length===0?null:e.jsxs("div",{className:`active-agents-panel ${h}`.trim(),children:[e.jsxs("div",{className:"active-agents-panel-header",children:[e.jsx(Je,{size:16}),e.jsxs("span",{children:["Active Agents (",b.length,")"]})]}),e.jsx("div",{className:"active-agents-grid",children:b.map(o=>e.jsx(_a,{agent:o,projectId:r,onSelect:x,onOpenTaskLogs:g},o.id))})]})}function Ia({stats:a,activeAgents:r,projectId:x,isOpen:g,onToggle:h,onSelectAgent:b,onOpenTaskLogs:o}){return e.jsxs("section",{className:"agents-overview-bar","aria-label":"Agents overview",children:[e.jsxs("button",{type:"button",className:"agents-overview-bar__toggle","aria-expanded":g,onClick:h,children:[e.jsxs("span",{className:"agents-overview-bar__title-wrap",children:[g?e.jsx(Fs,{size:16,"aria-hidden":"true"}):e.jsx(us,{size:16,"aria-hidden":"true"}),e.jsx("span",{className:"agents-overview-bar__title",children:"Overview"})]}),e.jsxs("span",{className:"agents-overview-bar__meta text-secondary",children:[r.filter(d=>d.state==="active").length," active · ",r.filter(d=>d.state==="running").length," running"]})]}),g?e.jsxs("div",{className:"agents-overview-bar__content",children:[e.jsx(Ta,{stats:a,className:"agents-overview-bar__metrics"}),e.jsx(La,{agents:r,projectId:x,onAgentSelect:b,onOpenTaskLogs:o,className:"agents-overview-bar__active-panel"})]}):null]})}function St({title:a="No agents found",description:r="Create an agent to get started",ctaLabel:x="Create Agent",onCtaClick:g}){return e.jsxs("div",{className:"agent-empty",children:[e.jsx(_t,{size:48,opacity:.3,className:"agent-empty-state__icon"}),e.jsx("p",{className:"agent-empty-state__title",children:a}),e.jsx("p",{className:"agent-empty-state__description text-secondary",children:r}),g?e.jsx("button",{type:"button",className:"btn btn-task-create btn-sm",onClick:g,children:x}):null]})}const is=3,At=1e3;function Pa({isOpen:a,onClose:r,onGenerated:x,projectId:g}){ms(a);const[h,b]=s.useState(""),[o,d]=s.useState({type:"input"}),[f,j]=s.useState(null),[k,R]=s.useState(!1),y=s.useRef(null),C=s.useRef(null);s.useEffect(()=>{a&&o.type==="input"&&C.current?.focus()},[a,o.type]),s.useEffect(()=>{if(!a&&y.current){const v=y.current;y.current=null,Nt(v,g).catch(()=>{})}},[a,g]),s.useEffect(()=>{if(!a)return;const v=F=>{F.key==="Escape"&&E()};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[a]);const E=s.useCallback(()=>{if(y.current){const v=y.current;y.current=null,Nt(v,g).catch(()=>{})}b(""),d({type:"input"}),j(null),R(!1),r()},[r,g]),L=s.useCallback(async()=>{if(!(!h.trim()||h.trim().length<is)){j(null),d({type:"loading"});try{const{sessionId:v}=await Os(h.trim(),g);y.current=v;const{spec:F}=await Ds(v,g);d({type:"preview",spec:F,sessionId:v})}catch(v){const F=v instanceof Error?v.message:"Failed to generate agent specification";F.includes("429")||F.toLowerCase().includes("rate limit")?j("Too many requests. Please wait a moment and try again."):j(F),d({type:"input"}),y.current=null}}},[h,g]),W=s.useCallback(async()=>{if(y.current){const v=y.current;y.current=null;try{await Nt(v,g)}catch{}}await L()},[L,g]),$=s.useCallback(()=>{o.type==="preview"&&(y.current=null,x(o.spec),b(""),d({type:"input"}),j(null),R(!1),r())},[o,x,r]);if(!a)return null;const _=h.trim().length>=is&&h.trim().length<=At;return e.jsx("div",{className:"agent-dialog-overlay",onClick:v=>{v.target===v.currentTarget&&E()},children:e.jsxs("div",{className:"agent-dialog",role:"dialog","aria-modal":"true","aria-label":"Generate agent with AI",children:[e.jsxs("div",{className:"agent-dialog-header",children:[e.jsxs("span",{className:"agent-dialog-header-title",children:[e.jsx("span",{className:"agent-dialog-header-sparkle",children:"✨"}),"Generate Agent"]}),e.jsx("button",{className:"modal-close",onClick:E,"aria-label":"Close",children:"×"})]}),e.jsxs("div",{className:"agent-dialog-body",children:[f&&e.jsx("div",{className:"agent-dialog-error-banner",children:f}),o.type==="input"&&e.jsxs("div",{children:[e.jsx("p",{className:"agent-dialog-info",children:"Describe your agent's role and the AI will generate a complete specification including system prompt, suggested configuration, and more."}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx("label",{htmlFor:"agent-role-description",children:"Role Description"}),e.jsx("textarea",{ref:C,id:"agent-role-description",className:"input agent-dialog-textarea",rows:4,placeholder:'e.g. "Senior frontend code reviewer who specializes in React accessibility"',value:h,onChange:v=>b(v.target.value),onKeyDown:v=>{v.key==="Enter"&&!v.shiftKey&&_&&(v.preventDefault(),L())},maxLength:At,"aria-describedby":"role-description-hint"}),e.jsxs("div",{id:"role-description-hint",className:"agent-dialog-hint",children:[e.jsx("span",{children:"Describe what your agent should do"}),e.jsxs("span",{children:[h.length,"/",At]})]})]})]}),o.type==="loading"&&e.jsxs("div",{className:"agent-dialog-loading-center",children:[e.jsx("div",{className:"agent-dialog-spinner spin"}),e.jsx("p",{className:"agent-dialog-loading-text",children:"Generating agent specification..."})]}),o.type==="preview"&&e.jsxs("div",{children:[e.jsxs("div",{className:"agent-dialog-summary agent-dialog-summary--spaced",children:[e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label agent-dialog-summary-row-label--fixed",children:"Title"}),e.jsxs("span",{className:"agent-dialog-summary-row-value",children:[o.spec.icon," ",o.spec.title]})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label agent-dialog-summary-row-label--fixed",children:"Role"}),e.jsx("span",{children:o.spec.role})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label agent-dialog-summary-row-label--fixed",children:"Description"}),e.jsx("span",{className:"agent-dialog-summary-row-value agent-dialog-summary-row-value--body",children:o.spec.description})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label agent-dialog-summary-row-label--fixed",children:"Thinking"}),e.jsx("span",{className:"agent-dialog-summary-row-value agent-dialog-summary-row-value--capitalize",children:o.spec.thinkingLevel})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label agent-dialog-summary-row-label--fixed",children:"Max Turns"}),e.jsx("span",{children:o.spec.maxTurns})]})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsxs("label",{children:["System Prompt",e.jsx("button",{type:"button",className:"agent-dialog-expand-btn",onClick:()=>R(!k),children:k?"Collapse":"Expand"})]}),e.jsxs("div",{className:`agent-generation-prompt-box${k?"":" agent-generation-prompt-box--collapsed"}`,children:[o.spec.systemPrompt,!k&&o.spec.systemPrompt.length>500&&e.jsx("div",{className:"agent-generation-prompt-fade"})]})]})]})]}),e.jsxs("div",{className:"agent-dialog-footer",children:[e.jsx("button",{className:"btn",onClick:E,children:"Cancel"}),o.type==="input"&&e.jsx("button",{className:"btn btn-task-create",onClick:()=>void L(),disabled:!_,children:"Generate"}),o.type==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn",onClick:()=>void W(),children:"Regenerate"}),e.jsx("button",{className:"btn btn-task-create",onClick:$,children:"Use This"})]})]})]})})}const rs=[{value:"triage",label:"Triage",icon:"⊕"},{value:"executor",label:"Executor",icon:"▶"},{value:"reviewer",label:"Reviewer",icon:"⊙"},{value:"merger",label:"Merger",icon:"⊞"},{value:"scheduler",label:"Scheduler",icon:"◷"},{value:"engineer",label:"Engineer",icon:"⎔"},{value:"custom",label:"Custom",icon:"✦"}],os=new Set(["triage","executor","reviewer","merger","scheduler","engineer","custom"]);function za({isOpen:a,onClose:r,onCreated:x,projectId:g,prefillDraft:h=null,agentOnboardingEnabled:b=!1,existingAgents:o=[],onPrefillDraft:d}){const[f,j]=s.useState(0),[k,R]=s.useState("presets"),[y,C]=s.useState(""),[E,L]=s.useState(""),[W,$]=s.useState(""),[_,v]=s.useState("custom"),[F,P]=s.useState(""),[q,xe]=s.useState(""),[ne,V]=s.useState(""),[ae,le]=s.useState(""),[O,N]=s.useState(""),[ue,me]=s.useState(""),[S,Z]=s.useState({model:"",thinkingLevel:"off",maxTurns:1e3}),[ie,$e]=s.useState(null),[ee,te]=s.useState([]),[be,K]=s.useState(!1),[ge,je]=s.useState(null),[re,G]=s.useState(!1),[oe,he]=s.useState(!1),{favoriteProviders:Le,favoriteModels:Ie,toggleFavoriteProvider:Ne,toggleFavoriteModel:Ve}=Hs(),[Se,Pe]=s.useState([]),[Te,ze]=s.useState(!1),[T,M]=s.useState("model"),[ve,fe]=s.useState(""),[Ee,ce]=s.useState([]),[Me,Ae]=s.useState(!1),[i,p]=s.useState([]),[I,J]=s.useState(!1);s.useEffect(()=>{a&&(ze(!0),Bs().then(n=>{Pe(n.models)}).catch(()=>{}).finally(()=>ze(!1)))},[a]),s.useEffect(()=>{a&&(J(!0),p([]),Lt(void 0,g).then(n=>{p(n)}).catch(()=>{p([])}).finally(()=>J(!1)))},[a,g]),s.useEffect(()=>{if(!a)return;const n=Gs;if(typeof n!="function"){ce([]),Ae(!1);return}Ae(!0),ce([]),n(g).then(z=>{ce(z)}).catch(()=>{ce([])}).finally(()=>Ae(!1))},[a,g]);const D=S.model.includes("/")?S.model:"",U=s.useCallback(n=>{const z=os.has(n.role)?n.role:"custom";C(n.title),L(n.description),$(n.icon),v(z),V(n.systemPrompt),Z(_e=>({..._e,thinkingLevel:n.thinkingLevel,maxTurns:n.maxTurns})),G(!1),j(1)},[]),Fe=s.useCallback(n=>{Z(z=>({...z,model:n}))},[]),Oe=s.useCallback(n=>{M(n),n==="model"&&fe("")},[]),xt=s.useCallback(n=>{$e(n.id),C(n.name),$(n.icon),L(n.description??n.title),v(n.role),N(n.soul??""),V(n.instructionsText??""),j(1)},[]),ye=s.useCallback(n=>{const z=n.runtimeHint?.trim()??"",_e=n.model?.trim()||n.modelHint?.trim()||"";j(1),R("custom"),C(n.name??""),L(n.title??""),$(n.icon??""),v(os.has(n.role)?n.role:"custom"),P(n.reportsTo??""),V(n.instructionsText??""),le(n.heartbeatProcedurePath??""),N(n.soul??""),me(n.memory??""),te(Array.isArray(n.skills)?n.skills:[]),Z(He=>({...He,model:z?"":_e,thinkingLevel:n.thinkingLevel??He.thinkingLevel,maxTurns:n.maxTurns??He.maxTurns})),z?(M("runtime"),fe(z)):(M("model"),fe(""))},[]);if(s.useEffect(()=>{!a||!h||ye(h)},[a,h,ye]),!a)return null;const Ke=()=>{j(0),R("presets"),C(""),L(""),$(""),v("custom"),P(""),xe(""),V(""),le(""),N(""),me(""),Z({model:"",thinkingLevel:"off",maxTurns:1e3}),M("model"),fe(""),$e(null),te([]),je(null),G(!1),he(!1),r()},bt=async()=>{if(y.trim()){K(!0),je(null);try{const n={};T==="runtime"?ve.trim()&&(n.runtimeHint=ve.trim()):S.model.trim()&&(n.model=S.model.trim()),S.thinkingLevel!=="off"&&(n.thinkingLevel=S.thinkingLevel),S.maxTurns!==1e3&&(n.maxTurns=S.maxTurns),await Ks({name:y.trim(),role:_,...E.trim()?{title:E.trim()}:{},...W.trim()?{icon:W.trim()}:{},...F.trim()?{reportsTo:F.trim()}:{},...q.trim()?{instructionsPath:q.trim()}:{},...ne.trim()?{instructionsText:ne.trim()}:{},...ae.trim()?{heartbeatProcedurePath:ae.trim()}:{},...O.trim()?{soul:O.trim()}:{},...ue.trim()?{memory:ue.trim()}:{},...Object.keys(n).length>0?{runtimeConfig:n}:{},...ee.length>0?{metadata:{skills:ee}}:{}},g),Ke(),x()}catch(n){je(n instanceof Error?n.message:"Failed to create agent")}finally{K(!1)}}},Re=rs.find(n=>n.value===_),De=F.trim(),ke=De?i.find(n=>n.id===De):void 0,Qe=ve?Ee.find(n=>n.runtimeId===ve):void 0,Ce=n=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx("label",{id:n,children:"Runtime Source"}),e.jsxs("div",{className:"agent-runtime-mode-toggle",role:"radiogroup","aria-labelledby":n,children:[e.jsxs("label",{className:`agent-runtime-mode-option${T==="model"?" agent-runtime-mode-option--active":""}`,children:[e.jsx("input",{type:"radio",name:n,value:"model",checked:T==="model",onChange:()=>Oe("model")}),e.jsx("span",{children:"Built-in Model"})]}),e.jsxs("label",{className:`agent-runtime-mode-option${T==="runtime"?" agent-runtime-mode-option--active":""}`,children:[e.jsx("input",{type:"radio",name:n,value:"runtime",checked:T==="runtime",onChange:()=>Oe("runtime")}),e.jsx("span",{children:"Plugin Runtime"})]})]})]}),T==="model"?e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx("label",{children:"Model"}),Te?e.jsx("div",{className:"agent-dialog-loading",children:"Loading models…"}):e.jsx(Vs,{id:"agent-model",label:"Model",value:D,onChange:Fe,models:Se,placeholder:"Select a model…",favoriteProviders:Le,onToggleFavorite:Ne,favoriteModels:Ie,onToggleModelFavorite:Ve})]}):e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx("label",{htmlFor:"agent-runtime-hint",children:"Runtime"}),Me?e.jsx("div",{className:"agent-dialog-loading",children:"Loading runtimes…"}):e.jsxs("select",{id:"agent-runtime-hint",className:"select",value:ve,onChange:z=>fe(z.target.value),children:[e.jsx("option",{value:"",children:Ee.length>0?"Select a plugin runtime…":"No plugin runtimes available"}),Ee.map(z=>e.jsx("option",{value:z.runtimeId,children:z.description?`${z.name} — ${z.description}`:z.name},`${z.pluginId}:${z.runtimeId}`))]})]})]});return ha.createPortal(e.jsxs("div",{className:"agent-dialog-overlay",onClick:n=>{n.target===n.currentTarget&&Ke()},children:[e.jsxs("div",{className:"agent-dialog",role:"dialog","aria-modal":"true","aria-label":"Create new agent",children:[e.jsxs("div",{className:"agent-dialog-header",children:[e.jsx("span",{className:"agent-dialog-header-title",children:"New Agent"}),e.jsx("button",{className:"btn-icon",onClick:Ke,"aria-label":"Close",children:"×"})]}),e.jsx("div",{className:"agent-dialog-steps",children:[0,1,2].map(n=>e.jsx("div",{className:`agent-dialog-step${n===f?" active":n<f?" completed":""}`,"aria-label":`Step ${n+1}`},n))}),e.jsxs("div",{className:"agent-dialog-body",children:[f===0&&e.jsxs("div",{children:[b&&e.jsx("div",{className:"agent-dialog-step-zero-actions",children:e.jsx("button",{type:"button",className:"btn agent-dialog-interview-btn",onClick:()=>he(!0),children:"AI Interview"})}),e.jsxs("div",{className:"agent-dialog-tabs",role:"tablist","aria-label":"Agent setup mode",children:[e.jsx("button",{id:"agent-dialog-tab-presets",type:"button",role:"tab","aria-controls":"agent-dialog-panel-presets","aria-selected":k==="presets",tabIndex:k==="presets"?0:-1,className:`agent-dialog-tab${k==="presets"?" active":""}`,onClick:()=>R("presets"),"data-testid":"agent-dialog-tab-presets",children:"Preset personas"}),e.jsx("button",{id:"agent-dialog-tab-custom",type:"button",role:"tab","aria-controls":"agent-dialog-panel-custom","aria-selected":k==="custom",tabIndex:k==="custom"?0:-1,className:`agent-dialog-tab${k==="custom"?" active":""}`,onClick:()=>R("custom"),"data-testid":"agent-dialog-tab-custom",children:"Custom agent"})]}),k==="presets"&&e.jsx("div",{id:"agent-dialog-panel-presets",className:"agent-dialog-tab-panel",role:"tabpanel","aria-labelledby":"agent-dialog-tab-presets",children:e.jsxs("div",{className:"agent-presets",children:[e.jsx("div",{className:"agent-presets-header",children:"Choose a preset persona to prefill role, identity, soul, and instructions"}),e.jsx("div",{className:"agent-presets-grid",children:pa.map(n=>e.jsxs("button",{type:"button",className:`agent-preset-card${ie===n.id?" selected":""}`,"data-testid":`preset-${n.id}`,onClick:()=>xt(n),title:n.title,children:[e.jsx("span",{className:"agent-preset-icon",children:e.jsx(ht,{agent:{id:n.id,icon:n.icon,name:n.name},size:28})}),e.jsx("span",{className:"agent-preset-name",children:n.name}),e.jsx("span",{className:"agent-preset-role",children:n.role}),n.description&&e.jsx("span",{className:"agent-preset-description",children:n.description})]},n.id))})]})}),k==="custom"&&e.jsxs("div",{id:"agent-dialog-panel-custom",className:"agent-dialog-tab-panel",role:"tabpanel","aria-labelledby":"agent-dialog-tab-custom",children:[e.jsxs("div",{className:"agent-dialog-section",children:[e.jsx("div",{className:"agent-dialog-section-header",children:"Identity"}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsxs("label",{htmlFor:"agent-name",children:["Name ",!ie&&e.jsx("span",{className:"agent-dialog-required",children:"*"})]}),e.jsx("input",{id:"agent-name",type:"text",className:"input",placeholder:"e.g. Frontend Reviewer",value:y,onChange:n=>C(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-field agent-dialog-field--title",children:[e.jsxs("label",{htmlFor:"agent-title",children:["Title ",e.jsx("span",{className:"agent-dialog-optional",children:"(optional)"})]}),e.jsx("input",{id:"agent-title",type:"text",className:"input",placeholder:"e.g. Senior Code Reviewer",value:E,onChange:n=>L(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsxs("label",{htmlFor:"agent-icon",children:["Icon ",e.jsx("span",{className:"agent-dialog-optional",children:"(optional)"})]}),e.jsx("input",{id:"agent-icon",type:"text",className:"input",placeholder:"e.g. 🤖",value:W,onChange:n=>$(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx("label",{children:"Role"}),e.jsx("div",{className:"agent-role-grid",children:rs.map(n=>e.jsxs("button",{type:"button",className:`agent-role-option${_===n.value?" selected":""}`,onClick:()=>v(n.value),children:[e.jsx("span",{className:"agent-role-option-icon",children:n.icon}),e.jsx("span",{className:"agent-role-option-label",children:n.label})]},n.value))})]})]}),e.jsxs("div",{className:"agent-dialog-section",children:[e.jsx("div",{className:"agent-dialog-section-header",children:"Configuration"}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsxs("label",{htmlFor:"agent-reports-to",children:["Reports To ",e.jsx("span",{className:"agent-dialog-optional",children:"(optional)"})]}),e.jsxs("select",{id:"agent-reports-to",className:"select",value:F,onChange:n=>P(n.target.value),disabled:I,children:[e.jsx("option",{value:"",children:"No manager"}),i.map(n=>e.jsxs("option",{value:n.id,children:[n.name," (",n.id,")"]},n.id))]})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsxs("label",{htmlFor:"agent-soul",children:["Soul ",e.jsx("span",{className:"agent-dialog-optional",children:"(optional)"})]}),e.jsx("textarea",{id:"agent-soul",className:"input",rows:2,placeholder:"Describe the agent's personality and communication style...",value:O,onChange:n=>N(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsxs("label",{htmlFor:"agent-memory",children:["Agent Memory ",e.jsx("span",{className:"agent-dialog-optional",children:"(optional)"})]}),e.jsx("textarea",{id:"agent-memory",className:"input",rows:2,placeholder:"Private to this agent — durable preferences, operating habits, and context it should carry across tasks...",value:ue,onChange:n=>me(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsxs("label",{htmlFor:"agent-instructions-path",children:["Instructions Path ",e.jsx("span",{className:"agent-dialog-optional",children:"(optional)"})]}),e.jsx("input",{id:"agent-instructions-path",type:"text",className:"input",placeholder:"e.g. .fusion/agents/reviewer.md",value:q,onChange:n=>xe(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsxs("label",{htmlFor:"agent-heartbeat-procedure-path",children:["Heartbeat Procedure Path ",e.jsx("span",{className:"agent-dialog-optional",children:"(optional)"})]}),e.jsx("input",{id:"agent-heartbeat-procedure-path",type:"text",className:"input",placeholder:"e.g. .fusion/agents/ceo-agent2736/HEARTBEAT.md",value:ae,onChange:n=>le(n.target.value)}),e.jsx("p",{className:"agent-dialog-optional agent-dialog-field-hint",children:"Path to the agent's heartbeat procedure path, typically .fusion/agents/ceo-agent2736/HEARTBEAT.md. Legacy id-only default paths still work."})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsxs("label",{htmlFor:"agent-instructions-text",children:["Inline Instructions ",e.jsx("span",{className:"agent-dialog-optional",children:"(optional)"})]}),e.jsx("textarea",{id:"agent-instructions-text",className:"input",rows:4,placeholder:"Add custom behavior instructions...",value:ne,onChange:n=>V(n.target.value)})]})]}),e.jsxs("div",{className:"agent-dialog-section",children:[e.jsx("div",{className:"agent-dialog-section-header",children:"Runtime"}),Ce("agent-runtime-source-step-0")]}),e.jsxs("div",{className:"agent-dialog-ai-generate",children:[e.jsxs("button",{type:"button",className:"btn btn--ai-generate",onClick:()=>G(!0),children:[e.jsx("span",{children:"✨"}),"Generate with AI"]}),e.jsx("p",{className:"agent-dialog-ai-hint",children:"Describe your agent's role and let AI generate a specification"})]})]})]}),f===1&&e.jsxs("div",{children:[Ce("agent-runtime-source-step-1"),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx("label",{htmlFor:"agent-thinking",children:"Thinking Level"}),e.jsxs("select",{id:"agent-thinking",className:"select",value:S.thinkingLevel,onChange:n=>Z(z=>({...z,thinkingLevel:n.target.value})),children:[e.jsx("option",{value:"off",children:"Off"}),e.jsx("option",{value:"minimal",children:"Minimal"}),e.jsx("option",{value:"low",children:"Low"}),e.jsx("option",{value:"medium",children:"Medium"}),e.jsx("option",{value:"high",children:"High"})]})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx("label",{htmlFor:"agent-max-turns",children:"Max Turns"}),e.jsx("input",{id:"agent-max-turns",type:"number",className:"input",min:1,max:2e3,value:S.maxTurns,onChange:n=>Z(z=>({...z,maxTurns:Math.max(1,parseInt(n.target.value,10)||1)}))})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx(xa,{id:"agent-skills",label:"Skills",value:ee,onChange:te,projectId:g}),e.jsx("p",{className:"agent-dialog-optional agent-dialog-skills-hint",children:"Optional skills to assign to this agent"})]})]}),f===2&&e.jsxs("div",{children:[e.jsx("p",{className:"agent-dialog-info",children:"Review your agent configuration before creating."}),e.jsxs("div",{className:"agent-dialog-summary",children:[e.jsxs("div",{className:"agent-dialog-summary-row agent-dialog-summary-row--editable",children:[e.jsx("label",{className:"agent-dialog-summary-row-label",htmlFor:"agent-review-name",children:"Name"}),e.jsx("input",{id:"agent-review-name",type:"text",className:"input",placeholder:"e.g. Frontend Reviewer",value:y,onChange:n=>C(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-summary-row agent-dialog-summary-row--editable agent-dialog-summary-row--title",children:[e.jsx("label",{className:"agent-dialog-summary-row-label",htmlFor:"agent-review-title",children:"Title"}),e.jsx("input",{id:"agent-review-title",type:"text",className:"input",placeholder:"e.g. Senior Code Reviewer",value:E,onChange:n=>L(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Role"}),e.jsxs("span",{children:[Re?.icon," ",Re?.label]})]}),De&&e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Reports To"}),e.jsx("span",{children:ke?`${ke.name} (${ke.id})`:De})]}),e.jsxs("div",{className:"agent-dialog-summary-row agent-dialog-summary-row--editable",children:[e.jsx("label",{className:"agent-dialog-summary-row-label",htmlFor:"agent-review-soul",children:"Soul"}),e.jsx("textarea",{id:"agent-review-soul",className:"input",rows:2,placeholder:"Describe the agent's personality and communication style...",value:O,onChange:n=>N(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-summary-row agent-dialog-summary-row--editable",children:[e.jsx("label",{className:"agent-dialog-summary-row-label",htmlFor:"agent-review-heartbeat-procedure-path",children:"Heartbeat Procedure Path"}),e.jsx("input",{id:"agent-review-heartbeat-procedure-path",type:"text",className:"input",placeholder:"e.g. .fusion/agents/ceo-agent2736/HEARTBEAT.md",value:ae,onChange:n=>le(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-summary-row agent-dialog-summary-row--editable",children:[e.jsx("label",{className:"agent-dialog-summary-row-label",htmlFor:"agent-review-instructions-path",children:"Instructions Path"}),e.jsx("input",{id:"agent-review-instructions-path",type:"text",className:"input",placeholder:"e.g. .fusion/agents/reviewer.md",value:q,onChange:n=>xe(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-summary-row agent-dialog-summary-row--editable",children:[e.jsx("label",{className:"agent-dialog-summary-row-label",htmlFor:"agent-review-instructions-text",children:"Inline Instructions"}),e.jsx("textarea",{id:"agent-review-instructions-text",className:"input",rows:4,placeholder:"Add custom behavior instructions...",value:ne,onChange:n=>V(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:T==="runtime"?"Runtime":"Model"}),e.jsx("span",{children:T==="runtime"?Qe?Qe.name:e.jsx("em",{className:"agent-dialog-summary-row-value--muted",children:"Not selected"}):D?e.jsxs(e.Fragment,{children:[e.jsx(Ws,{provider:D.split("/")[0],size:"sm"})," ",(()=>{const n=D.indexOf("/"),z=D.slice(0,n),_e=D.slice(n+1);return Se.find(we=>we.provider===z&&we.id===_e)?.name||D})()]}):e.jsx("em",{className:"agent-dialog-summary-row-value--muted",children:"default"})})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Thinking"}),e.jsx("span",{className:"agent-dialog-summary-row-value--capitalize",children:S.thinkingLevel})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Max Turns"}),e.jsx("span",{children:S.maxTurns})]}),ee.length>0&&e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Skills"}),e.jsxs("span",{children:[ee.length," skill",ee.length!==1?"s":""," selected"]})]})]}),ge&&e.jsx("p",{className:"agent-dialog-error",children:ge})]})]}),e.jsxs("div",{className:"agent-dialog-footer",children:[f>0&&e.jsx("button",{className:"btn",onClick:()=>j(n=>n-1),disabled:be,children:"Back"}),e.jsx("button",{className:"btn",onClick:Ke,disabled:be,children:"Cancel"}),f<2?e.jsx("button",{className:"btn btn--primary",onClick:()=>j(n=>n+1),disabled:f===0&&!y.trim()&&!ie,children:"Next"}):e.jsx("button",{className:"btn btn--primary",onClick:()=>void bt(),disabled:be||!y.trim(),children:be?"Creating...":"Create"})]})]}),e.jsx(Pa,{isOpen:re,onClose:()=>G(!1),onGenerated:U,projectId:g}),e.jsx(ba,{isOpen:oe,onClose:()=>he(!1),onUseDraft:n=>{d?.(n),d||ye(n),he(!1)},projectId:g,existingAgents:o,mode:"create"})]}),document.body)}function Fa(a){const r=a.match(/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n([\s\S]*))?$/);if(!r)throw new Error("Missing YAML frontmatter delimiters (---)");const x=r[1].split(/\r?\n/),g=r[2]??"",h={name:""},b=[];let o=!1;for(const d of x){const j=d.trimEnd().trim();if(!j)continue;if(j.startsWith("skills:")){o=!0;continue}if(o&&j.startsWith("- ")){b.push(j.slice(2).trim());continue}o=!1;const[k,...R]=j.split(":"),C=R.join(":").trim().replace(/^['"]|['"]$/g,"");k==="name"&&(h.name=C),k==="title"&&(h.title=C),k==="icon"&&(h.icon=C),k==="role"&&(h.role=C),k==="reportsTo"&&(h.reportsTo=C)}if(!h.name)throw new Error("Missing required field: name");return b.length>0&&(h.skills=b),g.trim().length>0&&(h.instructionBody=g),h}function Oa({isOpen:a,onClose:r,onImported:x,projectId:g,initialInputMethod:h="paste"}){ms(a);const[b,o]=s.useState("input"),[d,f]=s.useState(h),[j,k]=s.useState(""),[R,y]=s.useState([]),[C,E]=s.useState("Unknown"),[L,W]=s.useState([]),[$,_]=s.useState([]),[v,F]=s.useState([]),[P,q]=s.useState([]),[xe,ne]=s.useState(!1),[V,ae]=s.useState(!1),[le,O]=s.useState(null),[N,ue]=s.useState(null),[me,S]=s.useState(null),Z=s.useRef(null),ie=s.useRef(null),[$e,ee]=s.useState([]),[te,be]=s.useState(""),[K,ge]=s.useState(null),[je,re]=s.useState(!1),[G,oe]=s.useState(null),he=s.useRef(!1);s.useEffect(()=>{d==="browse"&&!he.current&&!je&&(he.current=!0,re(!0),oe(null),qt().then(i=>{i.error?oe(i.error):i.companies.length>0?ee(i.companies):oe("No companies available")}).catch(i=>{oe(i instanceof Error?i.message:"Failed to load companies")}).finally(()=>{re(!1)}))},[d,je]);const Le=s.useCallback(()=>{he.current=!0,oe(null),ee([]),ge(null),re(!0),qt().then(i=>{i.error?oe(i.error):i.companies.length>0?ee(i.companies):oe("No companies available")}).catch(i=>{oe(i instanceof Error?i.message:"Failed to load companies")}).finally(()=>{re(!1)})},[]),Ie=s.useCallback(()=>{o("input"),f(h),k(""),y([]),E("Unknown"),W([]),_([]),F([]),q([]),ne(!1),ae(!1),O(null),ue(null),S(null),ee([]),be(""),ge(null),re(!1),oe(null),he.current=!1},[h]),Ne=s.useCallback(()=>{Ie(),r()},[Ie,r]),Ve=s.useCallback(i=>{const p=i.target.files?.[0];if(!p)return;const I=new FileReader;I.onload=J=>{const D=J.target?.result;f("file"),y([]),k(D),O(null)},I.onerror=()=>{O("Failed to read file")},I.readAsText(p),i.target.value=""},[]),Se=s.useCallback(async i=>{const p=Array.from(i.target.files??[]);if(p.length!==0)try{const I=p.filter(D=>(D.webkitRelativePath||D.name).toLowerCase().endsWith("agents.md")).sort((D,U)=>{const Fe=D.webkitRelativePath||D.name,Oe=U.webkitRelativePath||U.name;return Fe.localeCompare(Oe)});if(I.length===0){O("Selected directory has no AGENTS.md files");return}const J=[];for(const D of I){const U=await D.text();J.push(Fa(U))}f("directory"),y(J),k(""),O(null)}catch{O("Failed to parse AGENTS.md files from selected directory")}finally{i.target.value=""}},[]);function Pe(i){if(!g)return`/api${i}`;const p=i.includes("?")?"&":"?";return`/api${i}${p}projectId=${encodeURIComponent(g)}`}const Te=s.useCallback(async()=>{if(d==="directory"&&R.length===0){O("Please select a directory containing AGENTS.md files");return}if(d==="browse"&&!K){O("Please select a company from the catalog");return}if(d!=="directory"&&d!=="browse"&&!j.trim()){O("Please provide manifest content");return}ne(!0),O(null);try{let i;d==="directory"?i={agents:R,dryRun:!0}:d==="browse"&&K?i={importSource:"companies.sh",companySlug:K.slug,dryRun:!0}:i={manifest:j,dryRun:!0};const p=await fetch(Pe("/agents/import"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!p.ok){const U=await p.json();throw new Error(U.error??`Parse failed (${p.status})`)}const I=await p.json(),J=I.agents&&I.agents.length>0?I.agents:I.created.map(U=>({name:U,role:"custom"})),D=Array.isArray(I.skills)?I.skills:[];E(I.companyName??"Unknown"),W(J),_(D),F(J.map(U=>U.name)),q(D.map(U=>U.name)),o("preview")}catch(i){O(i instanceof Error?i.message:"Failed to parse manifest")}finally{ne(!1)}},[d,R,j,K,g]),ze=s.useCallback(async()=>{ae(!0),S(null);try{let i;d==="directory"?i={agents:R,skipExisting:!0,selectedAgents:v,selectedSkills:P}:d==="browse"&&K?i={importSource:"companies.sh",companySlug:K.slug,skipExisting:!0,selectedAgents:v,selectedSkills:P}:i={manifest:j,skipExisting:!0,selectedAgents:v,selectedSkills:P};const p=await fetch(Pe("/agents/import"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!p.ok){const J=await p.json();throw new Error(J.error??`Import failed (${p.status})`)}const I=await p.json();ue(I),o("result"),x()}catch(i){S(i instanceof Error?i.message:"Failed to import agents")}finally{ae(!1)}},[d,R,j,K,v,P,g,x]),T=v.length,M=P.length,ve=`${T} Agent${T!==1?"s":""}`,fe=`${M} Skill${M!==1?"s":""}`,Ee=T>0&&M>0?`${ve} + ${fe}`:M>0?fe:ve,ce=T>0&&M>0?`Importing ${T} agent${T!==1?"s":""} and ${M} skill${M!==1?"s":""}...`:M>0?`Importing ${M} skill${M!==1?"s":""}...`:`Importing ${T} agent${T!==1?"s":""}...`,Me=i=>{F(p=>p.includes(i)?p.filter(I=>I!==i):[...p,i])},Ae=i=>{q(p=>p.includes(i)?p.filter(I=>I!==i):[...p,i])};return a?e.jsx("div",{className:"agent-dialog-overlay",onClick:i=>{i.target===i.currentTarget&&Ne()},children:e.jsxs("div",{className:"agent-dialog agent-import-dialog",role:"dialog","aria-modal":"true","aria-label":"Import agents",children:[e.jsxs("div",{className:"agent-dialog-header",children:[e.jsx("span",{className:"agent-dialog-header-title",children:"Import Agents"}),e.jsx("button",{className:"modal-close",onClick:Ne,"aria-label":"Close",children:"×"})]}),e.jsxs("div",{className:"agent-dialog-body",children:[b==="input"&&e.jsxs("div",{className:"agent-import-input",children:[e.jsx("p",{className:"agent-import-description",children:"Import agents from an Agent Companies package. Browse the companies.sh catalog to discover published agents, upload an AGENTS.md file, select a directory, or paste manifest content."}),e.jsxs("div",{className:"agent-import-file-upload",children:[e.jsx("input",{ref:Z,type:"file",accept:".md,.txt",onChange:Ve,className:"agent-import-file-input","aria-label":"Upload agent manifest file"}),e.jsx("input",{ref:ie,type:"file",webkitdirectory:"",multiple:!0,onChange:Se,className:"agent-import-file-input","aria-label":"Select directory"}),e.jsxs("button",{type:"button",className:"btn agent-import-upload-btn",onClick:()=>Z.current?.click(),children:[e.jsx(It,{size:16}),"Choose File"]}),e.jsxs("button",{type:"button",className:"btn agent-import-upload-btn",onClick:()=>ie.current?.click(),children:[e.jsx(fa,{size:16}),"Select Directory"]}),e.jsxs("button",{type:"button",className:"btn agent-import-upload-btn",onClick:()=>{f("browse"),y([]),k(""),ge(null),O(null)},children:[e.jsx(Us,{size:16}),"Browse Catalog"]}),e.jsx("span",{className:"agent-import-file-hint",children:".md and .txt files supported"})]}),d==="browse"&&e.jsxs("div",{className:"agent-import-browse",children:[e.jsxs("div",{className:"agent-import-browse-header",children:[e.jsxs("div",{className:"agent-import-browse-search",children:[e.jsx(Ys,{size:16,className:"agent-import-browse-search-icon"}),e.jsx("input",{type:"text",className:"agent-import-browse-search-input",placeholder:"Search companies...",value:te,onChange:i=>be(i.target.value),"aria-label":"Search companies"})]}),K&&e.jsxs("div",{className:"agent-import-browse-selected",children:[e.jsx("span",{className:"agent-import-browse-selected-label",children:"Selected:"}),e.jsx("span",{className:"agent-import-browse-selected-name",children:K.name}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>ge(null),children:"Change"})]})]}),je&&e.jsxs("div",{className:"agent-import-browse-loading",children:[e.jsx(yt,{size:20,className:"spin"}),e.jsx("span",{children:"Loading companies..."})]}),G&&e.jsxs("div",{className:"agent-import-browse-error",children:[e.jsx(kt,{size:16}),e.jsx("span",{children:G}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:Le,children:[e.jsx(Ze,{size:14}),"Retry"]})]}),!je&&!G&&e.jsxs("div",{className:"agent-import-browse-list",children:[$e.filter(i=>te===""||i.name.toLowerCase().includes(te.toLowerCase())||(i.tagline?.toLowerCase().includes(te.toLowerCase())??!1)).map(i=>e.jsxs("div",{className:`agent-import-browse-item ${K?.slug===i.slug?"agent-import-browse-item--selected":""}`,onClick:()=>ge(i),role:"button",tabIndex:0,onKeyDown:p=>{(p.key==="Enter"||p.key===" ")&&ge(i)},children:[e.jsxs("div",{className:"agent-import-browse-item-header",children:[e.jsx("span",{className:"agent-import-browse-item-name",children:i.name}),i.installs!==void 0&&e.jsxs("span",{className:"agent-import-browse-item-installs",children:[i.installs.toLocaleString()," installs"]})]}),i.tagline&&e.jsx("span",{className:"agent-import-browse-item-tagline",children:i.tagline}),i.repo&&e.jsx("span",{className:"agent-import-browse-item-repo",children:i.repo})]},i.slug)),$e.filter(i=>te===""||i.name.toLowerCase().includes(te.toLowerCase())||(i.tagline?.toLowerCase().includes(te.toLowerCase())??!1)).length===0&&e.jsx("p",{className:"agent-import-browse-empty",children:te?"No companies match your search":"No companies available"})]})]}),d!=="browse"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"agent-import-divider",children:e.jsx("span",{children:"or paste manifest content"})}),e.jsx("textarea",{className:"agent-import-textarea",placeholder:`---
23
+ name: CEO
24
+ title: Chief Executive Officer
25
+ reportsTo: null
26
+ skills:
27
+ - review
28
+ ---
29
+ Agent instructions go here...`,value:j,onChange:i=>{f("paste"),y([]),k(i.target.value),O(null)},rows:8,"aria-label":"Manifest content"})]}),e.jsxs("p",{className:"agent-import-file-hint",children:["Current input: ",d]}),le&&e.jsxs("p",{className:"agent-dialog-error",children:[e.jsx(kt,{size:14}),le]})]}),b==="preview"&&e.jsxs("div",{className:"agent-import-preview",children:[e.jsxs("div",{className:"agent-import-company",children:[e.jsx("span",{className:"agent-import-company-label",children:"Company"}),e.jsx("span",{className:"agent-import-company-name",children:C})]}),e.jsxs("div",{className:"agent-import-count",children:[e.jsx(Mt,{size:14}),e.jsxs("span",{children:[L.length," agent",L.length!==1?"s":""," found"]})]}),L.length>0&&e.jsxs("div",{className:"agent-import-selection-controls",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>F(L.map(i=>i.name)),children:"Select all agents"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>F([]),children:"Clear agents"})]}),L.length>0?e.jsx("div",{className:"agent-import-agent-list",children:L.map((i,p)=>e.jsxs("div",{className:"agent-import-agent-item",children:[e.jsx("label",{className:"checkbox-label",children:e.jsx("input",{type:"checkbox","aria-label":`Select agent ${i.name}`,checked:v.includes(i.name),onChange:()=>Me(i.name)})}),e.jsx("span",{className:"agent-import-agent-icon",children:i.icon||"🤖"}),e.jsxs("div",{className:"agent-import-agent-details",children:[e.jsx("span",{className:"agent-import-agent-name",children:i.name}),e.jsxs("span",{className:"agent-import-agent-meta",children:[i.title&&e.jsxs("span",{className:"agent-import-agent-title",children:[i.title," · "]}),e.jsx("span",{className:"agent-import-agent-role",children:i.role}),i.reportsTo&&e.jsxs("span",{className:"agent-import-agent-reports",children:[" · reports to ",i.reportsTo]}),i.skills&&i.skills.length>0&&e.jsxs("span",{className:"agent-import-agent-model",children:[" · skills: ",i.skills.join(", ")]})]}),i.instructionsText&&e.jsxs("span",{className:"agent-import-agent-instructions",children:[i.instructionsText.slice(0,100),i.instructionsText.length>100?"...":""]})]})]},p))}):e.jsx("p",{className:"agent-import-empty",children:"No agents found in the manifest."}),$.length>0&&e.jsxs("div",{className:"agent-import-skills-section",children:[e.jsxs("div",{className:"agent-import-count",children:[e.jsx(Mt,{size:14}),e.jsxs("span",{children:[$.length," skill",$.length!==1?"s":""," found"]})]}),e.jsxs("div",{className:"agent-import-selection-controls",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>q($.map(i=>i.name)),children:"Select all skills"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>q([]),children:"Clear skills"})]}),e.jsx("div",{className:"agent-import-skill-list",children:$.map((i,p)=>e.jsxs("div",{className:"agent-import-skill-item",children:[e.jsx("label",{className:"checkbox-label",children:e.jsx("input",{type:"checkbox","aria-label":`Select skill ${i.name}`,checked:P.includes(i.name),onChange:()=>Ae(i.name)})}),e.jsx("span",{className:"agent-import-skill-icon",children:"⚡"}),e.jsxs("div",{className:"agent-import-skill-details",children:[e.jsx("span",{className:"agent-import-skill-name",children:i.name}),i.description&&e.jsx("span",{className:"agent-import-skill-description",children:i.description})]})]},`${i.name}-${p}`))})]}),me&&e.jsxs("p",{className:"agent-dialog-error",children:[e.jsx(kt,{size:14}),me]})]}),b==="result"&&N&&e.jsxs("div",{className:"agent-import-result",children:[e.jsx("div",{className:"agent-import-result-icon",children:e.jsx(gt,{size:32})}),e.jsx("h3",{className:"agent-import-result-title",children:"Import Complete"}),e.jsxs("p",{className:"agent-import-result-company",children:["From ",e.jsx("strong",{children:N.companyName??"Unknown"})]}),e.jsxs("div",{className:"agent-import-result-stats",children:[N.created.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--success",children:e.jsxs("span",{children:[N.created.length," created"]})}),N.skipped.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--skipped",children:e.jsxs("span",{children:[N.skipped.length," skipped (already exist)"]})}),N.errors.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--error",children:e.jsxs("span",{children:[N.errors.length," error",N.errors.length!==1?"s":""]})})]}),N.created.length>0&&e.jsx("div",{className:"agent-import-result-agents",children:N.created.map((i,p)=>e.jsxs("div",{className:"agent-import-result-agent",children:[e.jsx(gt,{size:12}),e.jsx("span",{children:i.name})]},p))}),N.errors.length>0&&e.jsx("div",{className:"agent-import-result-errors",children:N.errors.map((i,p)=>e.jsxs("div",{className:"agent-import-result-error",children:[e.jsx(Zt,{size:12}),e.jsxs("span",{children:[i.name,": ",i.error]})]},p))}),N.skills&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"agent-import-result-divider"}),e.jsx("h4",{className:"agent-import-result-section-title",children:"Skills"}),e.jsxs("div",{className:"agent-import-result-stats",children:[N.skills.imported.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--success",children:e.jsxs("span",{children:[N.skills.imported.length," skill",N.skills.imported.length!==1?"s":""," imported"]})}),N.skills.skipped.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--skipped",children:e.jsxs("span",{children:[N.skills.skipped.length," skill",N.skills.skipped.length!==1?"s":""," skipped (already exist)"]})}),N.skills.errors.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--error",children:e.jsxs("span",{children:[N.skills.errors.length," skill",N.skills.errors.length!==1?"s":""," error",N.skills.errors.length!==1?"s":""]})}),N.skills.imported.length===0&&N.skills.skipped.length===0&&N.skills.errors.length===0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--skipped",children:e.jsx("span",{children:"No skills in package"})})]}),N.skills.imported.length>0&&e.jsx("div",{className:"agent-import-result-agents",children:N.skills.imported.map((i,p)=>e.jsxs("div",{className:"agent-import-result-agent",children:[e.jsx(gt,{size:12}),e.jsx("span",{children:i.name})]},p))}),N.skills.errors.length>0&&e.jsx("div",{className:"agent-import-result-errors",children:N.skills.errors.map((i,p)=>e.jsxs("div",{className:"agent-import-result-error",children:[e.jsx(Zt,{size:12}),e.jsxs("span",{children:[i.name,": ",i.error]})]},p))})]})]})]}),e.jsxs("div",{className:"agent-dialog-footer",children:[b==="preview"&&e.jsx("button",{className:"btn",onClick:()=>o("input"),disabled:V,children:"Back"}),e.jsx("button",{className:"btn",onClick:Ne,disabled:V,children:b==="result"?"Close":"Cancel"}),b==="input"&&e.jsx("button",{className:"btn btn-task-create",onClick:()=>void Te(),disabled:xe||(d==="directory"?R.length===0:d==="browse"?!K:!j.trim()),children:xe?e.jsxs(e.Fragment,{children:[e.jsx(yt,{size:14,className:"spin"}),"Parsing..."]}):"Preview"}),b==="preview"&&e.jsx("button",{className:"btn btn-task-create",onClick:()=>void ze(),disabled:V||T===0&&M===0,children:V?e.jsxs(e.Fragment,{children:[e.jsx(yt,{size:14,className:"spin"}),ce]}):`Import ${Ee}`})]})]})}):null}const Rt="fn-agent-org-chart-layout";function cs(a){return a==="auto"||a==="horizontal"||a==="vertical"}const Da=768,Ha={nodeWidth:220,siblingGap:24,rootGap:24,chartPadding:24},Ba={nodeWidth:160,siblingGap:8,rootGap:8,chartPadding:8};function gs(a){return a.children.length===0?1:a.children.reduce((r,x)=>r+gs(x),0)}function Wa(a){return a<=Da?Ba:Ha}function Ga(a,r){const x=gs(a);return x*r.nodeWidth+Math.max(0,x-1)*r.siblingGap}function Va(a,r=Number.POSITIVE_INFINITY){const x=Wa(r);if(a.length===0)return x.nodeWidth;const h=a.map(o=>Ga(o,x)).reduce((o,d)=>o+d,0),b=Math.max(0,a.length-1)*x.rootGap;return h+b+x.chartPadding*2}function Ka(a){const r=a.preference??"auto";if(r!=="auto")return r;const x=Number.isFinite(a.availableWidth)&&a.availableWidth>0?a.availableWidth:0;return x===0||a.tree.length<=1?"horizontal":Va(a.tree,x)>x?"vertical":"horizontal"}const ds=s.lazy(()=>ca(()=>import("./AgentDetailView-DuRYmHK3.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])).then(a=>({default:a.AgentDetailView}))),$t=[{value:"triage",label:"Triage",icon:"⊕"},{value:"executor",label:"Executor",icon:"▶"},{value:"reviewer",label:"Reviewer",icon:"⊙"},{value:"merger",label:"Merger",icon:"⊞"},{value:"scheduler",label:"Scheduler",icon:"◷"},{value:"engineer",label:"Engineer",icon:"⎔"},{value:"custom",label:"Custom",icon:"✦"}],Tt=[.1,.25,.5,1,2,3,5,10],Ua=.25,Ya=3,mt=16,qe=32;function Pt(a){switch(a){case"running":return"agent-badge--running";case"active":return"agent-badge--active";case"paused":return"agent-badge--paused";case"error":return"agent-badge--error";case"idle":default:return"agent-badge--idle"}}function zt(a,r){switch(r){case"running":return`${a}--running`;case"active":return`${a}--active`;case"paused":return`${a}--paused`;case"error":return`${a}--error`;case"idle":default:return`${a}--idle`}}function hs(a){return a.children.length===0?1:a.children.reduce((r,x)=>r+hs(x),0)}function Ft(a,r){return a.state==="error"?{title:void 0,label:"Error"}:{title:r.reason??r.label,label:r.stateDerived?null:r.label}}function ps({node:a,onSelect:r,getHealthStatus:x,selectedAgentId:g,registerNodeElement:h,linksRef:b}){const{agent:o,children:d}=a,f=x(o),j=Ft(o,f),k=Pt(o.state),R=zt("org-chart-node-card",o.state),y=hs(a),C={"--org-chart-subtree-leaves":String(y)};return e.jsxs("div",{className:`org-chart-node${d.length>0?" org-chart-node--has-children":""}`,style:C,children:[e.jsxs("div",{ref:E=>h(o.id,E),"data-agent-id":o.id,className:`org-chart-node-card ${R}${g===o.id?" agent-card--selected":""}`,onClick:()=>r(o.id),role:"button",tabIndex:0,onKeyDown:E=>{(E.key==="Enter"||E.key===" ")&&(E.key===" "&&E.preventDefault(),r(o.id))},children:[e.jsxs("div",{className:"org-chart-node__header",children:[e.jsx("span",{className:"org-chart-node__icon",children:e.jsx(ht,{agent:o,size:20})}),e.jsx("span",{className:"org-chart-node__name",children:o.name})]}),e.jsxs("div",{className:"org-chart-node__meta",children:[e.jsx("span",{className:`org-chart-node__badge ${k}`,children:o.state}),e.jsxs("span",{className:"org-chart-node__health",style:{color:f.color},title:j.title,children:[f.icon,j.label&&e.jsx("span",{className:"text-secondary",children:j.label})]})]})]}),d.length>0&&e.jsx("div",{className:"org-chart-children",role:"group","aria-label":`${o.name} employees`,children:d.map(E=>(b.current.push({parentId:o.id,childId:E.agent.id}),e.jsx(ps,{node:E,onSelect:r,getHealthStatus:x,selectedAgentId:g,registerNodeElement:h,linksRef:b},E.agent.id)))})]})}function Xa({links:a,nodeElements:r,canvasRef:x,viewportRef:g,layoutMode:h,transform:b}){const[o,d]=s.useState([]);return s.useLayoutEffect(()=>{const f=x.current,j=g.current;if(!f||!j||a.length===0){d([]);return}const k=()=>{const y=f.getBoundingClientRect(),C=a.flatMap(({parentId:E,childId:L})=>{const W=r.get(E),$=r.get(L);if(!W||!$)return[];const _=W.getBoundingClientRect(),v=$.getBoundingClientRect(),F=(_.left-y.left)/b.scale,P=(_.top-y.top)/b.scale,q=(v.left-y.left)/b.scale,xe=(v.top-y.top)/b.scale;if(h==="vertical"){const N=F,ue=P+_.height/b.scale/2,me=q,S=xe+v.height/b.scale/2,Z=N-(N-me)/2;return[`M ${N} ${ue} L ${Z} ${ue} L ${Z} ${S} L ${me} ${S}`]}const ne=F+_.width/b.scale/2,V=P+_.height/b.scale,ae=q+v.width/b.scale/2,le=xe,O=V+(le-V)/2;return[`M ${ne} ${V} L ${ne} ${O} L ${ae} ${O} L ${ae} ${le}`]});d(C)};k();const R=new ResizeObserver(k);return R.observe(f),R.observe(j),r.forEach(y=>R.observe(y)),()=>R.disconnect()},[x,h,a,r,b.scale,g]),e.jsx("svg",{className:"agent-org-chart-connectors","aria-hidden":"true",children:o.map((f,j)=>e.jsx("path",{d:f},`${j}-${f}`))})}function an({addToast:a,projectId:r,onOpenTaskLogs:x,agentOnboardingEnabled:g=!1}){const[h,b]=s.useState(!1),d=Xs()==="mobile",[f,j]=s.useState("all"),{agents:k,stats:R,isLoading:y,loadAgents:C,refreshAgents:E}=qs(r,{filterState:f,showSystemAgents:h}),[L,W]=s.useState(!1),[$,_]=s.useState(null),[v,F]=s.useState(!1),[P,q]=s.useState(null),[xe,ne]=s.useState(null),V=d&&!!P,[ae,le]=s.useState("dashboard"),[O,N]=s.useState(null),[ue,me]=s.useState(!1),[S,Z]=s.useState(()=>{if(typeof window>"u")return"list";const t=ct("fn-agent-view",r);return t==="list"||t==="board"||t==="org"?t:"list"}),[ie,$e]=s.useState(()=>{if(typeof window>"u")return"auto";const t=ct(Rt,r);return cs(t)?t:"auto"}),[ee,te]=s.useState([]),[be,K]=s.useState(!1),[ge,je]=s.useState(0),[re,G]=s.useState(!1),[oe,he]=s.useState(!1),[Le,Ie]=s.useState(!1),[Ne,Ve]=s.useState(!1),[Se,Pe]=s.useState(0),[Te,ze]=s.useState(0),[T,M]=s.useState({scale:1,x:0,y:0}),[ve,fe]=s.useState(!1),Ee=s.useRef(null),ce=s.useRef(null),Me=s.useRef(null),Ae=s.useRef(new Map),i=s.useRef([]),p=s.useRef(new Map),I=s.useRef(null),J=s.useRef(null),D=s.useRef(!1),{confirm:U}=Zs(),Fe=s.useRef(null),Oe=s.useId();s.useEffect(()=>{const t=ct("fn-agent-view",r);if(t==="list"||t==="board"||t==="org"){Z(t);return}Z("list")},[r]),s.useEffect(()=>{Jt("fn-agent-view",S,r)},[S,r]),s.useEffect(()=>{const t=ct(Rt,r);$e(cs(t)?t:"auto")},[r]),s.useEffect(()=>{Jt(Rt,ie,r)},[ie,r]);const[xt,ye]=s.useState(null),Ke=s.useRef(null),[bt,Re]=s.useState(null),[De,ke]=s.useState(null),[Qe,Ce]=s.useState({}),[n,z]=s.useState(1),[_e,He]=s.useState(!1),[we,Ot]=s.useState(new Set),[vt,Ue]=s.useState(new Map),nt=s.useRef(!0);s.useEffect(()=>(nt.current=!0,()=>{nt.current=!1}),[]),s.useEffect(()=>{Js(r).then(t=>{nt.current&&z(t.heartbeatMultiplier??1)}).catch(()=>{})},[r]);const Dt=s.useCallback(async t=>{const l=Number.isFinite(t)&&t>0?t:1;z(l),He(!0);try{await Qs({heartbeatMultiplier:l},r),a(`Heartbeat speed set to ×${l.toFixed(1)}`,"success")}catch(c){a(`Failed to save heartbeat multiplier: ${pe(c)}`,"error")}finally{nt.current&&He(!1)}},[r,a]),lt=s.useMemo(()=>vt.size===0?k:k.map(t=>{const l=vt.get(t.id);return l?{...t,state:l}:t}),[k,vt]),et=s.useMemo(()=>lt.filter(t=>h||!at(t)),[lt,h]),xs=s.useMemo(()=>lt.filter(t=>t.state!=="active"&&t.state!=="running"?!1:h||!at(t)),[lt,h]),Be=s.useMemo(()=>{if(h)return ee;const t=l=>at(l.agent)?null:{...l,children:l.children.map(t).filter(c=>c!==null)};return ee.map(t).filter(l=>l!==null)},[ee,h]);s.useEffect(()=>{if(S!=="org")return;const t=ce.current;if(!t)return;const l=()=>{je(t.clientWidth)};l();const c=typeof ResizeObserver<"u"?new ResizeObserver(l):null;return c?.observe(t),window.addEventListener("resize",l),()=>{c?.disconnect(),window.removeEventListener("resize",l)}},[S,Be.length]),s.useEffect(()=>{if(S!=="org")return;let t=!1;return K(!0),ea(r,{includeEphemeral:h}).then(l=>{t||te(l)}).catch(l=>{t||(a(`Failed to load org chart: ${pe(l)}`,"error"),te([]))}).finally(()=>{t||K(!1)}),()=>{t=!0}},[S,r,h,a]),s.useEffect(()=>{const t=setInterval(()=>{C()},3e4);return()=>{clearInterval(t)}},[C]),s.useEffect(()=>{if(!re)return;let t=!1;Ve(!0),Lt(void 0,r).then(u=>{if(t)return;const w=u.filter(A=>!at(A));Pe(w.filter(A=>A.state==="active"||A.state==="running").length),ze(w.filter(A=>A.state==="paused").length)}).catch(u=>{t||(Pe(0),ze(0),a(`Failed to load bulk agent actions: ${pe(u)}`,"error"))}).finally(()=>{t||Ve(!1)});const l=u=>{const w=u.target;w&&(Ee.current?.contains(w)||Fe.current?.contains(w)||G(!1))},c=u=>{u.key==="Escape"&&(G(!1),Fe.current?.focus())};return document.addEventListener("mousedown",l),document.addEventListener("touchstart",l),document.addEventListener("keydown",c),()=>{t=!0,document.removeEventListener("mousedown",l),document.removeEventListener("touchstart",l),document.removeEventListener("keydown",c)}},[a,re,r]);const Ht=async t=>{if(!Le){Ie(!0);try{const c=(await Lt(void 0,r)).filter(B=>!at(B)),u=c.filter(B=>t==="paused"?B.state==="active"||B.state==="running":B.state==="paused"),w=c.length-u.length;if(u.length===0){a(`No agents eligible to ${t==="paused"?"pause":"resume"}`,"error");return}if(!await U({title:t==="paused"?"Pause All Agents":"Resume All Agents",message:`${t==="paused"?"Pause":"Resume"} ${u.length} agent${u.length===1?"":"s"} in this project?`,danger:t==="paused"}))return;const se=await Promise.allSettled(u.map(B=>ss(B.id,t,r))),Q=se.map((B,ot)=>({result:B,agent:u[ot]})).filter(B=>B.result.status==="rejected"),m=se.length-Q.length,H=Q.length,X=`${t==="paused"?"Paused":"Resumed"} ${m} agent${m===1?"":"s"}; skipped ${w}`;if(H>0){const B=Q.slice(0,3).map(({agent:ot,result:Ls})=>`${ot.name||ot.id}: ${pe(Ls.reason)}`).join("; ");a(`${X}; failed ${H}${B?` (${B})`:""}`,"error")}else a(X,"success");await C()}catch(l){a(`Failed to ${t==="paused"?"pause":"resume"} agents: ${pe(l)}`,"error")}finally{Ie(!1)}}},tt=async(t,l)=>{if(!we.has(t)){Ot(c=>new Set(c).add(t)),Ue(c=>{const u=new Map(c);return u.set(t,l),u});try{await ss(t,l,r),a(`Agent state updated to ${l}`,"success"),await C(),Ue(c=>{const u=new Map(c);return u.delete(t),u})}catch(c){Ue(u=>{const w=new Map(u);return w.delete(t),w}),a(`Failed to update state: ${pe(c)}`,"error")}finally{Ot(c=>{const u=new Set(c);return u.delete(t),u})}}},bs=async(t,l)=>{if(await U({title:"Delete Agent",message:`Delete agent "${l}"? This cannot be undone.`,danger:!0}))try{await ga(t,r),a(`Agent "${l}" deleted`,"success"),await C()}catch(u){a(`Failed to delete agent: ${pe(u)}`,"error")}},vs=async(t,l)=>{const c=k.find(u=>u.id===t);if(c){if(c.role===l){ye(null);return}try{await ut(t,{role:l},r),a(`Agent role updated to ${$t.find(u=>u.value===l)?.label??l}`,"success"),ye(null),C()}catch(u){a(`Failed to update role: ${pe(u)}`,"error")}}},fs=(t,l)=>{t.key==="Escape"&&ye(null)},js=async(t,l)=>{De===t.id&&(ke(null),Ce(c=>{const u={...c};return delete u[t.id],u})),Re(t.id);try{await ut(t.id,{runtimeConfig:{...t.runtimeConfig??{},heartbeatIntervalMs:l}},r),a(`Heartbeat interval updated to ${as(l)} for ${t.name}`,"success"),C()}catch(c){a(`Failed to update heartbeat interval: ${pe(c)}`,"error")}finally{Re(null)}},Bt=async t=>{const l=Qe[t.id]??"";if(l.trim()===""){a("Please enter a heartbeat interval in minutes","error");return}const c=Number(l);if(isNaN(c)){a("Heartbeat interval must be a valid number","error");return}if(c<=0){a("Heartbeat interval must be greater than 0","error");return}if(c>=1&&c<5){Re(t.id);try{await ut(t.id,{runtimeConfig:{...t.runtimeConfig??{},heartbeatIntervalMs:ua}},r),a(`Heartbeat interval set to 5 minutes (minimum). ${c} minute${c!==1?"s":""} was below the 5-minute minimum.`,"success"),ke(null),Ce(w=>{const A={...w};return delete A[t.id],A}),C()}catch(w){a(`Failed to update heartbeat interval: ${pe(w)}`,"error")}finally{Re(null)}return}const u=Math.round(c*6e4);Re(t.id);try{await ut(t.id,{runtimeConfig:{...t.runtimeConfig??{},heartbeatIntervalMs:u}},r),a(`Heartbeat interval updated to ${as(u)} for ${t.name}`,"success"),ke(null),Ce(w=>{const A={...w};return delete A[t.id],A}),C()}catch(w){a(`Failed to update heartbeat interval: ${pe(w)}`,"error")}finally{Re(null)}},Ns=t=>{const l=Et(t.runtimeConfig?.heartbeatIntervalMs),c=Math.round(l/6e4);ke(t.id),Ce(u=>({...u,[t.id]:String(c)}))},de=s.useCallback((t,l)=>{q(t),le(l?.initialTab??"dashboard"),N(l?.initialRunId??null),me(l?.preferActiveRun??!1)},[]),We=s.useCallback(()=>{q(null),le("dashboard"),N(null),me(!1)},[]),Wt=s.useCallback(t=>{de(t)},[de]),ys=s.useCallback(t=>{ne(t),de(t)},[de]),ks=s.useCallback(async({agentId:t,deleted:l})=>{await E(),l&&P===t&&We()},[E,P,We]),Cs=s.useCallback(t=>{de(t),d&&he(!1)},[d,de]),ws=async(t,l)=>{Ue(c=>{const u=new Map(c);return u.set(t,"running"),u});try{await ma(t,r,{source:"on_demand",triggerDetail:"Triggered from dashboard"}),a(`Heartbeat run started for ${l}`,"success"),await C(),Ue(c=>{const u=new Map(c);return u.delete(t),u})}catch(c){Ue(u=>{const w=new Map(u);return w.delete(t),w}),a(`Failed to start heartbeat run: ${pe(c)}`,"error")}},Ge=s.useCallback(t=>Math.min(Ya,Math.max(Ua,t)),[]),Y=s.useCallback(t=>{const l=ce.current,c=Me.current?.querySelector(".agent-org-chart");if(!l||!c)return{...t,scale:Ge(t.scale)};const u=Ge(t.scale),w=c.scrollWidth*u,A=c.scrollHeight*u,se=l.clientWidth,Q=l.clientHeight,m=Math.min(qe,se-w-qe),H=qe,X=Math.min(qe,Q-A-qe),B=qe;return{scale:u,x:Math.max(m,Math.min(H,t.x)),y:Math.max(X,Math.min(B,t.y))}},[Ge]),it=s.useCallback((t,l,c)=>{const u=ce.current;u&&M(w=>{const A=Ge(t),se=u.getBoundingClientRect(),Q=l-se.left,m=c-se.top,H=(Q-w.x)/w.scale,X=(m-w.y)/w.scale;return Y({scale:A,x:Q-H*A,y:m-X*A})})},[Ge,Y]),Ye=s.useCallback(()=>{const t=ce.current,l=Me.current?.querySelector(".agent-org-chart");if(!t||!l)return;const c=t.clientWidth,u=t.clientHeight,w=l.scrollWidth,A=l.scrollHeight;if(w<=0||A<=0)return;const se=Ge(Math.min(c/w,u/A,1)),Q=(c-w*se)/2,m=(u-A*se)/2;M(Y({scale:se,x:Q,y:m}))},[Ge,Y]),ft=s.useCallback(t=>{Z(t),t!=="org"&&M({scale:1,x:0,y:0}),d&&P&&We()},[We,d,P]),Gt=t=>$t.find(l=>l.value===t)?.label??t,rt=s.useMemo(()=>Ka({tree:Be,availableWidth:ge,preference:ie}),[Be,ie,ge]),Vt=s.useCallback(t=>{$e(t),M({scale:1,x:0,y:0})},[]);s.useEffect(()=>{M({scale:1,x:0,y:0}),D.current=!1},[r,rt]),s.useLayoutEffect(()=>{S!=="org"||be||Be.length===0||D.current||(Ye(),D.current=!0)},[S,Be.length,Ye,be]);const Ss=s.useCallback((t,l)=>{l?Ae.current.set(t,l):Ae.current.delete(t)},[]),Kt=s.useCallback(()=>e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"btn-icon touch-target",onClick:()=>M(t=>Y({...t,scale:t.scale*.9})),"aria-label":"Zoom out org chart",title:"Zoom out",children:e.jsx(Aa,{size:16})}),e.jsxs("span",{className:"agent-org-chart-controls__zoom-label","aria-live":"polite",children:[Math.round(T.scale*100),"%"]}),e.jsx("button",{type:"button",className:"btn-icon touch-target",onClick:()=>M(t=>Y({...t,scale:t.scale*1.1})),"aria-label":"Zoom in org chart",title:"Zoom in",children:e.jsx(wa,{size:16})}),e.jsxs("button",{type:"button",className:"btn touch-target btn-sm agent-org-chart-controls__fit-btn",onClick:Ye,"aria-label":"Fit org chart",title:"Fit org chart",children:[e.jsx(ta,{size:16}),"Fit"]}),e.jsxs("button",{type:"button",className:"btn touch-target btn-sm",onClick:()=>M(t=>Y({...t,x:0,y:0})),"aria-label":"Center org chart",title:"Center org chart",children:[e.jsx(sa,{size:16}),"Center"]})]}),[Y,Ye,T.scale]),As=s.useCallback(t=>{if(!(t.ctrlKey||t.metaKey))return;t.preventDefault();const l=t.deltaY>0?.9:1.1;it(T.scale*l,t.clientX,t.clientY)},[T.scale,it]),Rs=s.useCallback(t=>{if(t.target.closest(".org-chart-node-card"))return;if(t.currentTarget.setPointerCapture?.(t.pointerId),p.current.set(t.pointerId,{x:t.clientX,y:t.clientY}),p.current.size===1){I.current={x:t.clientX-T.x,y:t.clientY-T.y,pointerId:t.pointerId},fe(!0);return}if(p.current.size===2){const c=Array.from(p.current.values()),u=c[0].x-c[1].x,w=c[0].y-c[1].y;J.current={distance:Math.hypot(u,w),scale:T.scale,centerX:(c[0].x+c[1].x)/2,centerY:(c[0].y+c[1].y)/2},I.current=null}},[T.scale,T.x,T.y]),$s=s.useCallback(t=>{if(p.current.has(t.pointerId)){if(p.current.set(t.pointerId,{x:t.clientX,y:t.clientY}),p.current.size>=2){const l=Array.from(p.current.values()),c=J.current;if(!c)return;const u=l[0].x-l[1].x,w=l[0].y-l[1].y,A=Math.hypot(u,w),se=c.scale*(A/c.distance);it(se,c.centerX,c.centerY);return}!I.current||I.current.pointerId!==t.pointerId||M(l=>Y({...l,x:t.clientX-I.current.x,y:t.clientY-I.current.y}))}},[Y,it]),Ut=s.useCallback(t=>{p.current.delete(t.pointerId),p.current.size<2&&(J.current=null),p.current.size===0&&(I.current=null,fe(!1))},[]),Ts=s.useCallback(t=>{if(t.key==="ArrowLeft")M(l=>Y({...l,x:l.x+mt}));else if(t.key==="ArrowRight")M(l=>Y({...l,x:l.x-mt}));else if(t.key==="ArrowUp")M(l=>Y({...l,y:l.y+mt}));else if(t.key==="ArrowDown")M(l=>Y({...l,y:l.y-mt}));else if(t.key==="+"||t.key==="=")M(l=>Y({...l,scale:l.scale*1.1}));else if(t.key==="-")M(l=>Y({...l,scale:l.scale*.9}));else if(t.key==="0")Ye();else if(t.key==="Home")M({scale:1,x:0,y:0});else return;t.preventDefault()},[Y,Ye]),Yt=s.useCallback(()=>{const t=[{value:"horizontal",label:"Horizontal",icon:e.jsx(es,{size:16}),ariaLabel:"Horizontal layout"},{value:"vertical",label:"Vertical",icon:e.jsx(Qt,{size:16}),ariaLabel:"Vertical layout"},{value:"auto",label:"Auto",icon:e.jsx(Ze,{size:16}),ariaLabel:"Automatic layout"}];return e.jsx("div",{className:"agent-org-chart-layout-toggle","data-testid":"agent-org-chart-layout-toggle",children:t.map(l=>{const c=ie===l.value;return e.jsxs("button",{type:"button",className:`btn-icon touch-target agent-org-chart-layout-toggle__button${c?" btn-icon--active":""}`,onClick:()=>Vt(l.value),"aria-pressed":c,"aria-label":l.ariaLabel,title:l.ariaLabel,"data-layout-value":l.value,children:[l.icon,e.jsx("span",{className:"agent-org-chart-layout-toggle__text",children:l.label})]},l.value)})})},[Vt,ie]),Es=t=>Array.isArray(t.metadata?.skills)?t.metadata.skills:[],jt=t=>da(t),Ms=Ne||Le||Se===0,_s=Ne||Le||Te===0,Xt=y&&k.length===0,st=s.useCallback(()=>{W(!0)},[]);return e.jsxs("div",{className:"agents-view",children:[e.jsxs("div",{className:"agents-view-header",children:[e.jsxs("div",{className:"agents-view-title",children:[e.jsx(_t,{size:24}),e.jsx("h2",{children:"Agents"})]}),e.jsxs("div",{className:"agents-view-controls",children:[e.jsxs("div",{className:"view-toggle",children:[e.jsx("button",{className:`view-toggle-btn${S==="list"?" active":""}`,onClick:()=>ft("list"),title:"List view","aria-label":"List view","aria-pressed":S==="list",children:e.jsx(Qt,{size:16})}),e.jsx("button",{className:`view-toggle-btn${S==="board"?" active":""}`,onClick:()=>ft("board"),title:"Board view","aria-label":"Board view","aria-pressed":S==="board",children:e.jsx(Je,{size:16})}),e.jsx("button",{className:`view-toggle-btn${S==="org"?" active":""}`,onClick:()=>ft("org"),title:"Org Chart view","aria-label":"Org Chart view","aria-pressed":S==="org",children:e.jsx(es,{size:16})})]}),e.jsxs("div",{className:"agents-view-primary-actions",children:[e.jsx("button",{ref:Fe,className:`btn-icon agent-controls-trigger${re?" agent-controls-trigger--active":""}`,onClick:()=>G(t=>!t),title:"Controls","aria-label":"Controls","aria-haspopup":"dialog","aria-expanded":re,"aria-controls":Oe,children:e.jsx(ka,{size:16})}),e.jsx("button",{className:"btn-icon",onClick:()=>void C(),title:"Refresh","aria-label":"Refresh",children:e.jsx(Ze,{size:16,className:y?"spin":void 0})}),!d&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-sm agent-import-trigger",onClick:()=>{F(!0),G(!1)},"aria-label":"Import",title:"Import",children:[e.jsx(It,{size:16}),"Import"]}),e.jsxs("button",{className:"btn btn-task-create btn-sm",onClick:()=>{st(),G(!1)},"aria-label":"New Agent",title:"New Agent",children:[e.jsx(ts,{size:16}),"New Agent"]})]}),re&&e.jsxs("div",{ref:Ee,id:Oe,className:"agent-controls-panel agent-controls-panel--scrollable",role:"dialog","aria-label":"Agent controls","aria-modal":"false",children:[e.jsx("div",{className:"agent-controls",children:e.jsxs("div",{className:"agent-controls-filters",children:[e.jsxs("div",{className:"agent-state-filter",children:[e.jsx(aa,{size:14}),e.jsxs("select",{className:"agent-state-filter-select",value:f,onChange:t=>j(t.target.value),"aria-label":"Filter agents by state",children:[e.jsx("option",{value:"all",children:"All States"}),e.jsx("option",{value:"idle",children:"Idle"}),e.jsx("option",{value:"active",children:"Active"}),e.jsx("option",{value:"running",children:"Running"}),e.jsx("option",{value:"paused",children:"Paused"}),e.jsx("option",{value:"error",children:"Error"})]})]}),e.jsxs("label",{className:"checkbox-label agent-system-filter",children:[e.jsx("input",{type:"checkbox",checked:h,onChange:t=>b(t.target.checked),"aria-label":"Show system agents"}),"Show system agents"]})]})}),d&&e.jsxs("div",{className:"agent-controls-mobile-actions",children:[e.jsxs("button",{className:"btn btn-sm agent-import-trigger",onClick:()=>{F(!0),G(!1)},"aria-label":"Import",title:"Import",children:[e.jsx(It,{size:16}),"Import"]}),e.jsxs("button",{className:"btn btn-task-create btn-sm",onClick:()=>{st(),G(!1)},"aria-label":"New Agent",title:"New Agent",children:[e.jsx(ts,{size:16}),"New Agent"]})]}),e.jsxs("div",{className:"agent-controls-bulk-actions",role:"menu","aria-label":"Bulk agent actions",children:[e.jsxs("button",{type:"button",className:"agent-detail-bulk-menu-item",role:"menuitem",disabled:Ms,onClick:()=>{G(!1),Ht("paused")},children:[e.jsxs("span",{className:"agent-controls-bulk-actions__label",children:[e.jsx(Ct,{}),e.jsx("span",{children:"Pause All Agents"})]}),e.jsx("span",{className:"agent-detail-bulk-menu-item-hint",children:Ne?"Loading eligibility…":Se===0?"No active or running project agents to pause":`Pause ${Se} active/running agent${Se===1?"":"s"}`})]}),e.jsxs("button",{type:"button",className:"agent-detail-bulk-menu-item",role:"menuitem",disabled:_s,onClick:()=>{G(!1),Ht("active")},children:[e.jsxs("span",{className:"agent-controls-bulk-actions__label",children:[e.jsx(dt,{}),e.jsx("span",{children:"Resume All Agents"})]}),e.jsx("span",{className:"agent-detail-bulk-menu-item-hint",children:Ne?"Loading eligibility…":Te===0?"No paused project agents to resume":`Resume ${Te} paused agent${Te===1?"":"s"}`})]})]}),e.jsx("div",{className:"agent-global-controls agent-controls-actions",children:e.jsxs("div",{className:"heartbeat-multiplier-group",children:[e.jsxs("div",{className:"heartbeat-multiplier-controls",children:[e.jsx("label",{htmlFor:"globalHeartbeatMultiplier",className:"heartbeat-multiplier-label",children:"Heartbeat Speed"}),e.jsx("input",{id:"globalHeartbeatMultiplier",className:"heartbeat-multiplier-slider touch-target",type:"range",min:.1,max:10,step:.1,value:n,onChange:t=>{const l=Number(t.target.value);Dt(Number.isFinite(l)&&l>0?l:1)},disabled:_e}),e.jsxs("span",{className:"heartbeat-multiplier-value",children:["×",n.toFixed(1)]}),e.jsx("select",{className:"heartbeat-multiplier-preset",value:String(Tt.reduce((t,l)=>Math.abs(l-n)<Math.abs(t-n)?l:t,Tt[0])),onChange:t=>{const l=Number(t.target.value);Dt(Number.isFinite(l)&&l>0?l:1)},disabled:_e,"aria-label":"Heartbeat speed preset",children:Tt.map(t=>e.jsxs("option",{value:String(t),children:["×",t]},t))})]}),e.jsx("small",{className:"text-secondary",children:"Scales all agent heartbeat intervals. ×0.5 = twice as fast, ×2.0 = twice as slow. Default: ×1.0"})]})}),e.jsx(Ra,{agents:et})]})]})]})]}),e.jsx(za,{isOpen:L,onClose:()=>{W(!1),_(null)},onCreated:()=>{W(!1),_(null),C()},projectId:r,prefillDraft:$,agentOnboardingEnabled:g,existingAgents:k,onPrefillDraft:_}),e.jsx(Oa,{isOpen:v,onClose:()=>F(!1),onImported:()=>void C(),projectId:r}),e.jsx(Ia,{stats:R,activeAgents:xs,projectId:r,isOpen:oe,onToggle:()=>he(t=>!t),onSelectAgent:Cs,onOpenTaskLogs:x}),S==="org"?e.jsx("div",{className:"agents-org-full-view",children:e.jsx("div",{className:"agents-view-content agents-view-content--org-full",children:P?e.jsxs("div",{className:"agents-org-detail-view","data-testid":"agents-org-detail-view",children:[e.jsx("button",{type:"button",className:"btn btn-sm agents-org-detail-back",onClick:We,"aria-label":"Back to org chart",children:"Back to org chart"}),e.jsx(s.Suspense,{fallback:null,children:e.jsx(ds,{inline:!0,showInlineBackButton:!1,agentId:P,projectId:r,onClose:We,addToast:a,onChildClick:Wt,initialTab:ae,initialRunId:O,preferActiveRun:ue},P)})]}):Xt?e.jsxs("div",{className:"agents-view-loading",role:"status","aria-live":"polite",children:[e.jsx(Ze,{size:18,className:"spin"}),e.jsx("span",{children:"Loading agents..."})]}):e.jsxs("div",{className:"agent-org-chart-shell","data-testid":"agent-org-chart-shell",children:[d?e.jsxs("div",{className:"agent-org-chart-controls","data-testid":"agent-org-chart-controls",children:[Yt(),Kt()]}):e.jsxs("div",{className:"agent-org-chart-toolbar",children:[Yt(),e.jsx("div",{className:"agent-org-chart-controls","data-testid":"agent-org-chart-controls",children:Kt()})]}),e.jsx("div",{ref:ce,className:"agent-org-chart-viewport","data-testid":"agent-org-chart-viewport",tabIndex:0,role:"region","aria-label":"Org chart canvas",onWheel:As,onPointerDown:Rs,onPointerMove:$s,onPointerUp:Ut,onPointerCancel:Ut,onKeyDown:Ts,"data-panning":ve?"true":"false",children:e.jsxs("div",{ref:Me,className:`agent-org-chart-canvas agent-org-chart-canvas--zoom-${Math.round((T.scale??1)*100)}`,"data-panning":ve?"true":"false",style:{transform:`translate(${T.x}px, ${T.y}px) scale(${T.scale})`},children:[e.jsx("div",{className:`agent-org-chart${rt==="vertical"?" agent-org-chart--vertical":""}`,"data-testid":"agent-org-chart","data-layout-mode":rt,children:be?e.jsxs("div",{className:"agent-org-chart__loading",role:"status","aria-live":"polite",children:[e.jsx(Ze,{size:18,className:"spin"}),e.jsx("span",{children:"Loading org chart..."})]}):Be.length===0?e.jsx(St,{onCtaClick:st}):(i.current=[],Be.map(t=>e.jsx(ps,{node:t,onSelect:ys,getHealthStatus:jt,selectedAgentId:xe,registerNodeElement:Ss,linksRef:i},t.agent.id)))}),e.jsx(Xa,{links:i.current,nodeElements:Ae.current,canvasRef:Me,viewportRef:ce,layoutMode:rt,transform:T})]})})]})})}):e.jsxs("div",{className:"agents-split-layout",children:[e.jsx("div",{className:`agents-split-sidebar${V?" agents-split-sidebar--hidden-mobile":""}`,children:e.jsx("div",{className:"agents-view-content",children:Xt?e.jsxs("div",{className:"agents-view-loading",role:"status","aria-live":"polite",children:[e.jsx(Ze,{size:18,className:"spin"}),e.jsx("span",{children:"Loading agents..."})]}):S==="board"?e.jsx("div",{className:"agent-board",children:et.length===0?e.jsx(St,{onCtaClick:st}):et.map(t=>{const l=jt(t),c=Ft(t,l),u=Pt(t.state),w=zt("agent-board-card",t.state);return e.jsx("div",{className:`agent-board-card ${w}${P===t.id?" agent-card--selected":""}`,children:e.jsxs("div",{className:"agent-board-clickable",onClick:()=>de(t.id),role:"button",tabIndex:0,onKeyDown:A=>{(A.key==="Enter"||A.key===" ")&&(A.key===" "&&A.preventDefault(),de(t.id))},children:[e.jsxs("div",{className:"agent-board-header",children:[e.jsx("span",{className:"agent-board-icon",children:e.jsx(ht,{agent:t,size:20})}),e.jsx("span",{className:"agent-board-badge badge text-secondary",children:Gt(t.role)}),e.jsx("span",{className:`agent-board-badge badge ${u}`,children:t.state}),(t.pendingApprovalCount??0)>0?e.jsxs("span",{className:"agent-board-badge badge agent-approval-badge",title:"Pending approvals",children:[e.jsx("span",{className:"status-dot status-dot--pending"}),t.pendingApprovalCount]}):null]}),e.jsx("div",{className:"agent-board-name",children:t.name}),e.jsx("div",{className:"agent-board-id",children:t.id}),e.jsxs("div",{className:"agent-board-health",style:{color:l.color},title:c.title,children:[l.icon,c.label?` ${c.label}`:""]})]})},t.id)})}):e.jsx("div",{className:"agent-list",children:et.length===0?e.jsx(St,{onCtaClick:st}):et.map(t=>{const l=jt(t),c=Ft(t,l),u=Pt(t.state),w=zt("agent-card",t.state),A=Et(t.runtimeConfig?.heartbeatIntervalMs),se=na(A),Q=bt===t.id;return e.jsxs("div",{className:`agent-card agent-card--clickable ${w}${P===t.id?" agent-card--selected":""}`,onClick:m=>{const H=m.target;if(H===m.currentTarget){de(t.id);return}const X=H.closest('button, select, input, [role="button"]');X&&X!==m.currentTarget||de(t.id)},role:"button",tabIndex:0,onKeyDown:m=>{m.target===m.currentTarget&&(m.key==="Enter"||m.key===" ")&&(m.key===" "&&m.preventDefault(),de(t.id))},"aria-label":`Open details for ${t.name}`,children:[e.jsxs("div",{className:"agent-card-header",children:[e.jsxs("div",{className:"agent-info",children:[xt===t.id?e.jsx("select",{ref:Ke,className:"select agent-role-select",value:t.role,onChange:m=>void vs(t.id,m.target.value),onKeyDown:m=>fs(m,t.id),onBlur:()=>ye(null),autoFocus:!0,children:$t.map(m=>e.jsxs("option",{value:m.value,children:[m.icon," ",m.label]},m.value))}):e.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:m=>{m.stopPropagation(),ye(t.id)},title:"Click to change role",role:"button",tabIndex:0,onKeyDown:m=>{(m.key==="Enter"||m.key===" ")&&(m.stopPropagation(),ye(t.id))},children:e.jsx(ht,{agent:t,size:20})}),e.jsxs("div",{className:"agent-meta",children:[e.jsx("span",{className:"agent-name",children:t.name}),e.jsx("span",{className:"agent-id text-secondary",children:t.id})]}),e.jsx(us,{size:20,className:"agent-card-chevron"})]}),e.jsxs("div",{className:"agent-badges",children:[e.jsx("span",{className:`badge ${u}`,children:t.state}),e.jsxs("span",{className:"badge",style:{color:l.color},title:c.title,children:[l.icon,c.label?` ${c.label}`:""]}),e.jsx("span",{className:"badge text-secondary",children:Gt(t.role)}),(t.pendingApprovalCount??0)>0?e.jsxs("span",{className:"badge agent-approval-badge",title:"Pending approvals",children:[e.jsx("span",{className:"status-dot status-dot--pending"}),t.pendingApprovalCount]}):null,(()=>{const m=Es(t);if(m.length===0)return null;const H=m.slice(0,2),X=m.length-2;return e.jsxs(e.Fragment,{children:[H.map(B=>e.jsx("span",{className:"badge badge-skill",title:B,children:va(B)},B)),X>0&&e.jsxs("span",{className:"badge badge-skill",children:["+",X]})]})})()]})]}),e.jsxs("div",{className:"agent-card-body",children:[t.state==="error"&&t.lastError?e.jsx(la,{errorText:t.lastError,issueContext:{surface:"AgentsView list",agentId:t.id,agentName:t.name,agentState:t.state,taskId:t.taskId}}):null,t.taskId&&e.jsxs("div",{className:"agent-task",children:[e.jsx("span",{className:"text-secondary",children:"Working on:"}),e.jsx("span",{className:"badge",children:t.taskId})]}),e.jsxs("div",{className:"agent-heartbeat-control",children:[e.jsx("span",{className:"text-secondary",children:"Heartbeat:"}),De===t.id?e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"input agent-heartbeat-custom-input",value:Qe[t.id]??"",onChange:m=>Ce(H=>({...H,[t.id]:m.target.value})),onKeyDown:m=>{m.key==="Enter"?Bt(t):m.key==="Escape"&&(ke(null),Ce(H=>{const X={...H};return delete X[t.id],X}))},disabled:Q,"aria-label":`Custom heartbeat interval in minutes for ${t.name}`}),e.jsx("span",{className:"text-secondary",children:"min"}),e.jsx("button",{className:"btn btn-sm",onClick:()=>void Bt(t),disabled:Q,title:"Save custom interval",children:"Save"}),e.jsx("button",{className:"btn btn-sm",onClick:()=>{ke(null),Ce(m=>{const H={...m};return delete H[t.id],H})},disabled:Q,title:"Cancel custom interval",children:"Cancel"})]}):e.jsx(e.Fragment,{children:e.jsxs("select",{className:"select agent-heartbeat-select",value:A,onChange:m=>{const H=m.target.value;H==="__custom__"?Ns(t):js(t,Number(H))},disabled:Q,"aria-label":`Set heartbeat interval for ${t.name}`,children:[se.map(m=>e.jsx("option",{value:m.value,children:m.label},m.value)),ia.some(m=>m.value===A)&&e.jsx("option",{value:"__custom__",children:"Custom..."})]})}),Q&&e.jsx("span",{className:"agent-heartbeat-saving text-secondary",children:"Saving…"}),t.lastHeartbeatAt&&(()=>{const m=new Date(t.lastHeartbeatAt),H=new Date(m.getTime()+A),X=t.state==="active"||t.state==="running";return e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"agent-heartbeat-last text-secondary",title:m.toLocaleString(),children:["Last: ",m.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})]}),X&&e.jsxs("span",{className:"agent-heartbeat-next text-secondary",title:H.toLocaleString(),children:["Next: ",H.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})]})]})})()]})]}),e.jsxs("div",{className:"agent-card-actions",children:[e.jsxs("div",{className:"agent-card-actions-group agent-card-actions-group--primary",children:[t.state==="idle"&&e.jsxs("button",{className:"btn btn-sm",onClick:()=>void tt(t.id,"active"),disabled:we.has(t.id),title:"Activate",children:[e.jsx(dt,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Start"})]}),t.state==="active"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-sm",onClick:()=>void ws(t.id,t.name),disabled:we.has(t.id),title:"Run Now","aria-label":`Run now for ${t.name}`,children:[e.jsx(Je,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Run Now"})]}),e.jsxs("button",{className:"btn btn-sm",onClick:()=>void tt(t.id,"paused"),disabled:we.has(t.id),title:"Pause",children:[e.jsx(Ct,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Pause"})]})]}),t.state==="paused"&&e.jsxs("button",{className:"btn btn-sm",onClick:()=>void tt(t.id,"active"),disabled:we.has(t.id),title:"Resume",children:[e.jsx(dt,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Resume"})]}),t.state==="running"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-sm",onClick:()=>de(t.id,{initialTab:"runs",initialRunId:null,preferActiveRun:!0}),title:"View live run details","aria-label":`View live run details for ${t.name}`,children:[e.jsx(Je,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Running"})]}),e.jsxs("button",{className:"btn btn-sm",onClick:()=>void tt(t.id,"paused"),disabled:we.has(t.id),title:"Pause",children:[e.jsx(Ct,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Pause"})]})]}),t.state==="error"&&e.jsxs("button",{className:"btn btn-sm",onClick:()=>void tt(t.id,"active"),disabled:we.has(t.id),title:"Retry",children:[e.jsx(dt,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Retry"})]})]}),e.jsxs("div",{className:"agent-card-actions-group agent-card-actions-group--secondary",children:[e.jsxs("button",{className:"btn btn-sm agent-card-details-btn",onClick:()=>de(t.id),title:`View details for ${t.name}`,"aria-label":`View details for ${t.name}`,children:[e.jsx(ra,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Details"})]}),(t.state==="idle"||t.state==="paused")&&e.jsxs("button",{className:"btn btn-sm btn-danger",onClick:()=>void bs(t.id,t.name),title:"Delete",children:[e.jsx(oa,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Delete"})]})]})]})]},t.id)})})})}),e.jsx("div",{className:`agents-split-detail${d&&!P?" agents-split-detail--hidden-mobile":""}`,children:P?e.jsx(s.Suspense,{fallback:null,children:e.jsx(ds,{inline:!0,showInlineBackButton:d,agentId:P,projectId:r,onClose:We,addToast:a,onChildClick:Wt,initialTab:ae,initialRunId:O,preferActiveRun:ue,onMutationSuccess:ks},P)}):e.jsxs("div",{className:"agents-detail-empty-state",children:[e.jsx(_t,{size:48}),e.jsx("h3",{children:"Select an agent"}),e.jsx("p",{children:"Choose an agent from the sidebar to view details"})]})})]})]})}export{an as AgentsView};
@@ -0,0 +1,6 @@
1
+ import{r as s,a as wn,j as t,R as Sn}from"./vendor-react-K0fH_qHe.js";import{c as Cn,a9 as Ts,a7 as Is,bd as $s,be as ls,aG as At,bf as Ds,ac as Ps,bg as ts,t as kn,bh as Nn,bi as Ls,bj as jn,bk as ss,w as Mn,bl as Rn,bm as An,bn as En,bo as Tn,bp as In,bq as $n,br as Dn,s as Pn,bs as Ln,j as Fn,k as Qs,bt as _n,bu as zn,bv as Zs,bw as Hn,bx as Un,by as On,p as Bn,bz as Kn,bA as Gn,u as Wn,bB as Vn,ah as en,ai as tn,bC as qn,bD as Xn,S as Yn,_ as ns,P as dt,J as lt,aw as Jn,bE as Fs,a as Nt,bF as _s,bG as zs,bH as Hs,B as ut,ae as Qn,af as Zn,b2 as Et,bI as ea,bJ as ta,a$ as sa,bK as Us,bL as na,T as aa,bM as Os,bN as ra,au as Bs,m as ia}from"./index-BS-jSWPW.js";import"./vendor-xterm-DzcZoU0P.js";import"./vendor-codemirror-jBKmHyH0.js";/**
2
+ * @license lucide-react v1.7.0 - ISC
3
+ *
4
+ * This source code is licensed under the ISC license.
5
+ * See the LICENSE file in the root directory of this source tree.
6
+ */const oa=[["path",{d:"M5 3h14",key:"7usisc"}],["path",{d:"m18 13-6-6-6 6",key:"1kf1n9"}],["path",{d:"M12 7v14",key:"1akyts"}]],ca=Cn("arrow-up-to-line",oa),as="kb-chat-active-session";function Ks(n){const r=typeof n=="string"?n.trim():"",d=r.indexOf("/");return!r||d<=0||d>=r.length-1?{}:{modelProvider:r.slice(0,d),modelId:r.slice(d+1)}}function la(n){const r=n?.toolCalls;if(!Array.isArray(r))return;const d=r.map(i=>{if(!i||typeof i!="object")return null;const g=i,b=typeof g.toolName=="string"?g.toolName:"";if(!b)return null;const y=g.args;return{toolName:b,...y&&typeof y=="object"?{args:y}:{},isError:!!g.isError,result:g.result,status:"completed"}}).filter(i=>i!==null);return d.length>0?d:void 0}function da(n){const r=n?.fallback;if(!r||typeof r!="object")return;const d=r,i=typeof d.primaryModel=="string"?d.primaryModel:"",g=typeof d.fallbackModel=="string"?d.fallbackModel:"",b=d.triggerPoint;if(!(!i||!g||b!=="session-creation"&&b!=="prompt-time"))return{primaryModel:i,fallbackModel:g,triggerPoint:b}}function ua(n){const r=n?.failureInfo;if(!r||typeof r!="object")return;const d=r,i=typeof d.summary=="string"?d.summary.trim():"";if(!i)return;const g=(()=>{const b=d.reference;if(!b||typeof b!="object")return;const y=b,f=typeof y.kind=="string"?y.kind.trim():"",I=typeof y.id=="string"?y.id.trim():"";if(!(!f||!I))return{kind:f,id:I,...typeof y.label=="string"&&y.label.trim()?{label:y.label.trim()}:{}}})();return{summary:i,...typeof d.errorClass=="string"&&d.errorClass.trim()?{errorClass:d.errorClass.trim()}:{},...typeof d.code=="string"&&d.code.trim()?{code:d.code.trim()}:{},...typeof d.detail=="string"&&d.detail.trim()?{detail:d.detail.trim()}:{},...g?{reference:g}:{}}}function Gs(n){return typeof n=="string"?{summary:n.trim()||"Failed to get response"}:{summary:typeof n.summary=="string"&&n.summary.trim()?n.summary.trim():"Failed to get response",...typeof n.errorClass=="string"&&n.errorClass.trim()?{errorClass:n.errorClass.trim()}:{},...typeof n.code=="string"&&n.code.trim()?{code:n.code.trim()}:{},...typeof n.detail=="string"&&n.detail.trim()?{detail:n.detail.trim()}:{},...n.reference?{reference:n.reference}:{}}}function rs(n){return{id:n.id,sessionId:n.sessionId,role:n.role,content:n.content,thinkingOutput:n.thinkingOutput,toolCalls:la(n.metadata),fallbackInfo:da(n.metadata),failureInfo:ua(n.metadata),attachments:n.attachments,createdAt:n.createdAt}}function ma(n,r){const d=s.useCallback(l=>l?`${Ts.CHAT_SESSIONS_PREFIX}${l}`:null,[]),i=s.useCallback((l,u)=>l&&u?`${Ts.CHAT_MESSAGES_PREFIX}${l}:${u}`:null,[]),g=s.useCallback(l=>{const u=d(l);return u?Is(u,{maxAgeMs:$s})??[]:[]},[d]),[b,y]=s.useState(()=>g(n)),[f,I]=s.useState(null),[J,Q]=s.useState(()=>g(n).length===0),[w,j]=s.useState([]),[z,S]=s.useState(!1),[Z,C]=s.useState(!1),[O,N]=s.useState(""),[X,E]=s.useState(""),[_,T]=s.useState([]),[Y,k]=s.useState(""),[B,te]=s.useState(""),[h,p]=s.useState(!1),{agentsMap:he}=ls(n),c=s.useRef(null),re=s.useRef(null),se=s.useRef(!1),$=s.useRef(""),ue=s.useRef(null),be=s.useRef(b),G=s.useRef(f),Ge=s.useRef(w),K=s.useRef(Z);be.current=b,G.current=f,Ge.current=w,K.current=Z,s.useEffect(()=>{$.current=Y},[Y]);const We=s.useRef(new Set),ye=s.useRef(0),Ie=s.useRef(n);Ie.current!==n&&(At({view:"useChat",trigger:"project-context-change",projectId:n,replayAttempted:!1,detail:{previousProjectId:Ie.current??null}}),Ie.current=n,ye.current++);const oe=s.useCallback(async()=>{be.current.length===0&&Q(!0);try{const u=[...(await Ds(n)).sessions].sort((D,H)=>new Date(H.updatedAt).getTime()-new Date(D.updatedAt).getTime());y(u);const v=d(n);v&&Ps(v,u,{maxBytes:5e5})}catch{const l=g(n);if(be.current.length===0&&l.length===0){const u=d(n);u&&ts(u)}}finally{Q(!1)}},[d,n]);s.useEffect(()=>{const l=g(n);y(l),Q(l.length===0)},[n,g]),s.useEffect(()=>{oe()},[oe,n]);const Se=s.useRef(()=>{}),Ce=s.useRef(!1);s.useEffect(()=>{Ce.current=!1,re.current=null},[n]),s.useEffect(()=>{if(J||Ce.current||G.current)return;const l=kn(as,n);if(!l){Ce.current=!0;return}const u=b.find(v=>v.id===l);if(u){Ce.current=!0,Se.current(l,u);return}Ce.current=!0},[J,b,n]);const Ve=s.useCallback((l,u)=>{const v=i(l,u);return v?Is(v,{maxAgeMs:$s})??[]:[]},[i]),Oe=s.useCallback(l=>{const u=Ve(n,l);return u.length>0?(j(u),S(!1),!0):(j([]),!1)},[n,Ve]),ce=s.useCallback(async(l,u)=>{const v=typeof u?.offset=="number"&&u.offset>0||typeof u?.before=="string",D=i(n,l),H=v?[]:Ve(n,l),A=H.length>0;!v&&A?(j(H),S(!1)):S(!0);try{const ee=await Nn(l,{limit:50,order:"desc",...u},n),M=ee.messages.slice().reverse().map(rs);v?G.current?.id===l&&(j(U=>[...M,...U]),p(ee.messages.length>=50)):G.current?.id===l&&(j(M),p(ee.messages.length>=50),D&&Ps(D,M,{maxBytes:5e5}))}catch{!v&&Ge.current.length===0&&A&&(j(H),S(!1))}finally{S(!1)}},[i,n,Ve]),me=s.useCallback(()=>{ue.current?.(),ue.current=null,$.current="",k(""),N(""),E(""),T([]),C(!1)},[]),mt=s.useCallback(()=>{$.current="",k("")},[]),ie=s.useCallback(()=>{const l=$.current.trim();l&&($.current="",k(""),Be.current(l))},[]),le=s.useCallback((l,u,v)=>{if(c.current||!l)return!0;se.current=!1,u&&(N(u.streamingText),E(u.streamingThinking),T(u.toolCalls)),C(!0);const{handlers:D}=Ls({sessionId:l,tempUserMessageId:"",setStreamingText:N,setStreamingThinking:E,setStreamingToolCalls:T,cancelStreamingFlushesRef:ue,addToast:v?.silent?void 0:r,onFallbackSession:(A,ee)=>{const M=Ks(A.fallbackModel);y(U=>U.map(W=>W.id===ee?{...W,...M}:W)),I(U=>U&&U.id===ee?{...U,...M}:U)},onDone:()=>{N(""),E(""),T([]),C(!1),K.current=!1,c.current=null,re.current=null,ce(l),ie()},onError:A=>{N(""),E(""),T([]),C(!1),K.current=!1,c.current=null,re.current=null;const ee=Gs(A);v?.silent||r?.(ee.summary,"error"),ce(l),ie()}});At({view:"useChat",trigger:"sse-open",projectId:n,replayAttempted:typeof u?.replayFromEventId=="number",replayFromEventId:u?.replayFromEventId??null,lastEventId:u?.replayFromEventId??null});const H=jn(l,D,n,{...typeof u?.replayFromEventId=="number"?{lastEventId:u.replayFromEventId}:{}});return c.current=H,re.current={sessionId:l,replayFromEventId:typeof u?.replayFromEventId=="number"?u.replayFromEventId:null},!0},[r,ce,n,ie]),$e=s.useCallback((l,u)=>{const v=G.current?.id??null;if(l&&v===l&&!u)return;c.current&&(c.current.close(),c.current=null),re.current=null;const D=u??b.find(H=>H.id===l);I(D||null),l&&ss(l,n).then(({session:H})=>{!H.isGenerating||!H.inFlightGeneration||I(A=>!A||A.id!==l?A:{...A,...H})}).catch(()=>{}),me(),p(!1),l?(Oe(l),ce(l)):j([]),D?.isGenerating&&le(D.id,D.inFlightGeneration),l?Mn(as,l,n):Rn(as,n)},[le,Oe,b,ce,n,me]);Se.current=$e;const Tt=s.useCallback(async l=>{const u=await An(l,n);c.current&&(c.current.close(),c.current=null),re.current=null;const v={id:u.session.id,title:u.session.title,agentId:u.session.agentId,status:u.session.status,modelProvider:u.session.modelProvider,modelId:u.session.modelId,createdAt:u.session.createdAt,updatedAt:u.session.updatedAt};return y(D=>D.some(H=>H.id===v.id)?D:[v,...D]),me(),$e(v.id,v),v},[n,me,$e]),De=s.useCallback(async l=>{await En(l,{status:"archived"},n),y(u=>u.filter(v=>v.id!==l)),f?.id===l&&(re.current=null,I(null),j([]))},[f,n]),Pe=s.useCallback(async l=>{f?.id===l&&c.current&&(c.current.close(),c.current=null),f?.id===l&&(re.current=null),await Tn(l,n);const u=i(n,l);u&&ts(u),y(v=>v.filter(D=>D.id!==l)),f?.id===l&&(I(null),j([]))},[f,i,n]),nt=s.useCallback(async()=>{if(!f||!h)return;const l=Ge.current[0]?.createdAt;l&&await ce(f.id,{before:l})},[f,h,ce]),qe=s.useCallback(()=>{f&&(se.current=!0,ue.current?.(),ue.current=null,c.current?.close(),c.current=null,re.current=null,In(f.id,n).catch(()=>{}),C(!1),K.current=!1,N(""),E(""),T([]),ie())},[f,n,ie]),Be=s.useRef(()=>{}),Le=$n(),ke=s.useCallback(async l=>{try{await oe();const u=await ss(l,n);G.current?.id===l&&I(v=>!v||v.id!==l?v:{...v,...u.session}),u.session.isGenerating?(N(""),E(""),T([]),C(!0),K.current=!0,le(l,u.session.inFlightGeneration,{silent:!0})):(N(""),E(""),T([]),C(!1),K.current=!1,await ce(l))}catch{}},[le,ce,n,oe]),Ne=s.useCallback((l,u)=>{if(!f)return;if(K.current){$.current=l,k(l);return}se.current=!1,c.current&&(c.current.close(),c.current=null),re.current=null;const v=`temp-${Date.now()}`,D={id:v,sessionId:f.id,role:"user",content:l,createdAt:new Date().toISOString()};j(A=>[...A,D]),N(""),E(""),T([]),C(!0);const{handlers:H}=Ls({sessionId:f.id,tempUserMessageId:v,setStreamingText:N,setStreamingThinking:E,setStreamingToolCalls:T,cancelStreamingFlushesRef:ue,addToast:r,onFallbackSession:(A,ee)=>{const M=Ks(A.fallbackModel);y(U=>U.map(W=>W.id===ee?{...W,...M}:W)),I(U=>U&&U.id===ee?{...U,...M}:U)},onDone:({messageId:A,message:ee,accumulated:M})=>{const U=ee?{...rs(ee),...M.text.length>0?{content:M.text}:{}}:{id:A||`msg-${Date.now()}`,sessionId:f.id,role:"assistant",content:M.text,thinkingOutput:M.thinking,toolCalls:M.toolCalls.length>0?M.toolCalls:void 0,fallbackInfo:M.fallbackInfo,createdAt:new Date().toISOString()};We.current.add(U.id),j(W=>[...W,U]),N(""),E(""),T([]),C(!1),K.current=!1,c.current=null,re.current=null,setTimeout(()=>{We.current.delete(U.id)},1e3),oe(),ie()},onError:(A,ee)=>{const M=Gs(A),U=typeof A=="string"?A:M.summary,W=Ln(U);j(V=>{const P=V.filter(q=>q.id!==ee);return W?P:[...P,{id:`error-${Date.now()}`,sessionId:f.id,role:"assistant",content:M.summary,failureInfo:M,createdAt:new Date().toISOString()}]}),N(""),E(""),T([]),C(!1),K.current=!1,c.current=null,re.current=null,console.error("[useChat] Stream error:",A),W?(console.info("[useChat] Suppressed tab-suspension stream error:",A),f?.id&&(N(""),E(""),T([]),C(!0),K.current=!0,ke(f.id))):(r?.(M.summary,"error"),oe()),se.current||ie()}});c.current=Dn(f.id,l,H,u,n)},[f,n,oe,r,le,ke,ie]);Be.current=Ne;const ve=B?b.filter(l=>l.title?.toLowerCase().includes(B.toLowerCase())||l.agentId.toLowerCase().includes(B.toLowerCase())):b;return s.useEffect(()=>{if(!f?.id||f.isGenerating!==!0||c.current)return;const l=typeof f.inFlightGeneration?.replayFromEventId=="number"?f.inFlightGeneration.replayFromEventId:null,u=re.current;u?.sessionId===f.id&&u.replayFromEventId===l||le(f.id,f.inFlightGeneration,{silent:!0})},[f?.id,f?.isGenerating,f?.inFlightGeneration,le]),s.useEffect(()=>{if(!G.current?.isGenerating||(c.current||le(G.current.id,G.current.inFlightGeneration),!K.current||c.current||!G.current))return;const l=setInterval(async()=>{if(!K.current||c.current||!G.current){clearInterval(l);return}try{(await Ds(n)).sessions.find(D=>D.id===G.current?.id)?.isGenerating||(clearInterval(l),await ce(G.current.id),N(""),E(""),T([]),C(!1),K.current=!1,ie())}catch{}},3e3);return()=>clearInterval(l)},[le,ce,n,f,ie]),s.useEffect(()=>Le.onBecameVisible(()=>{const u=G.current;if(!u||c.current)return;const v=ye.current;ss(u.id,n).then(D=>{if(!(ye.current!==v||c.current)){if(D.session.isGenerating){N(""),E(""),T([]),C(!0),K.current=!0,le(u.id,D.session.inFlightGeneration,{silent:!0});return}K.current&&(N(""),E(""),T([]),C(!1),K.current=!1,ie(),ce(u.id))}}).catch(()=>{})}),[le,ce,n,Le,ie]),s.useEffect(()=>{const l=ye.current,u=n?`?projectId=${encodeURIComponent(n)}`:"",v=()=>ye.current!==l,D=W=>{if(v())return;const V=JSON.parse(W.data);y(P=>P.some(q=>q.id===V.id)?P:[V,...P])},H=W=>{if(v())return;const V=JSON.parse(W.data);y(P=>[...P.map(ne=>ne.id===V.id?V:ne)]),G.current?.id===V.id&&(I(V),V.isGenerating&&!c.current&&le(V.id,V.inFlightGeneration))},A=W=>{if(v())return;const{id:V}=JSON.parse(W.data);y(q=>q.filter(ne=>ne.id!==V));const P=i(n,V);P&&ts(P),G.current?.id===V&&(I(null),j([]))},ee=W=>{if(v())return;const V=JSON.parse(W.data),P=rs(V);if(!We.current.has(P.id)){if(G.current?.id===P.sessionId&&K.current&&!c.current&&P.role==="assistant"){j(q=>q.some(ne=>ne.id===P.id)?q:[...q,P]),N(""),E(""),T([]),C(!1),K.current=!1,ie();return}G.current?.id===P.sessionId&&!K.current&&j(q=>{if(q.some(ne=>ne.id===P.id))return q;if(P.role==="user"){const ne=q.findIndex(je=>je.role==="user"&&je.id.startsWith("temp-")&&je.content.trim()===P.content.trim());if(ne>=0){const je=[...q];return je[ne]=P,je}}return[...q,P]})}},M=W=>{if(v())return;const{id:V}=JSON.parse(W.data);j(P=>P.filter(q=>q.id!==V))};return Pn(`/api/events${u}`,{events:{"chat:session:created":D,"chat:session:updated":H,"chat:session:deleted":A,"chat:message:added":ee,"chat:message:deleted":M}})},[le,i,n,ie]),s.useEffect(()=>()=>{c.current&&(c.current.close(),c.current=null),re.current=null},[]),{sessions:b,activeSession:f,sessionsLoading:J,messages:w,messagesLoading:z,isStreaming:Z,streamingText:O,streamingThinking:X,streamingToolCalls:_,pendingMessage:Y,selectSession:$e,createSession:Tt,archiveSession:De,deleteSession:Pe,sendMessage:Ne,stopStreaming:qe,clearPendingMessage:mt,loadMoreMessages:nt,hasMoreMessages:h,searchQuery:B,setSearchQuery:te,filteredSessions:ve,refreshSessions:oe,agentsMap:he}}function ha(n,r=[]){const d=n.trim().replace(/^#/,"");if(!d)return{ok:!1,error:"Room name is required."};if(/[A-Z]/.test(d))return{ok:!1,error:"Use lowercase letters only."};const i=d.toLowerCase();return i.length>80?{ok:!1,error:"Room names can be at most 80 characters."}:/^[a-z0-9_-]+$/.test(i)?/^[-_]|[-_]$/.test(i)?{ok:!1,error:"Room names cannot start or end with a hyphen or underscore."}:r.some(g=>g.toLowerCase()===i)?{ok:!1,error:"A room with this name already exists."}:{ok:!0,name:i}:{ok:!1,error:"Use lowercase letters, numbers, hyphens, or underscores only."}}function fa({isOpen:n,onClose:r,onCreate:d,projectId:i,existingRoomNames:g=[]}){const[b,y]=s.useState(""),[f,I]=s.useState([]),[J,Q]=s.useState(""),[w,j]=s.useState([]),[z,S]=s.useState(!1),[Z,C]=s.useState(null),[O,N]=s.useState(!1),X=s.useRef(null),E=s.useRef(null);s.useEffect(()=>{n&&(E.current=document.activeElement instanceof HTMLElement?document.activeElement:null,S(!0),C(null),Fn(void 0,i).then(h=>I(h)).catch(()=>{I([]),C("Failed to load agents.")}).finally(()=>S(!1)))},[n,i]),s.useEffect(()=>{if(!n){y(""),Q(""),j([]),C(null),N(!1);return}const h=window.requestAnimationFrame(()=>X.current?.focus());return()=>window.cancelAnimationFrame(h)},[n]),s.useEffect(()=>{if(!n)return;const h=p=>{p.key==="Escape"&&r()};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[n,r]),s.useEffect(()=>{n||E.current?.focus()},[n]);const _=s.useMemo(()=>ha(b,g),[b,g]),T=s.useMemo(()=>{const h=J.trim().toLowerCase();return h?f.filter(p=>p.name.toLowerCase().includes(h)):f},[f,J]),Y=s.useMemo(()=>f.filter(h=>w.includes(h.id)),[f,w]),k=_.ok&&w.length>0&&!O&&!z;if(!n)return null;const B=h=>{O||j(p=>p.includes(h)?p.filter(he=>he!==h):[...p,h])},te=async()=>{if(!_.ok){C(_.error);return}if(w.length===0){C("Select at least one member.");return}C(null),N(!0);try{await d({name:_.name,displayName:`#${_.name}`,memberAgentIds:w}),r()}catch(h){C(h instanceof Error?h.message:"Failed to create room.")}finally{N(!1)}};return wn.createPortal(t.jsx("div",{className:"modal-overlay open",onClick:h=>h.target===h.currentTarget&&r(),children:t.jsxs("div",{className:"modal modal-lg create-room-modal",role:"dialog","aria-modal":"true","aria-label":"Create room",onClick:h=>h.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"Create room"}),t.jsx("button",{type:"button",className:"modal-close","aria-label":"Close",onClick:r,children:"×"})]}),t.jsxs("div",{className:"form-group create-room-modal-name-group",children:[t.jsx("label",{htmlFor:"create-room-name",children:"Room name"}),t.jsxs("div",{className:"create-room-modal-name-field",children:[t.jsx("span",{"aria-hidden":"true",className:"create-room-modal-name-hash",children:"#"}),t.jsx("input",{ref:X,id:"create-room-name",className:"input",value:b,disabled:O,onChange:h=>{const p=h.target.value.replace(/^#/,"").replace(/\s+/g,"-").toLowerCase();y(p)}})]}),!_.ok&&t.jsx("div",{className:"form-error",children:_.error})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"create-room-member-search",children:"Members"}),t.jsx("input",{id:"create-room-member-search",className:"input",placeholder:"Search agents",value:J,disabled:O,onChange:h=>Q(h.target.value)})]}),Y.length>0&&t.jsx("div",{className:"create-room-modal-selected","data-testid":"create-room-selected-chips",children:Y.map(h=>t.jsxs("button",{type:"button",className:"btn btn-sm create-room-modal-chip",onClick:()=>B(h.id),disabled:O,children:[h.name," ×"]},h.id))}),t.jsx("div",{className:"create-room-modal-member-list","data-testid":"create-room-member-list",children:z?t.jsx("div",{className:"create-room-modal-empty",children:"Loading agents..."}):T.length===0?t.jsx("div",{className:"create-room-modal-empty",children:f.length===0?"No agents in this project yet.":"No agents match your search."}):T.map(h=>{const p=w.includes(h.id);return t.jsxs("button",{type:"button",className:`create-room-modal-member-row${p?" create-room-modal-member-row--selected":""}`,onClick:()=>B(h.id),disabled:O,children:[t.jsx(Qs,{agent:h,size:20}),t.jsx("span",{children:h.name}),t.jsx("span",{className:"create-room-modal-member-role",children:h.role})]},h.id)})}),Z&&t.jsx("div",{className:"form-group",children:t.jsx("div",{className:"form-error",children:Z})}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:r,disabled:O,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>void te(),disabled:!k,children:O?"Creating...":"Create room"})]})]})}),document.body)}const sn=640;let is=!1;function ga(n){return n>sn?"auto":"hidden"}function pa(n){return Math.max(40,Math.min(n,sn))}function nn(n){const r=new Date(n),i=new Date().getTime()-r.getTime(),g=Math.floor(i/1e3),b=Math.floor(g/60),y=Math.floor(b/60),f=Math.floor(y/24);return g<60?"just now":b<60?`${b}m ago`:y<24?`${y}h ago`:f<7?`${f}d ago`:r.toLocaleDateString()}function Ws(n,r){if(!n||!r)return null;const d=r.toLowerCase();if(d.includes("claude")){let g=r.replace(/^claude[- ]/i,"Claude ").replace(/sonnet[- ](\d+)[- ](\d+)/i,"Sonnet $1.$2").replace(/sonnet[- ](\d+)/i,"Sonnet $1").replace(/haiku[- ](\d+)/i,"Haiku $1").replace(/opus[- ](\d+)/i,"Opus $1").replace(/sonnet/i,"Sonnet").replace(/haiku/i,"Haiku").replace(/opus/i,"Opus").replace(/-/g," ").trim();return g=g.replace(/\s+/g," "),g.length>30?g.slice(0,30)+"…":g}if(d.includes("gpt")||d.includes("openai")){const g=r.replace(/^gpt-4-turbo$/i,"GPT-4 Turbo").replace(/^gpt-4o-mini$/i,"GPT-4o Mini").replace(/^gpt-4o$/i,"GPT-4o").replace(/^gpt-4$/i,"GPT-4").replace(/^gpt-o1-preview$/i,"GPT-o1 Preview").replace(/^gpt-o1-mini$/i,"GPT-o1 Mini").replace(/^gpt-o1$/i,"GPT-o1").replace(/^gpt/i,"GPT").trim();return g.length>30?g.slice(0,30)+"…":g}if(d.includes("gemini")){const g=r.replace(/^gemini[- ]/i,"Gemini ").replace(/pro[- ](\d+)[- ](\d+)/i,"Pro $1.$2").replace(/pro[- ](\d+)/i,"Pro $1").replace(/-/g," ").replace(/\s+/g," ").trim();return g.length>30?g.slice(0,30)+"…":g}const i=r.replace(/-/g," ").replace(/^\w/,g=>g.toUpperCase()).replace(/\s+/g," ").trim();return i.length>30?i.slice(0,30)+"…":i}function Rt(n,r){return n.length<=r?n:`${n.slice(0,r)}…`}function ba(n){if(!n)return null;const r=Object.entries(n);return r.length===0?null:r.map(([d,i])=>{const g=typeof i=="string"?i:(()=>{try{return JSON.stringify(i)}catch{return String(i)}})();return`${d}=${Rt(g,50)}`}).join(", ")}function va(n){if(n===void 0)return null;if(typeof n=="string")return Rt(n,200);try{return Rt(JSON.stringify(n),200)}catch{return Rt(String(n),200)}}function xa(n){if(!n)return null;if(n.kind==="mailbox"||n.kind==="mailbox-message"){const r=typeof window>"u"?"/":window.location.pathname||"/",d=new URLSearchParams(typeof window>"u"?"":window.location.search);return d.set("view","mailbox"),d.set("mailbox-message",n.id),`${r}?${d.toString()}#message-${encodeURIComponent(n.id)}`}return null}function ya(n){if(!n)return null;const r=n.label??`${n.kind} ${n.id}`,d=xa(n),i=`chat-failure-reference-${n.kind}-${n.id}`.replace(/[^a-zA-Z0-9_-]+/g,"-").toLowerCase();return t.jsxs("div",{className:"chat-message-failure-reference",children:[t.jsx("span",{className:"chat-message-failure-reference-label",children:"Reference"}),t.jsx("span",{className:"chat-message-failure-reference-value",children:r}),d?t.jsx("a",{className:"btn btn-sm chat-message-failure-reference-link",href:d,children:"Open mailbox message"}):t.jsxs("details",{className:"chat-message-failure-reference-details",children:[t.jsx("summary",{className:"btn btn-sm chat-message-failure-reference-link",children:"View failure details"}),t.jsxs("dl",{className:"chat-message-failure-reference-meta",id:i,children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Kind"}),t.jsx("dd",{children:n.kind})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"ID"}),t.jsx("dd",{children:n.id})]}),n.label&&t.jsxs("div",{children:[t.jsx("dt",{children:"Label"}),t.jsx("dd",{children:n.label})]})]})]})]})}function an(n){if(!n||n.length===0)return null;const r=(w,j)=>{const z=w.status==="running",S=w.status==="completed"&&w.isError,Z=ba(w.args),C=va(w.result),O=z?Z:C?`result: ${C}`:Z?`args: ${Z}`:null,N=z?"running":S?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${z?" chat-tool-call--running":""}${S?" chat-tool-call--error":""}`,open:z,children:[t.jsxs("summary",{children:[t.jsx("span",{className:"chat-tool-call-status-dot","aria-hidden":"true"}),t.jsx("span",{className:"chat-tool-call-name",title:w.toolName,children:w.toolName}),O&&t.jsx("span",{className:"chat-tool-call-preview",title:O,children:O}),t.jsx("span",{className:"chat-tool-call-status-text",children:N})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[Z&&t.jsxs("div",{className:"chat-tool-call-row",children:[t.jsx("span",{className:"chat-tool-call-label",children:"args"}),t.jsx("span",{className:"chat-tool-call-value",children:Z})]}),C&&t.jsxs("div",{className:`chat-tool-call-row${S?" chat-tool-call-row--error":""}`,children:[t.jsx("span",{className:"chat-tool-call-label",children:"result"}),t.jsx("span",{className:"chat-tool-call-value",children:C})]})]})]},`${w.toolName}-${j}`)},d="chat-tool-calls";if(n.length===1)return t.jsxs("div",{className:d,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(Os,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:"Tool calls"})]}),r(n[0],0)]});const i=n.filter(w=>w.status==="running").length,g=n.filter(w=>w.status==="completed"&&w.isError).length,b=i>0,y=Array.from(new Set(n.map(w=>w.toolName))),f=y.slice(0,5),I=Math.max(0,y.length-f.length),J=I>0?`${f.join(", ")}, +${I} more`:f.join(", "),Q=b?`(${i} running)`:g>0?`(${g} ${g===1?"error":"errors"})`:null;return t.jsx("div",{className:d,"data-testid":"chat-tool-calls",children:t.jsxs("details",{className:"chat-tool-calls-group","data-testid":"chat-tool-calls-group",open:b,children:[t.jsxs("summary",{className:"chat-tool-calls-group-summary",children:[t.jsx(Os,{size:12,"aria-hidden":"true"}),t.jsxs("span",{className:"chat-tool-calls-count",children:[n.length," tool calls"]}),t.jsx("span",{className:"chat-tool-calls-names",title:J,children:J}),Q&&t.jsx("span",{className:"chat-tool-calls-group-status",children:Q})]}),n.map((w,j)=>r(w,j))]})})}const rn={p:({children:n,...r})=>t.jsx("p",{...r,children:Us(n)}),li:({children:n,...r})=>t.jsx("li",{...r,children:Us(n)}),pre:({children:n,...r})=>t.jsx("pre",{...r,className:"chat-markdown-pre",children:n}),code:({children:n,...r})=>{const d=typeof n=="string"?n:Sn.Children.toArray(n).join(""),i=Et(d);return i.length===1&&typeof i[0]=="string"?t.jsx("code",{...r,children:n}):t.jsx("code",{...r,children:i})},table:({children:n,...r})=>t.jsx("table",{...r,className:"chat-markdown-table",children:n})},st="__fn_agent__",wa=280,jt=180,Mt=500,Vs="fusion:chat-sidebar-width",os="fusion:chat-scope",Sa="fusion:chat-draft:";function qs(n,r){return r?`${Sa}${n}:${r}`:null}function Xs(n){if(!n)return"";try{return localStorage.getItem(n)??""}catch{return""}}const Ca=["image/png","image/jpeg","image/gif","image/webp","text/plain","application/json","text/yaml","text/markdown","text/csv","application/xml","text/x-log"];function Ys(n){const r=/(^|[\s])\/([^\s]*)$/.exec(n);if(!r)return null;const d=r[1]??"",i=r[2]??"",g=r.index+d.length;return{filter:i,start:g,end:n.length}}function ka(n,r){const d=n.slice(0,r),i=/(^|[\s\n])@([\w-]*)$/.exec(d);if(!i)return null;const g=i[2]??"",b=d.length-g.length-1;return{filter:g,start:b,end:r}}function Na(n){const r=n?.runtimeConfig;if(!r||typeof r!="object")return null;const d=Reflect.get(r,"modelProvider"),i=Reflect.get(r,"modelId");return typeof d!="string"||d.trim().length===0||typeof i!="string"||i.trim().length===0?null:{provider:d,modelId:i}}function Js(n,r,d){if(n?.modelProvider&&n?.modelId)return{provider:n.modelProvider,modelId:n.modelId};const i=Na(r??void 0);return i||(d.provider&&d.modelId?{provider:d.provider,modelId:d.modelId}:null)}function ja({projectId:n,onClose:r,onCreate:d}){const[i,g]=s.useState("agent"),{agents:b,loading:y}=ls(n),[f,I]=s.useState(""),{models:J,favoriteProviders:Q,favoriteModels:w,loading:j,refresh:z}=Zs(),[S,Z]=s.useState(""),[C,O]=s.useState(Q),[N,X]=s.useState(w);s.useEffect(()=>{O(Q)},[Q]),s.useEffect(()=>{X(w)},[w]);const E=s.useCallback(async k=>{const B=C,h=B.includes(k)?B.filter(p=>p!==k):[k,...B];O(h);try{await Bs({favoriteProviders:h,favoriteModels:N}),await z()}catch{O(B)}},[C,N,z]),_=s.useCallback(async k=>{const B=N,h=B.includes(k)?B.filter(p=>p!==k):[k,...B];X(h);try{await Bs({favoriteProviders:C,favoriteModels:h}),await z()}catch{X(B)}},[N,C,z]),T=k=>{if(k.preventDefault(),i==="agent"){if(!f)return;d({agentId:f});return}if(!S)return;const B=S.indexOf("/");if(B<=0)return;const te=S.slice(0,B),h=S.slice(B+1);d({agentId:st,modelProvider:te,modelId:h})},Y=i==="agent"?!f:!S;return t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:r,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:k=>k.stopPropagation(),children:[t.jsx("h3",{children:"New Chat"}),t.jsxs("div",{className:"chat-new-dialog-mode-toggle","data-testid":"chat-new-dialog-mode-toggle",children:[t.jsx("button",{type:"button",className:`chat-new-dialog-mode-btn${i==="agent"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-agent",onClick:()=>{g("agent"),Z("")},children:"Agent"}),t.jsx("button",{type:"button",className:`chat-new-dialog-mode-btn${i==="model"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-model",onClick:()=>{g("model"),I("")},children:"Model"})]}),t.jsxs("form",{onSubmit:T,children:[i==="agent"&&t.jsxs("label",{className:"chat-new-dialog-model-label",children:["Agent",y?t.jsx("div",{className:"chat-new-dialog-loading",children:"Loading agents..."}):b.length===0?t.jsx("div",{className:"chat-new-dialog-empty",children:"No agents available"}):t.jsx("div",{className:"chat-new-dialog-agent-list",children:b.map(k=>t.jsxs("button",{type:"button",className:`chat-new-dialog-agent-item${f===k.id?" chat-new-dialog-agent-item--selected":""}`,onClick:()=>I(k.id),"data-testid":`agent-option-${k.id}`,children:[t.jsx(ut,{size:16}),t.jsx("span",{className:"chat-new-dialog-agent-name",children:k.name}),t.jsx("span",{className:"chat-new-dialog-agent-role",children:k.role})]},k.id))})]}),i==="model"&&t.jsx("div",{className:"chat-new-dialog-model-dropdown","data-testid":"chat-new-dialog-model-section",children:j?t.jsx("div",{className:"chat-new-dialog-loading",children:"Loading models..."}):t.jsx(ia,{models:J,value:S,onChange:Z,label:"Model",placeholder:"Select a model",favoriteProviders:C,onToggleFavorite:E,favoriteModels:N,onToggleModelFavorite:_})}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:r,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:Y,children:"Create"})]})]})]})})}const cs=s.memo(function({message:r,forcePlain:d,agentName:i,hideAssistantIdentity:g,showAssistantModelTag:b,activeModelTag:y,activeModelProvider:f,activeSessionId:I,mentionAgentsByName:J,roomContext:Q,copyAction:w,onScrollToTop:j}){const z=r.role==="assistant",S=z?r.failureInfo:void 0,Z=z&&(!g||!!S),C=s.useMemo(()=>{if(z)return null;const X=r.content,E=/@([\w-]+)/g,_=[];let T=0,Y=E.exec(X);for(;Y;){const[k,B=""]=Y,te=Y.index;te>T&&_.push(X.slice(T,te));const h=B.replace(/_/g," ").toLowerCase(),p=J.get(h);if(p){const he=!!(Q&&!Q.memberIds.has(p.id)),c=he?`Not a member of ${Q?.roomName}`:void 0;_.push(t.jsxs("span",{className:`chat-mention-chip${he?" chat-mention-chip--non-member":""}`,title:c,"aria-label":c,children:["@",p.name.replace(/\s+/g,"_")]},`${p.id}-${te}`))}else _.push(k);T=te+k.length,Y=E.exec(X)}return T<X.length&&_.push(X.slice(T)),_.length===0?X:_},[z,r.content,J,Q]),O=s.useMemo(()=>{const X=r.attachments;if(!X||X.length===0)return null;const E=r.roomId?`/api/chat/rooms/${encodeURIComponent(r.roomId)}/attachments/`:I?`/api/chat/sessions/${encodeURIComponent(I)}/attachments/`:null;return E?t.jsx("div",{className:"chat-message-attachments",children:X.map(_=>{const T=_.mimeType.startsWith("image/"),Y=_.id||_.filename,k=`${E}${encodeURIComponent(_.filename)}`;return T?t.jsx("a",{className:"chat-message-attachment-link","data-testid":"chat-message-attachment",href:k,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{className:"chat-message-attachment",src:k,alt:_.originalName})},Y):t.jsxs("a",{className:"chat-message-attachment-file","data-testid":"chat-message-attachment",href:k,target:"_blank",rel:"noopener noreferrer",children:[t.jsx(na,{size:14}),t.jsx("span",{children:_.originalName})]},Y)})}):null},[r.attachments,r.roomId,I]),N=s.useMemo(()=>z?S?t.jsxs("div",{className:"chat-message-content chat-message-content--failure",children:[t.jsxs("div",{className:"chat-message-failure-summary-row",children:[t.jsx("span",{className:"status-dot status-dot--error","aria-hidden":"true"}),t.jsx("span",{className:"chat-message-failure-label",children:"Response failed"})]}),t.jsx("div",{className:"chat-message-failure-summary",children:S.summary}),(S.errorClass||S.code)&&t.jsxs("div",{className:"chat-message-failure-badges",children:[S.errorClass&&t.jsx("span",{className:"chat-message-failure-badge",children:S.errorClass}),S.code&&t.jsx("span",{className:"chat-message-failure-badge",children:S.code})]}),(S.detail||S.reference)&&t.jsxs("details",{className:"chat-message-failure-details",children:[t.jsxs("summary",{children:[t.jsx(aa,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Failure details"})]}),S.detail&&t.jsx("pre",{className:"chat-message-failure-detail",children:Et(S.detail)}),ya(S.reference)]})]}):d?t.jsx("div",{className:"chat-message-content chat-message-content--plain",children:r.content}):t.jsx("div",{className:"chat-message-content chat-message-content--markdown",children:t.jsx(en,{remarkPlugins:[tn],components:rn,children:r.content})}):null,[S,d,z,r.content]);return t.jsxs("div",{className:`chat-message chat-message--${r.role}${S?" chat-message--failure":""}`,"data-testid":`chat-message-${r.id}`,"data-message-id":r.id,children:[Z&&t.jsxs("div",{className:"chat-message-avatar",children:[f?t.jsx(dt,{provider:f,size:"sm"}):t.jsx(ut,{size:14}),t.jsx("span",{children:i}),b&&y&&t.jsx("span",{className:"chat-model-tag",children:y})]}),z?N:t.jsx("div",{className:"chat-message-content",children:C}),z&&!S&&(w||j)&&t.jsxs("div",{className:"chat-message-actions",children:[w,j&&t.jsx("button",{type:"button",className:"btn-icon chat-message-scroll-to-top-action","aria-label":"Scroll message to top","data-testid":`chat-message-scroll-to-top-${r.id}`,onClick:()=>j(r.id),children:t.jsx(ca,{size:14})})]}),an(r.toolCalls),r.thinkingOutput&&t.jsxs("details",{className:"chat-message-thinking",children:[t.jsx("summary",{children:"Thinking"}),t.jsx("pre",{className:"chat-message-thinking-content",children:Et(r.thinkingOutput)})]}),O,t.jsx("div",{className:"chat-message-time",children:nn(r.createdAt)})]})});function Ia({projectId:n,addToast:r,experimentalFeatures:d}){s.useEffect(()=>(At({view:"ChatView",trigger:is?"route-active":"remount",projectId:n,replayAttempted:!1}),is=!1,()=>{is=!0,At({view:"ChatView",trigger:"route-inactive",projectId:n,replayAttempted:!1})}),[n]);const{activeSession:i,sessionsLoading:g,messages:b,messagesLoading:y,isStreaming:f,streamingText:I,streamingThinking:J,streamingToolCalls:Q,selectSession:w,createSession:j,archiveSession:z,deleteSession:S,sendMessage:Z,stopStreaming:C,pendingMessage:O,clearPendingMessage:N,loadMoreMessages:X,hasMoreMessages:E,searchQuery:_,setSearchQuery:T,filteredSessions:Y,agentsMap:k}=ma(n,r),[B,te]=s.useState(!1),h=d?.chatRooms===!0,[p,he]=s.useState(()=>{try{if(localStorage.getItem(os)==="rooms"&&h)return"rooms"}catch{}return"direct"}),c=_n(n,r),{isUnread:re,markRead:se}=zn(n),[$,ue]=s.useState(()=>{const e=qs(p,p==="rooms"?c.activeRoom?.id:i?.id);return Xs(e)}),[be,G]=s.useState(null),[Ge,K]=s.useState(null),[We,ye]=s.useState(null),[Ie,oe]=s.useState(!0),[Se,Ce]=s.useState(wa),[Ve,Oe]=s.useState(!1),{agentsMap:ce}=ls(n),me=s.useMemo(()=>k.size>0?k:ce,[ce,k]),{defaultProvider:mt,defaultModelId:ie}=Zs(),le=s.useMemo(()=>({provider:mt,modelId:ie}),[ie,mt]),{skills:$e,loading:Tt}=Hn(n),[De,Pe]=s.useState(!1),[nt,qe]=s.useState(""),[Be,Le]=s.useState(0),[ke,Ne]=s.useState(""),[ve,l]=s.useState(!1),[u,v]=s.useState(0),[D,H]=s.useState(-1),[A,ee]=s.useState(!1),[M,U]=s.useState([]),[W,V]=s.useState(!1),[P,q]=s.useState(!1),[ne,je]=s.useState({}),[ht,Xe]=s.useState(!1),[ft,at]=s.useState(!1),{pushNav:ds}=Un(),[,gt]=s.useState(!1),[on,cn]=s.useState({top:0,left:0}),L=On({projectId:n}),It=s.useCallback(e=>{if(!e||!L.mentionActive)return;const a=e.getBoundingClientRect();cn({top:a.top-260,left:a.left+8})},[L.mentionActive]),us=s.useRef(null),ms=s.useRef(null),hs=s.useRef(null),fs=s.useRef(null),we=s.useRef(!1),$t=s.useRef(null),gs=s.useRef(null),Fe=s.useRef(null),pt=s.useRef(0),Dt=s.useRef(null),bt=s.useRef(null),Me=s.useRef(null),ge=s.useRef(null),Pt=s.useRef(null),vt=s.useRef(!1),Re=s.useRef(null),de=s.useRef(null),ps=s.useRef(null),bs=s.useRef([]),Ye=s.useRef(0),rt=s.useRef(new Map),R=Bn()==="mobile";s.useEffect(()=>{i?.id&&se("direct",i.id,i.lastMessageAt??i.updatedAt)},[i?.id,i?.lastMessageAt,i?.updatedAt,se]),s.useEffect(()=>{c.activeRoom?.id&&se("room",c.activeRoom.id,c.activeRoom.updatedAt)},[c.activeRoom?.id,c.activeRoom?.updatedAt,se]),s.useEffect(()=>{if(!i?.id||b.length===0)return;const e=b[b.length-1];se("direct",i.id,e?.createdAt??i.lastMessageAt??i.updatedAt)},[i?.id,i?.lastMessageAt,i?.updatedAt,se,b]),s.useEffect(()=>{if(!c.activeRoom?.id||c.messages.length===0)return;const e=c.messages[c.messages.length-1];se("room",c.activeRoom.id,e?.createdAt??c.activeRoom.updatedAt)},[se,c.activeRoom?.id,c.activeRoom?.updatedAt,c.messages]),s.useEffect(()=>{try{const e=localStorage.getItem(Vs);if(!e)return;const a=Number.parseInt(e,10);if(Number.isNaN(a))return;const o=Math.max(jt,Math.min(Mt,a));Ce(o)}catch{}},[]),s.useEffect(()=>{try{const e=localStorage.getItem(os);if(e==="direct"){he("direct");return}e==="rooms"&&h&&he("rooms")}catch{}},[h]),s.useEffect(()=>{if(!h&&p==="rooms"){he("direct");return}try{localStorage.setItem(os,p)}catch{}},[h,p]);const fe=qs(p,p==="rooms"?c.activeRoom?.id:i?.id),Lt=s.useRef(fe);s.useEffect(()=>{fe!==Lt.current&&(Lt.current=fe,ue(Xs(fe)))},[fe]),s.useEffect(()=>{if(!(!fe||Lt.current!==fe))try{if($){localStorage.setItem(fe,$);return}localStorage.removeItem(fe)}catch{}},[fe,$]);const ae=h&&p==="rooms"&&!!c.activeRoom,{keyboardOverlap:vs,keyboardOpen:Ft}=Kn({enabled:R&&(!!i||ae)}),xe=s.useMemo(()=>{const e=nt.trim().toLowerCase();return(e?$e.filter(o=>o.name.toLowerCase().includes(e)):$e).slice(0,10)},[$e,nt]),Je=s.useMemo(()=>Array.from(me.values()),[me]),Ae=s.useMemo(()=>!h||p!=="rooms"||!c.activeRoom?null:{roomId:c.activeRoom.id,roomName:c.activeRoom.name,memberIds:new Set(c.activeRoomMembers.map(e=>e.agentId))},[h,p,c.activeRoom,c.activeRoomMembers]),Ke=s.useMemo(()=>{const e=Je.filter(m=>Gn(m.name,ke));if(!Ae)return e;const a=e.filter(m=>Ae.memberIds.has(m.id));if(ke.trim().length===0)return a;const o=e.filter(m=>!Ae.memberIds.has(m.id));return[...a,...o]},[Je,ke,Ae]),_t=s.useMemo(()=>{const e=new Map;for(const a of Je)e.set(a.name.toLowerCase(),a);return e},[Je]);s.useEffect(()=>{Le(0)},[xe]),s.useEffect(()=>{v(0)},[ke,ve]),s.useEffect(()=>()=>{Me.current!==null&&window.clearTimeout(Me.current)},[]),s.useEffect(()=>{const e=ms.current;if(!e||!E||y)return;const a=new IntersectionObserver(o=>{o[0].isIntersecting&&X()},{threshold:.1});return a.observe(e),()=>a.disconnect()},[E,y,X]);const Qe=s.useCallback(()=>ae?c.activeRoom?.id??null:i?.id??null,[ae,c.activeRoom?.id,i?.id]),xs=s.useCallback((e,a)=>typeof CSS<"u"&&typeof CSS.escape=="function"?e.querySelector(`.chat-message[data-message-id="${CSS.escape(a)}"]`):e.querySelector(`.chat-message[data-message-id="${a.replace(/"/g,'\\"')}"]`),[]),xt=s.useCallback(()=>{const e=ge.current,a=Qe();if(!e||!a)return;const o=e.querySelector(".chat-message[data-message-id]"),m=o?.getAttribute("data-message-id")??null,x=o?o.offsetTop-e.scrollTop:0;bt.current={threadId:a,scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight,anchorMessageId:m,anchorOffset:x,wasPinnedBefore:!we.current}},[Qe]),ys=s.useCallback(()=>{const e=ge.current;if(!e)return;const o=e.scrollTop+e.clientHeight>=e.scrollHeight-50;q(!o),we.current=!o,xt()},[xt]),Ee=s.useCallback(e=>{if(!e.isConnected)return;let a=0,o=0,m=-1;const x=6,F=()=>{if(e.isConnected){if(e.scrollTop=e.scrollHeight,e.scrollHeight===m?o+=1:(o=0,m=e.scrollHeight),a+=1,a>=x||o>=2){q(!1),we.current=!1;return}window.requestAnimationFrame(F)}};F()},[]),it=ae?c.messages:b;s.useLayoutEffect(()=>{const e=ge.current,a=Qe(),o=bt.current;if(!e||!a||!o||o.threadId!==a||o.wasPinnedBefore)return;let m=o.scrollTop;if(o.anchorMessageId){const x=xs(e,o.anchorMessageId);x?m=x.offsetTop-o.anchorOffset:m=o.scrollTop+(e.scrollHeight-o.scrollHeight)}else m=o.scrollTop+(e.scrollHeight-o.scrollHeight);e.scrollTop=Math.max(0,m),we.current=!0,q(!0),bt.current=null},[it,Qe,xs]);const zt=s.useCallback(e=>{},[it.length,ae]),_e=s.useCallback(e=>{zt(e);const a=ge.current;a&&(bt.current=null,we.current=!1,Ee(a))},[Ee,zt]);s.useLayoutEffect(()=>{Fe.current!==null&&(window.clearTimeout(Fe.current),Fe.current=null);const e=ae?c.activeRoom?.id??null:i?.id??null;if(!e){$t.current=null;return}const a={threadId:e,loaded:ae?!c.messagesLoading:!y,hasMessages:ae?c.messages.length>0:b.length>0},o=$t.current,m=o?.threadId!==e,x=o?.threadId===e&&!o.loaded&&a.loaded,F=o?.threadId===e&&!o.hasMessages&&a.hasMessages;if(!(o===null||m||x||F))return;const Te=ge.current;if(Te)return zt(m?"thread-change":x?"finished-loading":F?"first-messages":"mount"),Ee(Te),ae||(Fe.current=window.setTimeout(()=>{if(Fe.current=null,we.current)return;const et=ge.current;et&&Ee(et)},250)),$t.current=a,()=>{Fe.current!==null&&(window.clearTimeout(Fe.current),Fe.current=null)}},[ae,c.activeRoom?.id,c.messages.length,c.messagesLoading,i?.id,b.length,y,Ee]),s.useEffect(()=>{!f||we.current||_e("streaming")},[f,I,J,_e]),s.useEffect(()=>{const e=Qe();if(!e){pt.current=0,Dt.current=null;return}if(Dt.current!==e){Dt.current=e,pt.current=it.length;return}const a=pt.current,o=it.length,m=o>a,x=!we.current;pt.current=o,m&&x&&_e("new-message")},[it,Qe,_e]),s.useEffect(()=>{vs<=0||!ge.current||_e("keyboard")},[vs,_e]),Wn(R&&Ft),s.useLayoutEffect(()=>{if(!R||!i&&!ae||typeof window>"u")return;const e=Pt.current,a=window.visualViewport;if(!e||!a)return;const o=x=>{if(!(x instanceof HTMLElement))return!1;if(x.tagName==="TEXTAREA")return!0;if(x.tagName!=="INPUT")return!1;const F=x.type.toLowerCase();return["","text","search","email","url","tel","password","number"].includes(F)},m=()=>{if(vt.current){e.classList.remove("chat-thread--keyboard-active");return}const x=Math.max(0,window.innerHeight-a.offsetTop-a.height),F=a.offsetTop||0;e.style.setProperty("--vv-height",`${a.height}px`),e.style.setProperty("--vv-offset-top",`${F}px`),e.style.setProperty("--keyboard-overlap",`${x}px`);const Ue=(x>0||F>0)&&o(document.activeElement);e.classList.toggle("chat-thread--keyboard-active",Ue)};return m(),a.addEventListener("resize",m),a.addEventListener("scroll",m),document.addEventListener("focusin",m),document.addEventListener("focusout",m),window.addEventListener("pageshow",m),document.addEventListener("visibilitychange",m),()=>{a.removeEventListener("resize",m),a.removeEventListener("scroll",m),document.removeEventListener("focusin",m),document.removeEventListener("focusout",m),window.removeEventListener("pageshow",m),document.removeEventListener("visibilitychange",m),e.classList.remove("chat-thread--keyboard-active")}},[i,R,ae]),s.useEffect(()=>{const e=()=>G(null);if(be)return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[be]),s.useEffect(()=>{if(!R||!Ft)return;const e=a=>{a.target?.closest(".chat-messages")||a.preventDefault()};return document.addEventListener("touchmove",e,{passive:!1}),()=>{document.removeEventListener("touchmove",e)}},[R,Ft]),s.useEffect(()=>{if(!R||!i)return;const e=()=>{const a=de.current;a&&document.activeElement===a&&(a.blur(),window.setTimeout(()=>{a.focus({preventScroll:!0})},0))};return document.addEventListener("visibilitychange",e),window.addEventListener("pageshow",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("pageshow",e)}},[R,i]),s.useEffect(()=>{const e=gs.current;if(gs.current=p,p!=="direct"||e!==null&&e!=="rooms")return;const a=ge.current;a&&(Ee(a),we.current=!1,q(!1))},[p,Ee]),s.useEffect(()=>{if(!i&&!ae||ae&&!R)return;const e=()=>{xt()},a=()=>{document.visibilityState==="visible"&&e()};return document.addEventListener("visibilitychange",a),window.addEventListener("pageshow",e),()=>{document.removeEventListener("visibilitychange",a),window.removeEventListener("pageshow",e)}},[R,i,ae,xt]),s.useEffect(()=>{if(ae||typeof ResizeObserver>"u")return;const e=ge.current;if(!e)return;const a=new ResizeObserver(()=>{we.current||Ee(e)});return a.observe(e),()=>{a.disconnect()}},[ae,Ee,i?.id,p]),s.useEffect(()=>{bs.current=M},[M]),s.useEffect(()=>()=>{for(const e of bs.current)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);for(const e of rt.current.values())window.clearTimeout(e);rt.current.clear()},[]);const yt=s.useCallback(e=>{if(!e||e.length===0)return;const a=[];for(const o of Array.from(e)){if(!Ca.includes(o.type))continue;const m=o.type.startsWith("image/");a.push({file:o,previewUrl:m?URL.createObjectURL(o):""})}a.length>0&&U(o=>[...o,...a])},[]),ln=s.useCallback(e=>{U(a=>{const o=a[e];return o?.previewUrl&&URL.revokeObjectURL(o.previewUrl),a.filter((m,x)=>x!==e)})},[]),dn=s.useCallback(e=>{const a=e.clipboardData?.files;if(!a||a.length===0)return;const o=Array.from(a).filter(m=>m.type.startsWith("image/"));o.length!==0&&yt(o)},[yt]),un=s.useCallback(async e=>{try{await j(e),te(!1),R&&oe(!1)}catch{r("Failed to create chat session","error")}},[j,r,R]),pe=s.useCallback(e=>{const a=e??de.current;a&&(a.style.height="auto",a.style.height=`${pa(a.scrollHeight)}px`,a.style.overflowY=ga(a.scrollHeight))},[]),ws=s.useCallback(e=>{de.current=e,e&&pe(e)},[pe]);s.useLayoutEffect(()=>{pe()},[p,$,i?.id,c.activeRoom?.id,pe]);const Ze=s.useCallback(()=>{if(ue(""),fe)try{localStorage.removeItem(fe)}catch{}Pe(!1),qe(""),l(!1),Ne(""),H(-1),U(e=>{for(const a of e)a.previewUrl&&URL.revokeObjectURL(a.previewUrl);return[]})},[fe]),Ht=s.useCallback(()=>{const e=$.trim(),a=M.map(o=>o.file);if(!(!e&&a.length===0||!i)){if(e==="/clear"||e==="/new"){Ze(),N(),C(),j({agentId:i.agentId,modelProvider:i.modelProvider??void 0,modelId:i.modelId??void 0}).catch(()=>{r("Failed to clear conversation","error")});return}Ze(),Z(e,a)}},[$,M,i,Ze,C,N,j,r,Z]),Ut=s.useCallback(async()=>{const e=$.trim();if(e){if(h&&p==="rooms"){if(!c.activeRoom)return;if(e==="/clear"||e==="/new"){Ze();try{await c.clearRoom(c.activeRoom.id)}catch{r("Failed to clear room conversation","error")}return}const a=$;Ze();try{await c.sendRoomMessage(e,{files:M.map(o=>o.file)})}catch(o){if(o instanceof Vn){const x=o.message.trim()?o.message:"Message sent, but assistant reply failed";r(`Message sent, but assistant reply failed: ${x}`,"error");return}ue(a);const m=o instanceof Error&&o.message.trim()?o.message:"Failed to send room message";r(m,"error")}return}Ht()}},[$,M,h,p,c,c.clearRoom,Ze,r,Ht]),Ot=s.useCallback(e=>{ue(a=>{const o=Ys(a);if(!o)return a;const m=`/skill:${e.name} `,x=a.slice(0,o.start)+m+a.slice(o.end);return window.requestAnimationFrame(()=>{de.current&&(pe(de.current),de.current.focus())}),x}),Pe(!1),qe(""),Le(0)},[pe]),wt=s.useCallback(e=>{const a=de.current;if(!a||D<0)return;const o=a.selectionStart??Ye.current,m=a.selectionEnd??o,x=Math.max(o,m),F=Math.min(D,x),Te=`${`@${e.name.replace(/\s+/g,"_")}`} `,et=$.slice(0,F)+Te+$.slice(x),tt=F+Te.length;ue(et),l(!1),Ne(""),v(0),H(-1),window.requestAnimationFrame(()=>{de.current&&(pe(de.current),de.current.focus(),de.current.setSelectionRange(tt,tt))})},[D,$,pe]),ot=s.useCallback((e,a)=>{const m=de.current?.selectionStart??Ye.current,x=$.lastIndexOf("#",m),F=x>=0?x+a.length:e.length;ue(e),L.dismissMention(),gt(!1),window.requestAnimationFrame(()=>{de.current&&(pe(de.current),de.current.focus(),de.current.setSelectionRange(F,F))})},[L,$,pe]),Ss=s.useCallback(e=>{if(Ye.current=e.currentTarget.selectionStart??Ye.current,L.mentionActive&&L.combinedItems.length>0){if(L.handleKeyDown(e,$),e.key==="Enter"||e.key==="Tab"){const a=L.combinedItems[L.selectedIndex];a?.kind==="task"?ot(L.selectTask(a.task,$),`#${a.task.id}`):a?.kind==="file"&&ot(L.selectFile(a.file,$),`#${a.file.path}`)}return}if(ve&&e.key==="ArrowDown"){e.preventDefault(),Ke.length>0&&v(a=>(a+1)%Ke.length);return}if(ve&&e.key==="ArrowUp"){e.preventDefault(),Ke.length>0&&v(a=>a===0?Ke.length-1:a-1);return}if(ve&&e.key==="Enter"){e.preventDefault();const a=Ke[u]??Ke[0];a&&wt(a);return}if(ve&&e.key==="Escape"){e.preventDefault(),l(!1),Ne(""),H(-1);return}if(De&&e.key==="ArrowDown"){e.preventDefault(),xe.length>0&&Le(a=>(a+1)%xe.length);return}if(De&&e.key==="ArrowUp"){e.preventDefault(),xe.length>0&&Le(a=>a===0?xe.length-1:a-1);return}if(De&&(e.key==="Enter"||e.key==="Tab")&&xe.length>0){e.preventDefault();const a=xe[Be]??xe[0];a&&Ot(a);return}if(De&&e.key==="Escape"){e.preventDefault(),Pe(!1);return}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Ut())},[ve,Ke,u,wt,De,xe,Be,Ot,Ut,L,ot,$]),St=s.useCallback((e,a)=>{const o=ka(e,a);if(o){l(!0),Ne(o.filter),H(o.start);return}l(!1),Ne(""),H(-1)},[]),Cs=s.useCallback(e=>{const a=e.target,o=a.value,m=a.selectionStart??o.length;pe(a),Ye.current=m,ue(o);const x=Ys(o);x?(Pe(!0),qe(x.filter)):(Pe(!1),qe("")),St(o,m),L.detectMention(o,m),gt(L.mentionActive),L.mentionActive&&It(a)},[St,pe]),Ct=s.useCallback(e=>{const a=e.currentTarget,o=a.selectionStart??a.value.length;Ye.current=o,St(a.value,o),L.detectMention(a.value,o),gt(L.mentionActive),L.mentionActive&&It(a)},[St,L,It]),ks=s.useCallback(e=>{e.key!=="Escape"&&Ct(e)},[Ct]),Ns=s.useCallback(()=>{typeof window<"u"&&window.innerWidth<=768&&(vt.current=!0,Re.current!==null&&window.clearTimeout(Re.current),Re.current=window.setTimeout(()=>{vt.current=!1,Re.current=null},450)),Me.current!==null&&window.clearTimeout(Me.current),Me.current=window.setTimeout(()=>{Pe(!1),l(!1),Ne(""),H(-1),gt(!1),L.dismissMention(),Me.current=null},120)},[L]),js=s.useCallback(()=>{vt.current=!1,Re.current!==null&&(window.clearTimeout(Re.current),Re.current=null),Me.current!==null&&(window.clearTimeout(Me.current),Me.current=null),typeof window<"u"&&window.innerWidth<=768&&queueMicrotask(()=>{(window.scrollY!==0||window.scrollX!==0)&&window.scrollTo(0,0)})},[]);s.useEffect(()=>()=>{Re.current!==null&&window.clearTimeout(Re.current)},[]);const mn=s.useCallback(async e=>{G(null);try{await z(e),r("Conversation archived","success")}catch{r("Failed to archive conversation","error")}},[z,r]),hn=s.useCallback(async e=>{K(null),G(null);try{await S(e),r("Conversation deleted","success")}catch{r("Failed to delete conversation","error")}},[S,r]),ct=s.useCallback(e=>{try{localStorage.setItem(Vs,String(e))}catch{}},[]),fn=s.useCallback(e=>{if(R)return;e.preventDefault(),e.stopPropagation();const a=e.currentTarget;typeof a.setPointerCapture=="function"&&a.setPointerCapture(e.pointerId);const o=e.clientX,m=Se;let x=m;document.body.style.userSelect="none";const F=Te=>{const et=Te.clientX-o,tt=Math.max(jt,Math.min(Mt,m+et));x=tt,Ce(tt),ct(tt)},Ue=Te=>{typeof a.releasePointerCapture=="function"&&a.releasePointerCapture(Te.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",F),document.removeEventListener("pointerup",Ue),ct(x)};document.addEventListener("pointermove",F),document.addEventListener("pointerup",Ue)},[R,ct,Se]),gn=s.useCallback(e=>{if(R||e.key!=="ArrowLeft"&&e.key!=="ArrowRight")return;e.preventDefault();const a=e.shiftKey?50:10,o=e.key==="ArrowLeft"?-a:a,m=Math.max(jt,Math.min(Mt,Se+o));Ce(m),ct(m)},[R,ct,Se]),Ms=s.useCallback(e=>{const a=Y.find(o=>o.id===e);se("direct",e,a?.lastMessageAt??a?.updatedAt),w(e),Xe(!1),R&&oe(!1)},[Y,R,se,w]),Bt=s.useCallback(()=>{w(""),oe(!0),Xe(!1)},[w]),Kt=s.useCallback(()=>{c.selectRoom(null),oe(!0),Xe(!1)},[c]),pn=()=>t.jsxs("div",{className:"chat-empty-state",children:[t.jsx(ra,{size:48,strokeWidth:1.5}),t.jsx("h2",{children:"Start a new conversation"}),t.jsxs("button",{className:"btn btn-primary",onClick:()=>te(!0),children:[t.jsx(lt,{size:16}),"New Chat"]})]}),Gt=Js(i,i?.agentId?me.get(i.agentId)??null:null,le),ze=Ws(Gt?.provider,Gt?.modelId),He=Gt?.provider??null,Wt=!!(i||f||b.length>0),kt=p==="rooms"?ae:!!i,Rs=s.useRef(kt);s.useEffect(()=>{const e=Rs.current;Rs.current=kt,R&&(e||!kt||ds({type:"view",revert:p==="rooms"?Kt:Bt}))},[p,Bt,Kt,kt,R,ds]);const Vt=i?.agentId===st?ze??"Fusion":i?.title||me.get(i?.agentId??"")?.name||i?.agentId||"Chat",As=!!(ze&&ze!==Vt),bn=R&&p==="direct"&&!!i,qt=me.get(i?.agentId??"")?.name||(i?.agentId===st?ze??"Fusion":i?.agentId?.slice(0,30)??"Fusion"),Xt=!1,Yt=i?.agentId===st,vn=O.length>50?`${O.slice(0,50)}…`:O,xn=s.useCallback(()=>{ee(e=>!e)},[]);s.useEffect(()=>{if(!ht)return;const e=a=>{hs.current?.contains(a.target)||Xe(!1)};return document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}},[ht]),s.useEffect(()=>{if(!ft)return;const e=o=>{fs.current?.contains(o.target)||at(!1)},a=o=>{o.key==="Escape"&&at(!1)};return document.addEventListener("mousedown",e),document.addEventListener("keydown",a),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",a)}},[ft]),s.useEffect(()=>{(!R||p!=="direct"||Ie)&&Xe(!1)},[R,p,Ie]),s.useEffect(()=>{at(!1)},[c.activeRoom?.id]);const Jt=s.useCallback((e,a)=>{const o=rt.current.get(e);o&&window.clearTimeout(o),je(x=>({...x,[e]:a}));const m=window.setTimeout(()=>{je(x=>{const{[e]:F,...Ue}=x;return Ue}),rt.current.delete(e)},2e3);rt.current.set(e,m)},[]),Es=s.useCallback(async(e,a)=>{try{if(!navigator.clipboard?.writeText)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(a),Jt(e,"success")}catch{Jt(e,"error")}},[Jt]),yn=s.useCallback((e,a=!1)=>a?t.jsx("div",{className:"chat-message-content chat-message-content--plain",children:e}):t.jsx("div",{className:"chat-message-content chat-message-content--markdown",children:t.jsx(en,{remarkPlugins:[tn],components:rn,children:e})}),[]),Qt=i?.agentId===st,Zt=s.useCallback((e,a,o)=>t.jsx("button",{type:"button",className:`btn-icon chat-message-copy-action${ne[e]==="success"?" chat-message-copy-action--success":""}${ne[e]==="error"?" chat-message-copy-action--error":""}`,"data-testid":o??`chat-copy-response-${e}`,"aria-label":ne[e]==="success"?"Response copied":ne[e]==="error"?"Copy failed":"Copy response",onClick:()=>{Es(e,a)},children:ne[e]==="success"?t.jsx(qn,{size:14}):t.jsx(Xn,{size:14})}),[ne,Es]),es=s.useCallback(e=>{const a=ge.current;if(!a)return;const o=`[data-testid="chat-message-${e}"]`,m=a.querySelector(o);if(!m)return;const x=m.getBoundingClientRect().top-a.getBoundingClientRect().top+a.scrollTop,F=typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;a.scrollTo({top:x,behavior:F?"auto":"smooth"})},[]);return t.jsxs("div",{className:"chat-view",children:[t.jsxs("div",{className:`chat-sidebar${Ie?"":" chat-sidebar--hidden"}`,style:R?void 0:{width:`${Se}px`},children:[h&&t.jsxs("div",{className:"chat-sidebar-scope-toggle",role:"tablist","data-testid":"chat-sidebar-scope-toggle",children:[t.jsx("button",{type:"button",role:"tab",className:`chat-sidebar-scope-btn${p==="direct"?" chat-sidebar-scope-btn--active":""}`,"aria-selected":p==="direct","data-testid":"chat-sidebar-scope-direct",onClick:()=>he("direct"),children:"Direct"}),t.jsx("button",{type:"button",role:"tab",className:`chat-sidebar-scope-btn${p==="rooms"?" chat-sidebar-scope-btn--active":""}`,"aria-selected":p==="rooms","data-testid":"chat-sidebar-scope-rooms",onClick:()=>he("rooms"),children:"Rooms"})]}),!h||p==="direct"?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"chat-sidebar-search-container",children:t.jsxs("div",{className:"chat-sidebar-search-wrapper",children:[t.jsx(Yn,{size:14,className:"chat-sidebar-search-icon"}),t.jsx("input",{type:"text",className:"chat-sidebar-search",placeholder:"Search conversations...",value:_,onChange:e=>T(e.target.value),"data-testid":"chat-search-input"})]})}),t.jsx("div",{className:"chat-session-list chat-sidebar-list",children:g?t.jsx("div",{className:"chat-empty-state chat-empty-state--padded",children:"Loading..."}):Y.length===0?t.jsx("div",{className:"chat-empty-state chat-empty-state--padded",children:"No conversations yet"}):Y.map(e=>{const a=i?.id===e.id,o=!a&&re("direct",e.id,e.lastMessageAt??e.updatedAt),m=Js(e,me.get(e.agentId)??null,le),x=Ws(m?.provider,m?.modelId)??"Fusion";return t.jsxs("div",{className:`chat-session-item${a?" chat-session-item--active":""}`,onClick:()=>Ms(e.id),onContextMenu:F=>{F.preventDefault(),G({sessionId:e.id,x:F.clientX,y:F.clientY})},"data-testid":`chat-session-${e.id}`,children:[t.jsx("button",{className:"chat-session-delete-btn",onClick:F=>{F.stopPropagation(),K(e.id)},"data-testid":"chat-session-delete-btn","aria-label":"Delete conversation",children:t.jsx(ns,{size:14})}),t.jsxs("div",{className:"chat-session-title",children:[e.title||"Untitled",o?t.jsx("span",{className:"chat-unread-dot","data-testid":`chat-unread-dot-${e.id}`,"aria-label":"Unread messages"}):null]}),t.jsx("div",{className:"chat-session-preview",children:e.lastMessagePreview||"No messages"}),t.jsxs("div",{className:"chat-session-meta",children:[t.jsxs("span",{className:"chat-session-meta-model",children:[m?.provider?t.jsx(dt,{provider:m.provider,size:"sm"}):null,t.jsx("span",{children:me.get(e.agentId)?.name||(e.agentId===st?x:e.agentId.slice(0,30))})]}),t.jsx("span",{children:e.updatedAt?nn(e.updatedAt):""})]})]},e.id)})})]}):t.jsxs("div",{className:"chat-sidebar-rooms","data-testid":"chat-sidebar-rooms",children:[!R&&t.jsx("div",{className:"chat-sidebar-rooms-header","data-testid":"chat-sidebar-rooms-header",children:t.jsxs("button",{type:"button",className:"btn btn-sm btn-primary","data-testid":"chat-create-room-btn",onClick:()=>Oe(!0),children:[t.jsx(lt,{size:14}),"Create room"]})}),c.rooms.length===0?t.jsx("div",{className:"chat-sidebar-rooms-empty","data-testid":"chat-sidebar-rooms-empty",children:"No rooms yet."}):t.jsx("div",{className:"chat-session-list chat-sidebar-list",children:c.rooms.map(e=>{const a=c.activeRoom?.id===e.id,o=!a&&re("room",e.id,e.updatedAt);return t.jsxs("div",{role:"button",tabIndex:0,className:`chat-room-item${a?" chat-room-item--active":""}`,"data-testid":`chat-room-item-${e.slug}`,onClick:()=>{se("room",e.id,e.updatedAt),c.selectRoom(e.id),R&&oe(!1)},onKeyDown:m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),se("room",e.id,e.updatedAt),c.selectRoom(e.id),R&&oe(!1))},children:[t.jsxs("span",{className:"chat-room-item-details",children:[t.jsxs("span",{className:"chat-room-item-name-row",children:[t.jsxs("span",{className:"chat-room-item-name",children:["#",e.name]}),o?t.jsx("span",{className:"chat-unread-dot","data-testid":`chat-unread-dot-${e.id}`,"aria-label":"Unread messages"}):null]}),a?t.jsxs("span",{className:"chat-room-item-meta",children:[c.activeRoomMembers.length," ",c.activeRoomMembers.length===1?"member":"members"]}):null]}),t.jsx("button",{type:"button",className:"btn-icon chat-room-item-delete","data-testid":`chat-room-delete-${e.slug}`,"aria-label":`Delete room ${e.name}`,onClick:m=>{m.stopPropagation(),ye(e.id)},children:t.jsx(ns,{size:14})})]},e.id)})})]}),p==="rooms"?R?t.jsx("div",{className:"chat-sidebar-footer",children:t.jsxs("button",{type:"button",className:"btn btn-sm btn-primary chat-sidebar-footer-btn","data-testid":"chat-create-room-btn",onClick:()=>Oe(!0),children:[t.jsx(lt,{size:14}),"Create room"]})}):null:t.jsx("div",{className:"chat-sidebar-footer",children:t.jsxs("button",{className:"btn btn-sm btn-primary chat-sidebar-footer-btn",onClick:()=>te(!0),"data-testid":"chat-new-btn",children:[t.jsx(lt,{size:14}),"New Chat"]})})]}),!R&&Ie&&t.jsx("div",{className:"chat-sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":jt,"aria-valuemax":Mt,"aria-valuenow":Se,"aria-label":"Resize chat sidebar",tabIndex:0,onPointerDown:fn,onKeyDown:gn}),be&&t.jsxs("div",{className:"chat-session-context-menu",style:{top:be.y,left:be.x},onClick:e=>e.stopPropagation(),children:[t.jsxs("button",{onClick:()=>mn(be.sessionId),"data-testid":"chat-context-archive",children:[t.jsx(Jn,{size:14}),"Archive"]}),t.jsxs("button",{onClick:()=>{G(null),K(be.sessionId)},"data-testid":"chat-context-delete",children:[t.jsx(ns,{size:14}),"Delete"]})]}),Ge&&t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:()=>K(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{children:"Delete Conversation?"}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:"This action cannot be undone. All messages in this conversation will be permanently deleted."}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>K(null),children:"Cancel"}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>void hn(Ge),children:"Delete"})]})]})}),h&&We&&t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:()=>ye(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{children:"Delete Room?"}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:"This action cannot be undone. This room and all its messages will be permanently deleted."}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>ye(null),children:"Cancel"}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>{(async()=>{try{await c.deleteRoom(We),ye(null)}catch{r("Failed to delete room","error")}})()},children:"Delete"})]})]})}),h&&p==="rooms"?t.jsxs("div",{ref:Pt,className:"chat-thread",children:[c.activeRoom?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"chat-room-thread-header",children:[R&&t.jsx("button",{className:"btn-icon",onClick:Kt,"data-testid":"chat-back-btn",children:t.jsx(Fs,{size:16})}),t.jsxs("div",{className:"chat-room-switcher-menu",ref:fs,children:[t.jsxs("button",{type:"button",className:"chat-room-switcher-trigger","data-testid":"chat-room-switcher-trigger","aria-haspopup":"menu","aria-expanded":ft,onClick:()=>at(e=>!e),children:[t.jsxs("span",{className:"chat-thread-header-title",children:["#",c.activeRoom.name]}),t.jsx(Nt,{size:16,"aria-hidden":"true"})]}),ft&&t.jsx("div",{role:"menu",className:"chat-room-switcher-dropdown","data-testid":"chat-room-switcher-dropdown",children:c.rooms.map(e=>t.jsxs("button",{type:"button",role:"menuitem",className:`chat-room-switcher-option${e.id===c.activeRoom?.id?" chat-room-switcher-option--active":""}`,"data-testid":`chat-room-switcher-option-${e.id}`,onClick:()=>{se("room",e.id,e.updatedAt),c.selectRoom(e.id),at(!1)},children:["#",e.name]},e.id))})]}),t.jsx("div",{className:"chat-room-thread-members",children:c.activeRoomMembers.map(e=>t.jsx(Qs,{agent:me.get(e.agentId)??{id:e.agentId,name:e.agentId.slice(0,30)}},e.agentId))})]}),t.jsxs("div",{className:"chat-messages",ref:ge,onScroll:ys,children:[c.messagesLoading?t.jsx("div",{className:"chat-empty-state",children:"Loading messages..."}):c.messages.length===0?t.jsx("div",{className:"chat-empty-state",children:"No messages yet. Start the conversation!"}):c.messages.map(e=>{const a=e.senderAgentId?me.get(e.senderAgentId)?.name??e.senderAgentId.slice(0,30):"You",o={id:e.id,sessionId:e.roomId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput??void 0,toolCalls:void 0,fallbackInfo:void 0,attachments:e.attachments,createdAt:e.createdAt};return t.jsx(cs,{message:o,forcePlain:A,agentName:a,hideAssistantIdentity:!1,showAssistantModelTag:!1,activeModelTag:null,activeModelProvider:null,activeSessionId:c.activeRoom?.id??null,mentionAgentsByName:_t,roomContext:Ae,onScrollToTop:es},e.id)}),t.jsx("div",{ref:us})]}),c.activeRoom&&P&&t.jsxs("button",{type:"button",className:"btn btn-sm chat-jump-to-latest","data-testid":"chat-jump-to-latest",onClick:()=>_e("fab-click"),children:[t.jsx(Nt,{size:14}),"Latest"]})]}):t.jsx("div",{className:"chat-room-empty-pane","data-testid":"chat-rooms-empty-pane",children:"Select a room or create one"}),c.activeRoom&&t.jsx("div",{className:"chat-input-area",children:t.jsxs("div",{className:"chat-input-row",children:[t.jsxs("div",{className:"chat-input-wrapper",children:[t.jsx("textarea",{ref:ws,className:"chat-input-textarea",placeholder:"Type a message...",value:$,onChange:Cs,onKeyDown:Ss,onKeyUp:ks,onClick:Ct,onBlur:Ns,onFocus:js,onTouchStart:e=>{typeof window>"u"||window.innerWidth>768||_s()&&document.activeElement!==e.currentTarget&&(e.preventDefault(),e.currentTarget.focus({preventScroll:!0}))},rows:1,"data-testid":"chat-input"}),t.jsx(zs,{agents:Je,filter:ke,highlightedIndex:u,visible:ve,onSelect:wt,position:"below",roomMemberIds:Ae?.memberIds,roomName:Ae?.roomName})]}),t.jsx("button",{type:"button",className:"chat-input-send",onPointerDown:e=>{e.pointerType&&e.pointerType!=="mouse"&&e.preventDefault()},onMouseDown:e=>{e.preventDefault()},onClick:()=>{Ut()},disabled:!$.trim(),"data-testid":"chat-send-btn",style:{touchAction:"manipulation"},children:t.jsx(Hs,{size:16})})]})})]}):t.jsxs("div",{ref:Pt,className:"chat-thread",children:[(Wt||!R)&&t.jsxs("div",{className:"chat-thread-header",children:[R&&Wt&&t.jsx("button",{className:"btn-icon",onClick:Bt,"data-testid":"chat-back-btn",children:t.jsx(Fs,{size:16})}),t.jsx("div",{className:"chat-thread-header-identity","data-testid":"chat-thread-header-identity",children:bn?t.jsxs("div",{className:"chat-mobile-session-menu",ref:hs,children:[t.jsxs("button",{type:"button",className:"btn chat-mobile-session-trigger","data-testid":"chat-mobile-session-trigger","aria-haspopup":"menu","aria-expanded":ht,onClick:()=>Xe(e=>!e),children:[He?t.jsx(dt,{provider:He,size:"md"}):t.jsx(ut,{size:16}),t.jsx("span",{className:"chat-thread-header-title",children:Vt}),As&&t.jsx("span",{className:"chat-model-tag",children:ze}),t.jsx(Nt,{size:16,"aria-hidden":"true"})]}),ht&&t.jsx("div",{className:"chat-mobile-session-dropdown",role:"menu","data-testid":"chat-mobile-session-dropdown",children:Y.map(e=>t.jsx("button",{type:"button",role:"menuitem",className:`chat-mobile-session-option${i?.id===e.id?" chat-mobile-session-option--active":""}`,"data-testid":`chat-mobile-session-option-${e.id}`,onClick:()=>Ms(e.id),children:t.jsx("span",{className:"chat-mobile-session-option-title",children:e.title||"Untitled"})},e.id))})]}):t.jsxs(t.Fragment,{children:[He?t.jsx(dt,{provider:He,size:"md"}):t.jsx(ut,{size:16}),t.jsx("span",{className:"chat-thread-header-title",children:Vt}),As&&t.jsx("span",{className:"chat-model-tag",children:ze})]})}),Wt&&t.jsx("button",{type:"button",className:`chat-thread-header-render-toggle${A?" chat-thread-header-render-toggle--plain":""}`,"data-testid":"chat-thread-render-toggle","aria-label":A?"Show all messages as rendered Markdown":"Show all messages as plain text",onClick:xn,children:A?t.jsx(Qn,{size:14}):t.jsx(Zn,{size:14})}),!R&&t.jsxs("button",{className:"btn btn-sm btn-primary chat-thread-header-new-chat",onClick:()=>te(!0),"data-testid":"chat-thread-new-chat-btn",children:[t.jsx(lt,{size:14}),"New Chat"]})]}),t.jsxs("div",{className:"chat-messages",ref:ge,onScroll:ys,children:[t.jsx("div",{ref:ms,className:"chat-load-more-sentinel",children:E&&y&&t.jsx("div",{className:"chat-loading-older",children:"Loading older messages…"})}),f?t.jsxs(t.Fragment,{children:[b.map(e=>t.jsx(cs,{message:e,forcePlain:A,agentName:qt,hideAssistantIdentity:Yt,showAssistantModelTag:Xt,activeModelTag:ze,activeModelProvider:He,activeSessionId:i?.id??null,mentionAgentsByName:_t,roomContext:null,copyAction:Qt&&e.role==="assistant"?Zt(e.id,e.content):void 0,onScrollToTop:es},e.id)),t.jsxs("div",{className:"chat-message chat-message--assistant chat-message--streaming",children:[!Yt&&t.jsxs("div",{className:"chat-message-avatar",children:[He?t.jsx(dt,{provider:He,size:"sm"}):t.jsx(ut,{size:14}),t.jsx("span",{children:qt}),Xt]}),I?yn(I,A):t.jsx("div",{className:"chat-message-content chat-message-content--waiting",children:J?"Thinking…":"Connecting…"}),Qt&&I&&Zt("__streaming__",I,"chat-copy-response-streaming"),an(Q),J&&t.jsxs("details",{className:"chat-message-thinking",children:[t.jsx("summary",{children:"Thinking"}),t.jsx("pre",{className:"chat-message-thinking-content",children:Et(J)})]}),t.jsxs("div",{className:"chat-typing-indicator",children:[t.jsx("span",{}),t.jsx("span",{}),t.jsx("span",{})]})]})]}):y?t.jsx("div",{className:"chat-empty-state",children:"Loading messages..."}):b.length===0&&!i?pn():b.length===0&&i?t.jsx("div",{className:"chat-empty-state",children:"No messages yet. Start the conversation!"}):t.jsx(t.Fragment,{children:b.map(e=>t.jsx(cs,{message:e,forcePlain:A,agentName:qt,hideAssistantIdentity:Yt,showAssistantModelTag:Xt,activeModelTag:ze,activeModelProvider:He,activeSessionId:i?.id??null,mentionAgentsByName:_t,roomContext:null,copyAction:Qt&&e.role==="assistant"?Zt(e.id,e.content):void 0,onScrollToTop:es},e.id))}),t.jsx("div",{ref:us})]}),P&&t.jsxs("button",{type:"button",className:"btn btn-sm chat-jump-to-latest","data-testid":"chat-jump-to-latest",onClick:()=>_e("fab-click"),children:[t.jsx(Nt,{size:14}),"Latest"]}),i&&t.jsxs("div",{className:"chat-input-area",children:[t.jsx("input",{ref:ps,type:"file",accept:"image/*,.txt,.json,.yaml,.yml,.log,.csv,.xml,.md",multiple:!0,style:{display:"none"},onChange:e=>{yt(e.target.files),e.target.value=""}}),De&&t.jsx("div",{className:"chat-skill-menu","data-testid":"chat-skill-menu",role:"listbox","aria-label":"Skill suggestions",children:Tt?t.jsx("div",{className:"chat-skill-menu-empty",children:"Loading skills…"}):xe.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:nt?"No skills found":"No skills available"}):xe.map((e,a)=>t.jsxs("button",{type:"button",role:"option","aria-selected":a===Be,className:`chat-skill-menu-item${a===Be?" chat-skill-menu-item--highlighted":""}`,onMouseDown:o=>o.preventDefault(),onMouseEnter:()=>Le(a),onClick:()=>Ot(e),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:e.name}),t.jsx("span",{className:"chat-skill-menu-item-description",title:e.relativePath,children:e.relativePath})]},e.id))}),M.length>0&&t.jsx("div",{className:"chat-attachment-previews","data-testid":"chat-attachment-previews",children:M.map((e,a)=>t.jsxs("div",{className:"chat-attachment-preview","data-testid":`chat-attachment-preview-${a}`,children:[e.previewUrl?t.jsx("img",{src:e.previewUrl,alt:e.file.name}):t.jsx("span",{className:"chat-attachment-preview-name",children:e.file.name}),t.jsx("button",{type:"button",className:"chat-attachment-remove",onClick:()=>ln(a),"data-testid":`chat-attachment-remove-${a}`,"aria-label":`Remove ${e.file.name}`,children:"×"})]},e.previewUrl||`${e.file.name}-${a}`))}),t.jsxs("div",{className:"chat-input-row",children:[t.jsx("button",{type:"button",className:"btn-icon chat-attach-btn","data-testid":"chat-attach-btn","aria-label":"Attach files",onClick:()=>ps.current?.click(),children:t.jsx(ea,{size:16})}),t.jsxs("div",{className:`chat-input-wrapper${W?" chat-input-wrapper--dragover":""}`,onDragOver:e=>{e.preventDefault(),V(!0)},onDragLeave:()=>V(!1),onDrop:e=>{e.preventDefault(),V(!1),yt(e.dataTransfer.files)},children:[t.jsx("textarea",{ref:ws,className:"chat-input-textarea",placeholder:"Type a message...",value:$,onChange:Cs,onKeyDown:Ss,onKeyUp:ks,onClick:Ct,onBlur:Ns,onFocus:js,onPaste:dn,onTouchStart:e=>{typeof window>"u"||window.innerWidth>768||_s()&&document.activeElement!==e.currentTarget&&(e.preventDefault(),e.currentTarget.focus({preventScroll:!0}))},rows:1,"data-testid":"chat-input"}),t.jsx(zs,{agents:Je,filter:ke,highlightedIndex:u,visible:ve,onSelect:wt,position:"below",roomMemberIds:Ae?.memberIds,roomName:Ae?.roomName}),t.jsx(ta,{visible:L.mentionActive&&!ve,position:on,tasks:L.tasks,files:L.files,selectedIndex:L.selectedIndex,onSelectTask:e=>{ot(L.selectTask(e,$),`#${e.id}`)},onSelectFile:e=>{ot(L.selectFile(e,$),`#${e.path}`)},loading:L.loading}),O&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${vn}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:N,children:"×"})]})]}),f?t.jsx("button",{className:"chat-input-stop",onClick:C,"aria-label":"Stop generation","data-testid":"chat-stop-btn",children:t.jsx(sa,{size:14})}):t.jsx("button",{type:"button",className:"chat-input-send",onPointerDown:e=>{e.pointerType&&e.pointerType!=="mouse"&&e.preventDefault()},onMouseDown:e=>{e.preventDefault()},onClick:()=>{Ht()},disabled:!$.trim()&&M.length===0,"data-testid":"chat-send-btn",style:{touchAction:"manipulation"},children:t.jsx(Hs,{size:16})})]})]})]}),h&&t.jsx(fa,{isOpen:Ve,onClose:()=>Oe(!1),projectId:n,existingRoomNames:c.rooms.map(e=>e.name),onCreate:async e=>{await c.createRoom({name:e.name,memberAgentIds:e.memberAgentIds}),p!=="rooms"&&he("rooms"),Oe(!1),R&&oe(!1)}}),B&&t.jsx(ja,{projectId:n,onClose:()=>te(!1),onCreate:un})]})}export{Ia as ChatView,pa as clampChatInputHeight,ga as resolveChatInputOverflowY,Js as resolveSessionProvider};