@runfusion/fusion 0.28.1 → 0.30.0

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 (88) hide show
  1. package/dist/bin.js +13194 -3642
  2. package/dist/client/assets/AgentDetailView-CY-O6VkV.css +1 -0
  3. package/dist/client/assets/AgentDetailView-Cu4TgvBn.js +18 -0
  4. package/dist/client/assets/AgentPermissionPolicyEditor-Ceg2Dszn.js +6 -0
  5. package/dist/client/assets/AgentPermissionPolicyEditor-CthjqUL_.css +1 -0
  6. package/dist/client/assets/AgentsView-BI_CESkd.css +1 -0
  7. package/dist/client/assets/AgentsView-CIH4Acck.js +34 -0
  8. package/dist/client/assets/ChatView-DqJoFquZ.js +1 -0
  9. package/dist/client/assets/DevServerView-Bd8JZ-3C.js +1 -0
  10. package/dist/client/assets/{DirectoryPicker-BfShQutV.js → DirectoryPicker-BOGqZNiq.js} +1 -1
  11. package/dist/client/assets/DocumentsView-B-ELcw4o.js +1 -0
  12. package/dist/client/assets/EvalsView-Ccl9QBYN.js +1 -0
  13. package/dist/client/assets/{ExperimentalAgentOnboardingModal-CtR7eRBv.js → ExperimentalAgentOnboardingModal-BM7EnSvJ.js} +1 -1
  14. package/dist/client/assets/ExperimentalAgentOnboardingModal-BNpveCEk.css +1 -0
  15. package/dist/client/assets/{InsightsView-BGbXkJpz.js → InsightsView-DLF49bzu.js} +3 -3
  16. package/dist/client/assets/{MemoryView-CRbaCcG_.js → MemoryView-CE1D9euM.js} +2 -2
  17. package/dist/client/assets/{NodesView-Hjxwv7rE.js → NodesView-Zxusnhxu.js} +2 -2
  18. package/dist/client/assets/{PiExtensionsManager-ckNj1Wvv.js → PiExtensionsManager-BlMmxtLZ.js} +2 -2
  19. package/dist/client/assets/PluginManager-BJQXdUmV.css +1 -0
  20. package/dist/client/assets/PluginManager-D4eZ0zA4.js +1 -0
  21. package/dist/client/assets/ReliabilityView-KmH60I_5.js +1 -0
  22. package/dist/client/assets/ReliabilityView-rxA_HgEG.css +1 -0
  23. package/dist/client/assets/ResearchView-C14Zh7c9.js +1 -0
  24. package/dist/client/assets/ResearchView-DTh8FLUm.css +1 -0
  25. package/dist/client/assets/SettingsModal-BAx4gt2A.css +1 -0
  26. package/dist/client/assets/{SettingsModal-Bqfq-gnu.js → SettingsModal-DRnZ6eBW.js} +1 -1
  27. package/dist/client/assets/SettingsModal-c1QwWno0.js +31 -0
  28. package/dist/client/assets/SettingsModal-sp7SNwS9.css +1 -0
  29. package/dist/client/assets/SetupWizardModal-BmmRM3g-.js +1 -0
  30. package/dist/client/assets/SkillsView-CUbSBeZ2.css +1 -0
  31. package/dist/client/assets/SkillsView-DWVtT2-8.js +1 -0
  32. package/dist/client/assets/StashRecoveryView-CKkaWzzc.js +1 -0
  33. package/dist/client/assets/{TodoView-CDtkPdrq.js → TodoView-hbD0NOCY.js} +2 -2
  34. package/dist/client/assets/dashboard-view-VNPB3ca0.js +21 -0
  35. package/dist/client/assets/{folder-open-D8Qfxakh.js → folder-open-BTN2_Wuv.js} +1 -1
  36. package/dist/client/assets/index-CZFBq256.css +1 -0
  37. package/dist/client/assets/index-DzSLVOnp.js +695 -0
  38. package/dist/client/assets/{upload-BHiYszS2.js → upload-euJEs_N2.js} +1 -1
  39. package/dist/client/assets/{users-Ch_Fnf5M.js → users-B7miEHCZ.js} +1 -1
  40. package/dist/client/assets/vendor-codemirror-jBKmHyH0.js +27 -0
  41. package/dist/client/index.html +3 -2
  42. package/dist/client/version.json +1 -1
  43. package/dist/droid-cli/package.json +1 -1
  44. package/dist/extension.js +9987 -1944
  45. package/dist/pi-claude-cli/package.json +1 -1
  46. package/dist/plugins/fusion-plugin-cli-printing-press/package.json +1 -1
  47. package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/registration.test.ts +20 -3
  48. package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/workflow-integration.test.ts +103 -8
  49. package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/workflow-steps-verdict-contract.test.ts +42 -0
  50. package/dist/plugins/fusion-plugin-cli-printing-press/src/index.ts +4 -0
  51. package/dist/plugins/fusion-plugin-cli-printing-press/src/workflow-steps.ts +14 -0
  52. package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
  53. package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
  54. package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
  55. package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
  56. package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
  57. package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
  58. package/dist/plugins/fusion-plugin-reports/package.json +1 -1
  59. package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
  60. package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
  61. package/package.json +1 -1
  62. package/skill/fusion/SKILL.md +2 -2
  63. package/skill/fusion/references/extension-tools.md +28 -5
  64. package/skill/fusion/references/fusion-capabilities.md +7 -5
  65. package/dist/client/assets/AgentDetailView-DG01uRND.js +0 -18
  66. package/dist/client/assets/AgentDetailView-DSpIqBOs.css +0 -1
  67. package/dist/client/assets/AgentsView-B3ADnF0D.css +0 -1
  68. package/dist/client/assets/AgentsView-B6IKroR1.js +0 -34
  69. package/dist/client/assets/ChatView-DKstOyUm.js +0 -1
  70. package/dist/client/assets/DevServerView-DQQcGd2N.js +0 -1
  71. package/dist/client/assets/DocumentsView-C4Ky-ZkQ.js +0 -1
  72. package/dist/client/assets/EvalsView-B-z_KLLW.js +0 -1
  73. package/dist/client/assets/ExperimentalAgentOnboardingModal-B-APN_lM.css +0 -1
  74. package/dist/client/assets/PluginManager-C4UoLv4U.css +0 -1
  75. package/dist/client/assets/PluginManager-CpY9rYNq.js +0 -1
  76. package/dist/client/assets/ResearchView-BMxwiVk9.js +0 -1
  77. package/dist/client/assets/ResearchView-C7uXon3o.css +0 -1
  78. package/dist/client/assets/SettingsModal-3Jxv4PMI.js +0 -31
  79. package/dist/client/assets/SettingsModal-Ci0_sqbU.css +0 -1
  80. package/dist/client/assets/SettingsModal-DWKgRxBA.css +0 -1
  81. package/dist/client/assets/SetupWizardModal-SVUr5Mpm.js +0 -1
  82. package/dist/client/assets/SkillsView-COs7muvr.js +0 -1
  83. package/dist/client/assets/SkillsView-Cytf009Z.css +0 -1
  84. package/dist/client/assets/StashRecoveryView-BhB_6Fvq.js +0 -1
  85. package/dist/client/assets/dashboard-view-Czurx3BJ.js +0 -21
  86. package/dist/client/assets/index-CD0_dkME.css +0 -1
  87. package/dist/client/assets/index-u6AOHWO5.js +0 -692
  88. package/dist/client/assets/star-BkCn1oUu.js +0 -6
@@ -0,0 +1,34 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentDetailView-Cu4TgvBn.js","assets/vendor-react-K0fH_qHe.js","assets/index-DzSLVOnp.js","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/vendor-codemirror-jBKmHyH0.js","assets/index-CZFBq256.css","assets/AgentPermissionPolicyEditor-Ceg2Dszn.js","assets/AgentPermissionPolicyEditor-CthjqUL_.css","assets/ExperimentalAgentOnboardingModal-BM7EnSvJ.js","assets/ExperimentalAgentOnboardingModal-BNpveCEk.css","assets/AgentDetailView-CY-O6VkV.css"])))=>i.map(i=>d[i]);
2
+ import{c as at,A as Ze,C as ct,Z as Na,s as ya,r as wt,F as Ct,f as ka,a as wa,b as ta,B as St,u as aa,d as gt,e as Ca,g as Sa,h as Aa,i as Ra,j as Ot,k as dt,P as Ta,l as Ma,m as _a,n as Ea,o as Dt,G as $a,S as La,L as ht,T as pt,R as qe,X as Ht,p as Ia,q as Pa,t as it,v as za,w as Bt,x as Fa,y as Oa,z as Ee,D as xt,E as Da,M as Ha,H as Ba,I as Wt,N as Gt,J as Vt,K as Wa,O as Ga,Q as Va,U as Ka,V as bt,W as Kt,Y as Ua,_ as Ya,$ as Xa,a0 as rt,a1 as qa,a2 as Ut,a3 as Za,a4 as Ja,a5 as Qa}from"./index-DzSLVOnp.js";import{r as a,j as e,a as es}from"./vendor-react-K0fH_qHe.js";import{A as ts,S as as,E as ss,f as ns}from"./ExperimentalAgentOnboardingModal-BM7EnSvJ.js";import{U as At}from"./upload-euJEs_N2.js";import{F as ls}from"./folder-open-BTN2_Wuv.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 is=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],rs=at("info",is);/**
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 os=[["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"}]],cs=at("list-todo",os);/**
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 ds=[["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"}]],us=at("sliders-horizontal",ds);/**
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 ms=[["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"}]],gs=at("zoom-in",ms);/**
23
+ * @license lucide-react v1.7.0 - ISC
24
+ *
25
+ * This source code is licensed under the ISC license.
26
+ * See the LICENSE file in the root directory of this source tree.
27
+ */const hs=[["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"}]],ps=at("zoom-out",hs);function Yt(n){return typeof n=="number"&&Number.isFinite(n)?n:0}function Ye(n){return n.toLocaleString()}function xs({agents:n}){const{rows:r,totalInputTokens:p,totalOutputTokens:u,totalTokens:m}=a.useMemo(()=>{const o=n.map(d=>{const f=Yt(d.totalInputTokens),j=Yt(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)}},[n]),x=m>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:Ye(p)})]}),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:Ye(u)})]}),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:Ye(m)})]})]}),x?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:Ye(o.inputTokens)}),e.jsx("td",{children:Ye(o.outputTokens)}),e.jsx("td",{className:"agent-token-stats-panel__total-cell",children:Ye(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 bs=[{icon:Ze,label:"Active Agents",valueKey:"activeCount",className:"agent-metric-card--active"},{icon:cs,label:"Assigned Tasks",valueKey:"assignedTaskCount",className:"agent-metric-card--tasks"},{icon:ct,label:"Success Rate",valueKey:"successRate",className:"agent-metric-card--success"},{icon:Na,label:"Total Runs",valueKey:"completedRuns",className:"agent-metric-card--runs"}];function vs({stats:n,className:r=""}){return n?e.jsx("div",{className:`agent-metrics-bar ${r}`.trim(),children:bs.map(p=>{const u=p.valueKey==="successRate"?`${Math.round(n.successRate*100)}%`:n[p.valueKey];return e.jsxs("div",{className:`agent-metric-card ${p.className}`,children:[e.jsx(p.icon,{size:18}),e.jsxs("div",{className:"agent-metric-info",children:[e.jsx("span",{className:"agent-metric-value",children:u}),e.jsx("span",{className:"agent-metric-label",children:p.label})]})]},p.label)})}):null}const Xt=200;function fs(n,r){const[p,u]=a.useState([]),[m,x]=a.useState(!1),o=a.useRef(null),d=a.useRef(0),f=a.useRef(n),j=a.useRef(r);return(f.current!==n||j.current!==r)&&(f.current=n,j.current=r,d.current++,o.current&&(o.current(),o.current=null),u([]),x(!1)),a.useEffect(()=>{if(!n){u([]),x(!1);return}const A=d.current;let y=`/api/tasks/${encodeURIComponent(n)}/logs/stream`;r&&(y+=`?projectId=${encodeURIComponent(r)}`);const C=ya(y,{events:{"agent:log":T=>{if(d.current===A)try{const E=JSON.parse(T.data),H={type:E.type??"text",text:E.text??E.content??"",timestamp:E.timestamp,content:E.content};u(R=>{const _=[H,...R];return _.length>Xt?_.slice(0,Xt):_})}catch{}}},onOpen:()=>{d.current===A&&x(!0)},onError:()=>{d.current===A&&x(!1)}});return o.current=C,()=>{C(),o.current=null,d.current===A&&x(!1)}},[n,r]),{entries:p,isConnected:m}}const js=5e3;function Ns({agent:n,projectId:r,onSelect:p,onOpenTaskLogs:u}){const{entries:m,isConnected:x}=fs(n.taskId,r),[o,d]=a.useState(null);a.useEffect(()=>{if(!n.taskId){d(null);return}let R=!1,_;const b=async()=>{try{const I=await ka(n.taskId,r);R||d(I)}catch{}finally{R||(_=setTimeout(b,js))}};return b(),()=>{R=!0,_&&clearTimeout(_)}},[n.taskId,r]);const f=n.lastHeartbeatAt?Math.floor((Date.now()-new Date(n.lastHeartbeatAt).getTime())/1e3):0,j=(()=>{if(!n.lastHeartbeatAt)return null;const R=wt(n.runtimeConfig?.heartbeatIntervalMs),_=new Date(n.lastHeartbeatAt).getTime()+R,b=Math.round((_-Date.now())/1e3);return Number.isFinite(b)?b<=0?`Heartbeat overdue ${vt(-b)}`:`Next heartbeat in ${vt(b)}`:null})(),k=o?.steps?.[o.currentStep??0],A=o?.steps?.length??0,y=(o?.currentStep??0)+1,C=o?.modelId,T=()=>{p&&p(n.id)},E=R=>{R.stopPropagation(),n.taskId&&u&&u(n.taskId)},H=R=>{(R.key==="Enter"||R.key===" ")&&(R.preventDefault(),T())};return e.jsxs("div",{className:"live-agent-card",onClick:T,onKeyDown:H,role:"button",tabIndex:0,"aria-label":`Select agent ${n.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 ${n.state==="running"?"status-dot--pending":"status-dot--online"}`,"aria-hidden":"true"}),e.jsx("span",{children:n.name})]}),n.taskId&&e.jsx("span",{className:"live-agent-task badge",children:n.taskId})]}),e.jsx("div",{className:"live-agent-card-transcript",children:m.length===0?e.jsx("div",{className:"live-agent-card-empty",children:n.taskId?k?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"live-agent-card-status",children:["Step ",y,A?`/${A}`:"",": ",k.name]}),C&&e.jsx("div",{className:"live-agent-card-status-sub",children:C}),e.jsx("div",{className:"live-agent-card-status-sub",children:x?"Waiting for output...":"Connecting to log stream..."})]}):e.jsx("span",{children:x?"Waiting for output...":"Connecting..."}):e.jsx("span",{children:n.state==="running"?"Starting...":"Idle — no task assigned"})}):m.slice(0,20).map((R,_)=>e.jsx("div",{className:"live-agent-card-line",children:R.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:vt(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:[n.taskId&&u&&e.jsxs("button",{type:"button",className:"live-agent-card-logs-btn",onClick:E,title:"View live run logs","aria-label":`View live logs for ${n.taskId}`,children:[e.jsx(Ct,{size:12}),e.jsx("span",{children:"Live logs"})]}),x&&e.jsx(Ze,{size:12,className:"live-agent-streaming-dot"})]})]})]})}function vt(n){return n<60?`${n}s`:n<3600?`${Math.floor(n/60)}m ${n%60}s`:`${Math.floor(n/3600)}h ${Math.floor(n%3600/60)}m`}function ys({agents:n,projectId:r,onAgentSelect:p,onOpenTaskLogs:u,className:m=""}){const x=Array.from(new Map(n.map(o=>[o.id,o])).values());return x.length===0?null:e.jsxs("div",{className:`active-agents-panel ${m}`.trim(),children:[e.jsxs("div",{className:"active-agents-panel-header",children:[e.jsx(Ze,{size:16}),e.jsxs("span",{children:["Active Agents (",x.length,")"]})]}),e.jsx("div",{className:"active-agents-grid",children:x.map(o=>e.jsx(Ns,{agent:o,projectId:r,onSelect:p,onOpenTaskLogs:u},o.id))})]})}function ks({stats:n,activeAgents:r,projectId:p,isOpen:u,onToggle:m,onSelectAgent:x,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":u,onClick:m,children:[e.jsxs("span",{className:"agents-overview-bar__title-wrap",children:[u?e.jsx(wa,{size:16,"aria-hidden":"true"}):e.jsx(ta,{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"]})]}),u?e.jsxs("div",{className:"agents-overview-bar__content",children:[e.jsx(vs,{stats:n,className:"agents-overview-bar__metrics"}),e.jsx(ys,{agents:r,projectId:p,onAgentSelect:x,onOpenTaskLogs:o,className:"agents-overview-bar__active-panel"})]}):null]})}function ft({title:n="No agents found",description:r="Create an agent to get started",ctaLabel:p="Create Agent",onCtaClick:u}){return e.jsxs("div",{className:"agent-empty",children:[e.jsx(St,{size:48,opacity:.3,className:"agent-empty-state__icon"}),e.jsx("p",{className:"agent-empty-state__title",children:n}),e.jsx("p",{className:"agent-empty-state__description text-secondary",children:r}),u?e.jsx("button",{type:"button",className:"btn btn-task-create btn-sm",onClick:u,children:p}):null]})}const qt=3,jt=1e3;function ws({isOpen:n,onClose:r,onGenerated:p,projectId:u}){aa(n);const[m,x]=a.useState(""),[o,d]=a.useState({type:"input"}),[f,j]=a.useState(null),[k,A]=a.useState(!1),y=a.useRef(null),C=a.useRef(null);a.useEffect(()=>{n&&o.type==="input"&&C.current?.focus()},[n,o.type]),a.useEffect(()=>{if(!n&&y.current){const b=y.current;y.current=null,gt(b,u).catch(()=>{})}},[n,u]),a.useEffect(()=>{if(!n)return;const b=I=>{I.key==="Escape"&&T()};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[n]);const T=a.useCallback(()=>{if(y.current){const b=y.current;y.current=null,gt(b,u).catch(()=>{})}x(""),d({type:"input"}),j(null),A(!1),r()},[r,u]),E=a.useCallback(async()=>{if(!(!m.trim()||m.trim().length<qt)){j(null),d({type:"loading"});try{const{sessionId:b}=await Ca(m.trim(),u);y.current=b;const{spec:I}=await Sa(b,u);d({type:"preview",spec:I,sessionId:b})}catch(b){const I=b instanceof Error?b.message:"Failed to generate agent specification";I.includes("429")||I.toLowerCase().includes("rate limit")?j("Too many requests. Please wait a moment and try again."):j(I),d({type:"input"}),y.current=null}}},[m,u]),H=a.useCallback(async()=>{if(y.current){const b=y.current;y.current=null;try{await gt(b,u)}catch{}}await E()},[E,u]),R=a.useCallback(()=>{o.type==="preview"&&(y.current=null,p(o.spec),x(""),d({type:"input"}),j(null),A(!1),r())},[o,p,r]);if(!n)return null;const _=m.trim().length>=qt&&m.trim().length<=jt;return e.jsx("div",{className:"agent-dialog-overlay",onClick:b=>{b.target===b.currentTarget&&T()},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:T,"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:m,onChange:b=>x(b.target.value),onKeyDown:b=>{b.key==="Enter"&&!b.shiftKey&&_&&(b.preventDefault(),E())},maxLength:jt,"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:[m.length,"/",jt]})]})]})]}),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:()=>A(!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:T,children:"Cancel"}),o.type==="input"&&e.jsx("button",{className:"btn btn-task-create",onClick:()=>void E(),disabled:!_,children:"Generate"}),o.type==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn",onClick:()=>void H(),children:"Regenerate"}),e.jsx("button",{className:"btn btn-task-create",onClick:R,children:"Use This"})]})]})]})})}const Zt=[{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:"✦"}],Jt=new Set(["triage","executor","reviewer","merger","scheduler","engineer","custom"]);function Cs({isOpen:n,onClose:r,onCreated:p,projectId:u,prefillDraft:m=null,agentOnboardingEnabled:x=!1,existingAgents:o=[],onPrefillDraft:d}){const[f,j]=a.useState(0),[k,A]=a.useState("presets"),[y,C]=a.useState(""),[T,E]=a.useState(""),[H,R]=a.useState(""),[_,b]=a.useState("custom"),[I,$]=a.useState(""),[q,Ne]=a.useState(""),[le,K]=a.useState(""),[ae,ie]=a.useState(""),[F,N]=a.useState(""),[me,ge]=a.useState(""),[S,Z]=a.useState({model:"",thinkingLevel:"off",maxTurns:1e3}),[re,$e]=a.useState(null),[ee,te]=a.useState([]),[ye,U]=a.useState(!1),[he,ke]=a.useState(null),[oe,J]=a.useState(!1),[ce,pe]=a.useState(!1),[G,B]=a.useState([]),[Le,Fe]=a.useState(!1),[we,de]=a.useState([]),[xe,Ae]=a.useState([]),[D,L]=a.useState("model"),[Q,be]=a.useState(""),[Re,Ie]=a.useState([]),[Oe,Pe]=a.useState(!1),[i,v]=a.useState([]),[O,se]=a.useState(!1);a.useEffect(()=>{n&&(Fe(!0),Aa().then(s=>{B(s.models),de(s.favoriteProviders),Ae(s.favoriteModels)}).catch(()=>{}).finally(()=>Fe(!1)))},[n]),a.useEffect(()=>{n&&(se(!0),v([]),Ra(void 0,u).then(s=>{v(s)}).catch(()=>{v([])}).finally(()=>se(!1)))},[n,u]),a.useEffect(()=>{if(!n)return;const s=Ma;if(typeof s!="function"){Ie([]),Pe(!1);return}Pe(!0),Ie([]),s(u).then(w=>{Ie(w)}).catch(()=>{Ie([])}).finally(()=>Pe(!1))},[n,u]);const P=S.model.includes("/")?S.model:"",Y=a.useCallback(s=>{const w=Jt.has(s.role)?s.role:"custom";C(s.title),E(s.description),R(s.icon),b(w),K(s.systemPrompt),Z(_e=>({..._e,thinkingLevel:s.thinkingLevel,maxTurns:s.maxTurns})),J(!1),j(1)},[]),Ce=a.useCallback(s=>{Z(w=>({...w,model:s}))},[]),De=a.useCallback(s=>{L(s),s==="model"&&be("")},[]),Te=a.useCallback(async s=>{const w=we,V=w.includes(s)?w.filter(ve=>ve!==s):[s,...w];de(V);try{await Ot({favoriteProviders:V,favoriteModels:xe})}catch{de(w)}},[we,xe]),Ve=a.useCallback(async s=>{const w=xe,V=w.includes(s)?w.filter(ve=>ve!==s):[s,...w];Ae(V);try{await Ot({favoriteProviders:we,favoriteModels:V})}catch{Ae(w)}},[we,xe]),st=a.useCallback(s=>{$e(s.id),C(s.name),R(s.icon),E(s.description??s.title),b(s.role),N(s.soul??""),K(s.instructionsText??""),j(1)},[]),Ke=a.useCallback(s=>{const w=s.runtimeHint?.trim()??"",_e=s.model?.trim()||s.modelHint?.trim()||"";j(1),A("custom"),C(s.name??""),E(s.title??""),R(s.icon??""),b(Jt.has(s.role)?s.role:"custom"),$(s.reportsTo??""),K(s.instructionsText??""),ie(s.heartbeatProcedurePath??""),N(s.soul??""),ge(s.memory??""),te(Array.isArray(s.skills)?s.skills:[]),Z(V=>({...V,model:w?"":_e,thinkingLevel:s.thinkingLevel??V.thinkingLevel,maxTurns:s.maxTurns??V.maxTurns})),w?(L("runtime"),be(w)):(L("model"),be(""))},[]);if(a.useEffect(()=>{!n||!m||Ke(m)},[n,m,Ke]),!n)return null;const He=()=>{j(0),A("presets"),C(""),E(""),R(""),b("custom"),$(""),Ne(""),K(""),ie(""),N(""),ge(""),Z({model:"",thinkingLevel:"off",maxTurns:1e3}),L("model"),be(""),$e(null),te([]),ke(null),J(!1),pe(!1),r()},Me=async()=>{if(y.trim()){U(!0),ke(null);try{const s={};D==="runtime"?Q.trim()&&(s.runtimeHint=Q.trim()):S.model.trim()&&(s.model=S.model.trim()),S.thinkingLevel!=="off"&&(s.thinkingLevel=S.thinkingLevel),S.maxTurns!==1e3&&(s.maxTurns=S.maxTurns),await Ea({name:y.trim(),role:_,...T.trim()?{title:T.trim()}:{},...H.trim()?{icon:H.trim()}:{},...I.trim()?{reportsTo:I.trim()}:{},...q.trim()?{instructionsPath:q.trim()}:{},...le.trim()?{instructionsText:le.trim()}:{},...ae.trim()?{heartbeatProcedurePath:ae.trim()}:{},...F.trim()?{soul:F.trim()}:{},...me.trim()?{memory:me.trim()}:{},...Object.keys(s).length>0?{runtimeConfig:s}:{},...ee.length>0?{metadata:{skills:ee}}:{}},u),He(),p()}catch(s){ke(s instanceof Error?s.message:"Failed to create agent")}finally{U(!1)}}},Je=Zt.find(s=>s.value===_),ze=I.trim(),Se=ze?i.find(s=>s.id===ze):void 0,Be=Q?Re.find(s=>s.runtimeId===Q):void 0,Qe=s=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx("label",{id:s,children:"Runtime Source"}),e.jsxs("div",{className:"agent-runtime-mode-toggle",role:"radiogroup","aria-labelledby":s,children:[e.jsxs("label",{className:`agent-runtime-mode-option${D==="model"?" agent-runtime-mode-option--active":""}`,children:[e.jsx("input",{type:"radio",name:s,value:"model",checked:D==="model",onChange:()=>De("model")}),e.jsx("span",{children:"Built-in Model"})]}),e.jsxs("label",{className:`agent-runtime-mode-option${D==="runtime"?" agent-runtime-mode-option--active":""}`,children:[e.jsx("input",{type:"radio",name:s,value:"runtime",checked:D==="runtime",onChange:()=>De("runtime")}),e.jsx("span",{children:"Plugin Runtime"})]})]})]}),D==="model"?e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx("label",{children:"Model"}),Le?e.jsx("div",{className:"agent-dialog-loading",children:"Loading models…"}):e.jsx(_a,{id:"agent-model",label:"Model",value:P,onChange:Ce,models:G,placeholder:"Select a model…",favoriteProviders:we,onToggleFavorite:Te,favoriteModels:xe,onToggleModelFavorite:Ve})]}):e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx("label",{htmlFor:"agent-runtime-hint",children:"Runtime"}),Oe?e.jsx("div",{className:"agent-dialog-loading",children:"Loading runtimes…"}):e.jsxs("select",{id:"agent-runtime-hint",className:"select",value:Q,onChange:w=>be(w.target.value),children:[e.jsx("option",{value:"",children:Re.length>0?"Select a plugin runtime…":"No plugin runtimes available"}),Re.map(w=>e.jsx("option",{value:w.runtimeId,children:w.description?`${w.name} — ${w.description}`:w.name},`${w.pluginId}:${w.runtimeId}`))]})]})]});return es.createPortal(e.jsxs("div",{className:"agent-dialog-overlay",onClick:s=>{s.target===s.currentTarget&&He()},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:He,"aria-label":"Close",children:"×"})]}),e.jsx("div",{className:"agent-dialog-steps",children:[0,1,2].map(s=>e.jsx("div",{className:`agent-dialog-step${s===f?" active":s<f?" completed":""}`,"aria-label":`Step ${s+1}`},s))}),e.jsxs("div",{className:"agent-dialog-body",children:[f===0&&e.jsxs("div",{children:[x&&e.jsx("div",{className:"agent-dialog-step-zero-actions",children:e.jsx("button",{type:"button",className:"btn agent-dialog-interview-btn",onClick:()=>pe(!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:()=>A("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:()=>A("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:ts.map(s=>e.jsxs("button",{type:"button",className:`agent-preset-card${re===s.id?" selected":""}`,"data-testid":`preset-${s.id}`,onClick:()=>st(s),title:s.title,children:[e.jsx("span",{className:"agent-preset-icon",children:e.jsx(dt,{agent:{id:s.id,icon:s.icon,name:s.name},size:28})}),e.jsx("span",{className:"agent-preset-name",children:s.name}),e.jsx("span",{className:"agent-preset-role",children:s.role}),s.description&&e.jsx("span",{className:"agent-preset-description",children:s.description})]},s.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 ",!re&&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:s=>C(s.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:T,onChange:s=>E(s.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:H,onChange:s=>R(s.target.value)})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx("label",{children:"Role"}),e.jsx("div",{className:"agent-role-grid",children:Zt.map(s=>e.jsxs("button",{type:"button",className:`agent-role-option${_===s.value?" selected":""}`,onClick:()=>b(s.value),children:[e.jsx("span",{className:"agent-role-option-icon",children:s.icon}),e.jsx("span",{className:"agent-role-option-label",children:s.label})]},s.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:I,onChange:s=>$(s.target.value),disabled:O,children:[e.jsx("option",{value:"",children:"No manager"}),i.map(s=>e.jsxs("option",{value:s.id,children:[s.name," (",s.id,")"]},s.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:F,onChange:s=>N(s.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:me,onChange:s=>ge(s.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:s=>Ne(s.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:s=>ie(s.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:le,onChange:s=>K(s.target.value)})]})]}),e.jsxs("div",{className:"agent-dialog-section",children:[e.jsx("div",{className:"agent-dialog-section-header",children:"Runtime"}),Qe("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:()=>J(!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:[Qe("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:s=>Z(w=>({...w,thinkingLevel:s.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:s=>Z(w=>({...w,maxTurns:Math.max(1,parseInt(s.target.value,10)||1)}))})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx(as,{id:"agent-skills",label:"Skills",value:ee,onChange:te,projectId:u}),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",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Name"}),e.jsxs("span",{className:"agent-dialog-summary-row-value",children:[H&&e.jsx("span",{className:"agent-dialog-icon-prefix",children:H}),y]})]}),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:T,onChange:s=>E(s.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:[Je?.icon," ",Je?.label]})]}),ze&&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:Se?`${Se.name} (${Se.id})`:ze})]}),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:F,onChange:s=>N(s.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:s=>ie(s.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:s=>Ne(s.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:le,onChange:s=>K(s.target.value)})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:D==="runtime"?"Runtime":"Model"}),e.jsx("span",{children:D==="runtime"?Be?Be.name:e.jsx("em",{className:"agent-dialog-summary-row-value--muted",children:"Not selected"}):P?e.jsxs(e.Fragment,{children:[e.jsx(Ta,{provider:P.split("/")[0],size:"sm"})," ",(()=>{const s=P.indexOf("/"),w=P.slice(0,s),_e=P.slice(s+1);return G.find(ve=>ve.provider===w&&ve.id===_e)?.name||P})()]}):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"]})]})]}),he&&e.jsx("p",{className:"agent-dialog-error",children:he})]})]}),e.jsxs("div",{className:"agent-dialog-footer",children:[f>0&&e.jsx("button",{className:"btn",onClick:()=>j(s=>s-1),disabled:ye,children:"Back"}),e.jsx("button",{className:"btn",onClick:He,disabled:ye,children:"Cancel"}),f<2?e.jsx("button",{className:"btn btn--primary",onClick:()=>j(s=>s+1),disabled:f===0&&!y.trim()&&!re,children:"Next"}):e.jsx("button",{className:"btn btn--primary",onClick:()=>void Me(),disabled:ye||!y.trim(),children:ye?"Creating...":"Create"})]})]}),e.jsx(ws,{isOpen:oe,onClose:()=>J(!1),onGenerated:Y,projectId:u}),e.jsx(ss,{isOpen:ce,onClose:()=>pe(!1),onUseDraft:s=>{d?.(s),d||Ke(s),pe(!1)},projectId:u,existingAgents:o,mode:"create"})]}),document.body)}function Ss(n){const r=n.match(/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n([\s\S]*))?$/);if(!r)throw new Error("Missing YAML frontmatter delimiters (---)");const p=r[1].split(/\r?\n/),u=r[2]??"",m={name:""},x=[];let o=!1;for(const d of p){const j=d.trimEnd().trim();if(!j)continue;if(j.startsWith("skills:")){o=!0;continue}if(o&&j.startsWith("- ")){x.push(j.slice(2).trim());continue}o=!1;const[k,...A]=j.split(":"),C=A.join(":").trim().replace(/^['"]|['"]$/g,"");k==="name"&&(m.name=C),k==="title"&&(m.title=C),k==="icon"&&(m.icon=C),k==="role"&&(m.role=C),k==="reportsTo"&&(m.reportsTo=C)}if(!m.name)throw new Error("Missing required field: name");return x.length>0&&(m.skills=x),u.trim().length>0&&(m.instructionBody=u),m}function As({isOpen:n,onClose:r,onImported:p,projectId:u,initialInputMethod:m="paste"}){aa(n);const[x,o]=a.useState("input"),[d,f]=a.useState(m),[j,k]=a.useState(""),[A,y]=a.useState([]),[C,T]=a.useState("Unknown"),[E,H]=a.useState([]),[R,_]=a.useState([]),[b,I]=a.useState([]),[$,q]=a.useState([]),[Ne,le]=a.useState(!1),[K,ae]=a.useState(!1),[ie,F]=a.useState(null),[N,me]=a.useState(null),[ge,S]=a.useState(null),Z=a.useRef(null),re=a.useRef(null),[$e,ee]=a.useState([]),[te,ye]=a.useState(""),[U,he]=a.useState(null),[ke,oe]=a.useState(!1),[J,ce]=a.useState(null),pe=a.useRef(!1);a.useEffect(()=>{d==="browse"&&!pe.current&&!ke&&(pe.current=!0,oe(!0),ce(null),Dt().then(i=>{i.error?ce(i.error):i.companies.length>0?ee(i.companies):ce("No companies available")}).catch(i=>{ce(i instanceof Error?i.message:"Failed to load companies")}).finally(()=>{oe(!1)}))},[d,ke]);const G=a.useCallback(()=>{pe.current=!0,ce(null),ee([]),he(null),oe(!0),Dt().then(i=>{i.error?ce(i.error):i.companies.length>0?ee(i.companies):ce("No companies available")}).catch(i=>{ce(i instanceof Error?i.message:"Failed to load companies")}).finally(()=>{oe(!1)})},[]),B=a.useCallback(()=>{o("input"),f(m),k(""),y([]),T("Unknown"),H([]),_([]),I([]),q([]),le(!1),ae(!1),F(null),me(null),S(null),ee([]),ye(""),he(null),oe(!1),ce(null),pe.current=!1},[m]),Le=a.useCallback(()=>{B(),r()},[B,r]),Fe=a.useCallback(i=>{const v=i.target.files?.[0];if(!v)return;const O=new FileReader;O.onload=se=>{const P=se.target?.result;f("file"),y([]),k(P),F(null)},O.onerror=()=>{F("Failed to read file")},O.readAsText(v),i.target.value=""},[]),we=a.useCallback(async i=>{const v=Array.from(i.target.files??[]);if(v.length!==0)try{const O=v.filter(P=>(P.webkitRelativePath||P.name).toLowerCase().endsWith("agents.md")).sort((P,Y)=>{const Ce=P.webkitRelativePath||P.name,De=Y.webkitRelativePath||Y.name;return Ce.localeCompare(De)});if(O.length===0){F("Selected directory has no AGENTS.md files");return}const se=[];for(const P of O){const Y=await P.text();se.push(Ss(Y))}f("directory"),y(se),k(""),F(null)}catch{F("Failed to parse AGENTS.md files from selected directory")}finally{i.target.value=""}},[]);function de(i){if(!u)return`/api${i}`;const v=i.includes("?")?"&":"?";return`/api${i}${v}projectId=${encodeURIComponent(u)}`}const xe=a.useCallback(async()=>{if(d==="directory"&&A.length===0){F("Please select a directory containing AGENTS.md files");return}if(d==="browse"&&!U){F("Please select a company from the catalog");return}if(d!=="directory"&&d!=="browse"&&!j.trim()){F("Please provide manifest content");return}le(!0),F(null);try{let i;d==="directory"?i={agents:A,dryRun:!0}:d==="browse"&&U?i={importSource:"companies.sh",companySlug:U.slug,dryRun:!0}:i={manifest:j,dryRun:!0};const v=await fetch(de("/agents/import"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!v.ok){const Y=await v.json();throw new Error(Y.error??`Parse failed (${v.status})`)}const O=await v.json(),se=O.agents&&O.agents.length>0?O.agents:O.created.map(Y=>({name:Y,role:"custom"})),P=Array.isArray(O.skills)?O.skills:[];T(O.companyName??"Unknown"),H(se),_(P),I(se.map(Y=>Y.name)),q(P.map(Y=>Y.name)),o("preview")}catch(i){F(i instanceof Error?i.message:"Failed to parse manifest")}finally{le(!1)}},[d,A,j,U,u]),Ae=a.useCallback(async()=>{ae(!0),S(null);try{let i;d==="directory"?i={agents:A,skipExisting:!0,selectedAgents:b,selectedSkills:$}:d==="browse"&&U?i={importSource:"companies.sh",companySlug:U.slug,skipExisting:!0,selectedAgents:b,selectedSkills:$}:i={manifest:j,skipExisting:!0,selectedAgents:b,selectedSkills:$};const v=await fetch(de("/agents/import"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!v.ok){const se=await v.json();throw new Error(se.error??`Import failed (${v.status})`)}const O=await v.json();me(O),o("result"),p()}catch(i){S(i instanceof Error?i.message:"Failed to import agents")}finally{ae(!1)}},[d,A,j,U,b,$,u,p]),D=b.length,L=$.length,Q=`${D} Agent${D!==1?"s":""}`,be=`${L} Skill${L!==1?"s":""}`,Re=D>0&&L>0?`${Q} + ${be}`:L>0?be:Q,Ie=D>0&&L>0?`Importing ${D} agent${D!==1?"s":""} and ${L} skill${L!==1?"s":""}...`:L>0?`Importing ${L} skill${L!==1?"s":""}...`:`Importing ${D} agent${D!==1?"s":""}...`,Oe=i=>{I(v=>v.includes(i)?v.filter(O=>O!==i):[...v,i])},Pe=i=>{q(v=>v.includes(i)?v.filter(O=>O!==i):[...v,i])};return n?e.jsx("div",{className:"agent-dialog-overlay",onClick:i=>{i.target===i.currentTarget&&Le()},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:Le,"aria-label":"Close",children:"×"})]}),e.jsxs("div",{className:"agent-dialog-body",children:[x==="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:Fe,className:"agent-import-file-input","aria-label":"Upload agent manifest file"}),e.jsx("input",{ref:re,type:"file",webkitdirectory:"",multiple:!0,onChange:we,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(At,{size:16}),"Choose File"]}),e.jsxs("button",{type:"button",className:"btn agent-import-upload-btn",onClick:()=>re.current?.click(),children:[e.jsx(ls,{size:16}),"Select Directory"]}),e.jsxs("button",{type:"button",className:"btn agent-import-upload-btn",onClick:()=>{f("browse"),y([]),k(""),he(null),F(null)},children:[e.jsx($a,{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(La,{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=>ye(i.target.value),"aria-label":"Search companies"})]}),U&&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:U.name}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>he(null),children:"Change"})]})]}),ke&&e.jsxs("div",{className:"agent-import-browse-loading",children:[e.jsx(ht,{size:20,className:"spin"}),e.jsx("span",{children:"Loading companies..."})]}),J&&e.jsxs("div",{className:"agent-import-browse-error",children:[e.jsx(pt,{size:16}),e.jsx("span",{children:J}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:G,children:[e.jsx(qe,{size:14}),"Retry"]})]}),!ke&&!J&&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 ${U?.slug===i.slug?"agent-import-browse-item--selected":""}`,onClick:()=>he(i),role:"button",tabIndex:0,onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&he(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:`---
28
+ name: CEO
29
+ title: Chief Executive Officer
30
+ reportsTo: null
31
+ skills:
32
+ - review
33
+ ---
34
+ Agent instructions go here...`,value:j,onChange:i=>{f("paste"),y([]),k(i.target.value),F(null)},rows:8,"aria-label":"Manifest content"})]}),e.jsxs("p",{className:"agent-import-file-hint",children:["Current input: ",d]}),ie&&e.jsxs("p",{className:"agent-dialog-error",children:[e.jsx(pt,{size:14}),ie]})]}),x==="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(Ct,{size:14}),e.jsxs("span",{children:[E.length," agent",E.length!==1?"s":""," found"]})]}),E.length>0&&e.jsxs("div",{className:"agent-import-selection-controls",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>I(E.map(i=>i.name)),children:"Select all agents"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>I([]),children:"Clear agents"})]}),E.length>0?e.jsx("div",{className:"agent-import-agent-list",children:E.map((i,v)=>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:b.includes(i.name),onChange:()=>Oe(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?"...":""]})]})]},v))}):e.jsx("p",{className:"agent-import-empty",children:"No agents found in the manifest."}),R.length>0&&e.jsxs("div",{className:"agent-import-skills-section",children:[e.jsxs("div",{className:"agent-import-count",children:[e.jsx(Ct,{size:14}),e.jsxs("span",{children:[R.length," skill",R.length!==1?"s":""," found"]})]}),e.jsxs("div",{className:"agent-import-selection-controls",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>q(R.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:R.map((i,v)=>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:$.includes(i.name),onChange:()=>Pe(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}-${v}`))})]}),ge&&e.jsxs("p",{className:"agent-dialog-error",children:[e.jsx(pt,{size:14}),ge]})]}),x==="result"&&N&&e.jsxs("div",{className:"agent-import-result",children:[e.jsx("div",{className:"agent-import-result-icon",children:e.jsx(ct,{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,v)=>e.jsxs("div",{className:"agent-import-result-agent",children:[e.jsx(ct,{size:12}),e.jsx("span",{children:i.name})]},v))}),N.errors.length>0&&e.jsx("div",{className:"agent-import-result-errors",children:N.errors.map((i,v)=>e.jsxs("div",{className:"agent-import-result-error",children:[e.jsx(Ht,{size:12}),e.jsxs("span",{children:[i.name,": ",i.error]})]},v))}),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,v)=>e.jsxs("div",{className:"agent-import-result-agent",children:[e.jsx(ct,{size:12}),e.jsx("span",{children:i.name})]},v))}),N.skills.errors.length>0&&e.jsx("div",{className:"agent-import-result-errors",children:N.skills.errors.map((i,v)=>e.jsxs("div",{className:"agent-import-result-error",children:[e.jsx(Ht,{size:12}),e.jsxs("span",{children:[i.name,": ",i.error]})]},v))})]})]})]}),e.jsxs("div",{className:"agent-dialog-footer",children:[x==="preview"&&e.jsx("button",{className:"btn",onClick:()=>o("input"),disabled:K,children:"Back"}),e.jsx("button",{className:"btn",onClick:Le,disabled:K,children:x==="result"?"Close":"Cancel"}),x==="input"&&e.jsx("button",{className:"btn btn-task-create",onClick:()=>void xe(),disabled:Ne||(d==="directory"?A.length===0:d==="browse"?!U:!j.trim()),children:Ne?e.jsxs(e.Fragment,{children:[e.jsx(ht,{size:14,className:"spin"}),"Parsing..."]}):"Preview"}),x==="preview"&&e.jsx("button",{className:"btn btn-task-create",onClick:()=>void Ae(),disabled:K||D===0&&L===0,children:K?e.jsxs(e.Fragment,{children:[e.jsx(ht,{size:14,className:"spin"}),Ie]}):`Import ${Re}`})]})]})}):null}const Nt="fn-agent-org-chart-layout";function Qt(n){return n==="auto"||n==="horizontal"||n==="vertical"}const Rs=768,Ts={nodeWidth:220,siblingGap:24,rootGap:24,chartPadding:24},Ms={nodeWidth:160,siblingGap:8,rootGap:8,chartPadding:8};function sa(n){return n.children.length===0?1:n.children.reduce((r,p)=>r+sa(p),0)}function _s(n){return n<=Rs?Ms:Ts}function Es(n,r){const p=sa(n);return p*r.nodeWidth+Math.max(0,p-1)*r.siblingGap}function $s(n,r=Number.POSITIVE_INFINITY){const p=_s(r);if(n.length===0)return p.nodeWidth;const m=n.map(o=>Es(o,p)).reduce((o,d)=>o+d,0),x=Math.max(0,n.length-1)*p.rootGap;return m+x+p.chartPadding*2}function Ls(n){const r=n.preference??"auto";if(r!=="auto")return r;const p=Number.isFinite(n.availableWidth)&&n.availableWidth>0?n.availableWidth:0;return p===0||n.tree.length<=1?"horizontal":$s(n.tree,p)>p?"vertical":"horizontal"}const ea=a.lazy(()=>Ya(()=>import("./AgentDetailView-Cu4TgvBn.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])).then(n=>({default:n.AgentDetailView}))),yt=[{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:"✦"}],kt=[.1,.25,.5,1,2,3,5,10],Is=.25,Ps=3,ot=16,Xe=32;function Rt(n){switch(n){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 Tt(n,r){switch(r){case"running":return`${n}--running`;case"active":return`${n}--active`;case"paused":return`${n}--paused`;case"error":return`${n}--error`;case"idle":default:return`${n}--idle`}}function na(n){return n.children.length===0?1:n.children.reduce((r,p)=>r+na(p),0)}function Mt(n,r){return n.state==="error"?{title:void 0,label:"Error"}:{title:r.reason??r.label,label:r.stateDerived?null:r.label}}function la({node:n,onSelect:r,getHealthStatus:p,selectedAgentId:u,registerNodeElement:m,linksRef:x}){const{agent:o,children:d}=n,f=p(o),j=Mt(o,f),k=Rt(o.state),A=Tt("org-chart-node-card",o.state),y=na(n),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:T=>m(o.id,T),"data-agent-id":o.id,className:`org-chart-node-card ${A}${u===o.id?" agent-card--selected":""}`,onClick:()=>r(o.id),role:"button",tabIndex:0,onKeyDown:T=>{(T.key==="Enter"||T.key===" ")&&(T.key===" "&&T.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(dt,{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(T=>(x.current.push({parentId:o.id,childId:T.agent.id}),e.jsx(la,{node:T,onSelect:r,getHealthStatus:p,selectedAgentId:u,registerNodeElement:m,linksRef:x},T.agent.id)))})]})}function zs({links:n,nodeElements:r,canvasRef:p,viewportRef:u,layoutMode:m,transform:x}){const[o,d]=a.useState([]);return a.useLayoutEffect(()=>{const f=p.current,j=u.current;if(!f||!j||n.length===0){d([]);return}const k=()=>{const y=f.getBoundingClientRect(),C=n.flatMap(({parentId:T,childId:E})=>{const H=r.get(T),R=r.get(E);if(!H||!R)return[];const _=H.getBoundingClientRect(),b=R.getBoundingClientRect(),I=(_.left-y.left)/x.scale,$=(_.top-y.top)/x.scale,q=(b.left-y.left)/x.scale,Ne=(b.top-y.top)/x.scale;if(m==="vertical"){const N=I,me=$+_.height/x.scale/2,ge=q,S=Ne+b.height/x.scale/2,Z=N-(N-ge)/2;return[`M ${N} ${me} L ${Z} ${me} L ${Z} ${S} L ${ge} ${S}`]}const le=I+_.width/x.scale/2,K=$+_.height/x.scale,ae=q+b.width/x.scale/2,ie=Ne,F=K+(ie-K)/2;return[`M ${le} ${K} L ${le} ${F} L ${ae} ${F} L ${ae} ${ie}`]});d(C)};k();const A=new ResizeObserver(k);return A.observe(f),A.observe(j),r.forEach(y=>A.observe(y)),()=>A.disconnect()},[p,m,n,r,x.scale,u]),e.jsx("svg",{className:"agent-org-chart-connectors","aria-hidden":"true",children:o.map((f,j)=>e.jsx("path",{d:f},`${j}-${f}`))})}function Vs({addToast:n,projectId:r,onOpenTaskLogs:p,agentOnboardingEnabled:u=!1}){const[m,x]=a.useState(!1),d=Ia()==="mobile",[f,j]=a.useState("all"),{agents:k,stats:A,isLoading:y,loadAgents:C,refreshAgents:T}=Pa(r,{filterState:f,showSystemAgents:m}),[E,H]=a.useState(!1),[R,_]=a.useState(null),[b,I]=a.useState(!1),[$,q]=a.useState(null),[Ne,le]=a.useState(null),K=d&&!!$,[ae,ie]=a.useState("dashboard"),[F,N]=a.useState(null),[me,ge]=a.useState(!1),[S,Z]=a.useState(()=>{if(typeof window>"u")return"list";const t=it("fn-agent-view",r);return t==="list"||t==="board"||t==="org"?t:"list"}),[re,$e]=a.useState(()=>{if(typeof window>"u")return"auto";const t=it(Nt,r);return Qt(t)?t:"auto"}),[ee,te]=a.useState([]),[ye,U]=a.useState(!1),[he,ke]=a.useState(0),[oe,J]=a.useState(!1),[ce,pe]=a.useState(!1),[G,B]=a.useState({scale:1,x:0,y:0}),[Le,Fe]=a.useState(!1),we=a.useRef(null),de=a.useRef(null),xe=a.useRef(null),Ae=a.useRef(new Map),D=a.useRef([]),L=a.useRef(new Map),Q=a.useRef(null),be=a.useRef(null),Re=a.useRef(!1),{confirm:Ie}=za(),Oe=a.useRef(null),Pe=a.useId();a.useEffect(()=>{const t=it("fn-agent-view",r);if(t==="list"||t==="board"||t==="org"){Z(t);return}Z("list")},[r]),a.useEffect(()=>{Bt("fn-agent-view",S,r)},[S,r]),a.useEffect(()=>{const t=it(Nt,r);$e(Qt(t)?t:"auto")},[r]),a.useEffect(()=>{Bt(Nt,re,r)},[re,r]);const[i,v]=a.useState(null),O=a.useRef(null),[se,P]=a.useState(null),[Y,Ce]=a.useState(null),[De,Te]=a.useState({}),[Ve,st]=a.useState(1),[Ke,He]=a.useState(!1),[Me,Je]=a.useState(new Set),[ze,Se]=a.useState(new Map),Be=a.useRef(!0);a.useEffect(()=>(Be.current=!0,()=>{Be.current=!1}),[]),a.useEffect(()=>{Fa(r).then(t=>{Be.current&&st(t.heartbeatMultiplier??1)}).catch(()=>{})},[r]);const Qe=a.useCallback(async t=>{const l=Number.isFinite(t)&&t>0?t:1;st(l),He(!0);try{await Oa({heartbeatMultiplier:l},r),n(`Heartbeat speed set to ×${l.toFixed(1)}`,"success")}catch(c){n(`Failed to save heartbeat multiplier: ${Ee(c)}`,"error")}finally{Be.current&&He(!1)}},[r,n]),s=a.useMemo(()=>ze.size===0?k:k.map(t=>{const l=ze.get(t.id);return l?{...t,state:l}:t}),[k,ze]),w=a.useMemo(()=>s.filter(t=>m||!xt(t)),[s,m]),_e=a.useMemo(()=>s.filter(t=>t.state!=="active"&&t.state!=="running"?!1:m||!xt(t)),[s,m]),V=a.useMemo(()=>{if(m)return ee;const t=l=>xt(l.agent)?null:{...l,children:l.children.map(t).filter(c=>c!==null)};return ee.map(t).filter(l=>l!==null)},[ee,m]);a.useEffect(()=>{if(S!=="org")return;const t=de.current;if(!t)return;const l=()=>{ke(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,V.length]),a.useEffect(()=>{if(S!=="org")return;let t=!1;return U(!0),Da(r,{includeEphemeral:m}).then(l=>{t||te(l)}).catch(l=>{t||(n(`Failed to load org chart: ${Ee(l)}`,"error"),te([]))}).finally(()=>{t||U(!1)}),()=>{t=!0}},[S,r,m,n]),a.useEffect(()=>{const t=setInterval(()=>{C()},3e4);return()=>{clearInterval(t)}},[C]),a.useEffect(()=>{if(!oe)return;const t=c=>{const g=c.target;g&&(we.current?.contains(g)||Oe.current?.contains(g)||J(!1))},l=c=>{c.key==="Escape"&&(J(!1),Oe.current?.focus())};return document.addEventListener("mousedown",t),document.addEventListener("touchstart",t),document.addEventListener("keydown",l),()=>{document.removeEventListener("mousedown",t),document.removeEventListener("touchstart",t),document.removeEventListener("keydown",l)}},[oe]);const ve=async(t,l)=>{if(!Me.has(t)){Je(c=>new Set(c).add(t)),Se(c=>{const g=new Map(c);return g.set(t,l),g});try{await Za(t,l,r),n(`Agent state updated to ${l}`,"success"),await C(),Se(c=>{const g=new Map(c);return g.delete(t),g})}catch(c){Se(g=>{const M=new Map(g);return M.delete(t),M}),n(`Failed to update state: ${Ee(c)}`,"error")}finally{Je(c=>{const g=new Set(c);return g.delete(t),g})}}},ia=async(t,l)=>{if(await Ie({title:"Delete Agent",message:`Delete agent "${l}"? This cannot be undone.`,danger:!0}))try{await Qa(t,r),n(`Agent "${l}" deleted`,"success"),await C()}catch(g){n(`Failed to delete agent: ${Ee(g)}`,"error")}},ra=async(t,l)=>{const c=k.find(g=>g.id===t);if(c){if(c.role===l){v(null);return}try{await rt(t,{role:l},r),n(`Agent role updated to ${yt.find(g=>g.value===l)?.label??l}`,"success"),v(null),C()}catch(g){n(`Failed to update role: ${Ee(g)}`,"error")}}},oa=(t,l)=>{t.key==="Escape"&&v(null)},ca=async(t,l)=>{Y===t.id&&(Ce(null),Te(c=>{const g={...c};return delete g[t.id],g})),P(t.id);try{await rt(t.id,{runtimeConfig:{...t.runtimeConfig??{},heartbeatIntervalMs:l}},r),n(`Heartbeat interval updated to ${Ut(l)} for ${t.name}`,"success"),C()}catch(c){n(`Failed to update heartbeat interval: ${Ee(c)}`,"error")}finally{P(null)}},_t=async t=>{const l=De[t.id]??"";if(l.trim()===""){n("Please enter a heartbeat interval in minutes","error");return}const c=Number(l);if(isNaN(c)){n("Heartbeat interval must be a valid number","error");return}if(c<=0){n("Heartbeat interval must be greater than 0","error");return}if(c>=1&&c<5){P(t.id);try{await rt(t.id,{runtimeConfig:{...t.runtimeConfig??{},heartbeatIntervalMs:qa}},r),n(`Heartbeat interval set to 5 minutes (minimum). ${c} minute${c!==1?"s":""} was below the 5-minute minimum.`,"success"),Ce(null),Te(M=>{const z={...M};return delete z[t.id],z}),C()}catch(M){n(`Failed to update heartbeat interval: ${Ee(M)}`,"error")}finally{P(null)}return}const g=Math.round(c*6e4);P(t.id);try{await rt(t.id,{runtimeConfig:{...t.runtimeConfig??{},heartbeatIntervalMs:g}},r),n(`Heartbeat interval updated to ${Ut(g)} for ${t.name}`,"success"),Ce(null),Te(M=>{const z={...M};return delete z[t.id],z}),C()}catch(M){n(`Failed to update heartbeat interval: ${Ee(M)}`,"error")}finally{P(null)}},da=t=>{const l=wt(t.runtimeConfig?.heartbeatIntervalMs),c=Math.round(l/6e4);Ce(t.id),Te(g=>({...g,[t.id]:String(c)}))},ue=a.useCallback((t,l)=>{q(t),ie(l?.initialTab??"dashboard"),N(l?.initialRunId??null),ge(l?.preferActiveRun??!1)},[]),We=a.useCallback(()=>{q(null),ie("dashboard"),N(null),ge(!1)},[]),Et=a.useCallback(t=>{ue(t)},[ue]),ua=a.useCallback(t=>{le(t),ue(t)},[ue]),ma=a.useCallback(async({agentId:t,deleted:l})=>{await T(),l&&$===t&&We()},[T,$,We]),ga=a.useCallback(t=>{ue(t),d&&pe(!1)},[d,ue]),ha=async(t,l)=>{Se(c=>{const g=new Map(c);return g.set(t,"running"),g});try{await Ja(t,r,{source:"on_demand",triggerDetail:"Triggered from dashboard"}),n(`Heartbeat run started for ${l}`,"success"),await C(),Se(c=>{const g=new Map(c);return g.delete(t),g})}catch(c){Se(g=>{const M=new Map(g);return M.delete(t),M}),n(`Failed to start heartbeat run: ${Ee(c)}`,"error")}},Ge=a.useCallback(t=>Math.min(Ps,Math.max(Is,t)),[]),X=a.useCallback(t=>{const l=de.current,c=xe.current?.querySelector(".agent-org-chart");if(!l||!c)return{...t,scale:Ge(t.scale)};const g=Ge(t.scale),M=c.scrollWidth*g,z=c.scrollHeight*g,fe=l.clientWidth,je=l.clientHeight,h=Math.min(Xe,fe-M-Xe),W=Xe,ne=Math.min(Xe,je-z-Xe),tt=Xe;return{scale:g,x:Math.max(h,Math.min(W,t.x)),y:Math.max(ne,Math.min(tt,t.y))}},[Ge]),nt=a.useCallback((t,l,c)=>{const g=de.current;g&&B(M=>{const z=Ge(t),fe=g.getBoundingClientRect(),je=l-fe.left,h=c-fe.top,W=(je-M.x)/M.scale,ne=(h-M.y)/M.scale;return X({scale:z,x:je-W*z,y:h-ne*z})})},[Ge,X]),Ue=a.useCallback(()=>{const t=de.current,l=xe.current?.querySelector(".agent-org-chart");if(!t||!l)return;const c=t.clientWidth,g=t.clientHeight,M=l.scrollWidth,z=l.scrollHeight;if(M<=0||z<=0)return;const fe=Ge(Math.min(c/M,g/z,1)),je=(c-M*fe)/2,h=(g-z*fe)/2;B(X({scale:fe,x:je,y:h}))},[Ge,X]),ut=a.useCallback(t=>{Z(t),t!=="org"&&B({scale:1,x:0,y:0}),d&&$&&We()},[We,d,$]),$t=t=>yt.find(l=>l.value===t)?.label??t,lt=a.useMemo(()=>Ls({tree:V,availableWidth:he,preference:re}),[V,re,he]),Lt=a.useCallback(t=>{$e(t),B({scale:1,x:0,y:0})},[]);a.useEffect(()=>{B({scale:1,x:0,y:0}),Re.current=!1},[r,lt]),a.useLayoutEffect(()=>{S!=="org"||ye||V.length===0||Re.current||(Ue(),Re.current=!0)},[S,V.length,Ue,ye]);const pa=a.useCallback((t,l)=>{l?Ae.current.set(t,l):Ae.current.delete(t)},[]),It=a.useCallback(()=>e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"btn-icon touch-target",onClick:()=>B(t=>X({...t,scale:t.scale*.9})),"aria-label":"Zoom out org chart",title:"Zoom out",children:e.jsx(ps,{size:16})}),e.jsxs("span",{className:"agent-org-chart-controls__zoom-label","aria-live":"polite",children:[Math.round(G.scale*100),"%"]}),e.jsx("button",{type:"button",className:"btn-icon touch-target",onClick:()=>B(t=>X({...t,scale:t.scale*1.1})),"aria-label":"Zoom in org chart",title:"Zoom in",children:e.jsx(gs,{size:16})}),e.jsxs("button",{type:"button",className:"btn touch-target btn-sm agent-org-chart-controls__fit-btn",onClick:Ue,"aria-label":"Fit org chart",title:"Fit org chart",children:[e.jsx(Ha,{size:16}),"Fit"]}),e.jsxs("button",{type:"button",className:"btn touch-target btn-sm",onClick:()=>B(t=>X({...t,x:0,y:0})),"aria-label":"Center org chart",title:"Center org chart",children:[e.jsx(Ba,{size:16}),"Center"]})]}),[X,Ue,G.scale]),xa=a.useCallback(t=>{if(!(t.ctrlKey||t.metaKey))return;t.preventDefault();const l=t.deltaY>0?.9:1.1;nt(G.scale*l,t.clientX,t.clientY)},[G.scale,nt]),ba=a.useCallback(t=>{if(t.target.closest(".org-chart-node-card"))return;if(t.currentTarget.setPointerCapture?.(t.pointerId),L.current.set(t.pointerId,{x:t.clientX,y:t.clientY}),L.current.size===1){Q.current={x:t.clientX-G.x,y:t.clientY-G.y,pointerId:t.pointerId},Fe(!0);return}if(L.current.size===2){const c=Array.from(L.current.values()),g=c[0].x-c[1].x,M=c[0].y-c[1].y;be.current={distance:Math.hypot(g,M),scale:G.scale,centerX:(c[0].x+c[1].x)/2,centerY:(c[0].y+c[1].y)/2},Q.current=null}},[G.scale,G.x,G.y]),va=a.useCallback(t=>{if(L.current.has(t.pointerId)){if(L.current.set(t.pointerId,{x:t.clientX,y:t.clientY}),L.current.size>=2){const l=Array.from(L.current.values()),c=be.current;if(!c)return;const g=l[0].x-l[1].x,M=l[0].y-l[1].y,z=Math.hypot(g,M),fe=c.scale*(z/c.distance);nt(fe,c.centerX,c.centerY);return}!Q.current||Q.current.pointerId!==t.pointerId||B(l=>X({...l,x:t.clientX-Q.current.x,y:t.clientY-Q.current.y}))}},[X,nt]),Pt=a.useCallback(t=>{L.current.delete(t.pointerId),L.current.size<2&&(be.current=null),L.current.size===0&&(Q.current=null,Fe(!1))},[]),fa=a.useCallback(t=>{if(t.key==="ArrowLeft")B(l=>X({...l,x:l.x+ot}));else if(t.key==="ArrowRight")B(l=>X({...l,x:l.x-ot}));else if(t.key==="ArrowUp")B(l=>X({...l,y:l.y+ot}));else if(t.key==="ArrowDown")B(l=>X({...l,y:l.y-ot}));else if(t.key==="+"||t.key==="=")B(l=>X({...l,scale:l.scale*1.1}));else if(t.key==="-")B(l=>X({...l,scale:l.scale*.9}));else if(t.key==="0")Ue();else if(t.key==="Home")B({scale:1,x:0,y:0});else return;t.preventDefault()},[X,Ue]),zt=a.useCallback(()=>{const t=[{value:"horizontal",label:"Horizontal",icon:e.jsx(Gt,{size:16}),ariaLabel:"Horizontal layout"},{value:"vertical",label:"Vertical",icon:e.jsx(Wt,{size:16}),ariaLabel:"Vertical layout"},{value:"auto",label:"Auto",icon:e.jsx(qe,{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=re===l.value;return e.jsxs("button",{type:"button",className:`btn-icon touch-target agent-org-chart-layout-toggle__button${c?" btn-icon--active":""}`,onClick:()=>Lt(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)})})},[Lt,re]),ja=t=>Array.isArray(t.metadata?.skills)?t.metadata.skills:[],mt=t=>Xa(t),Ft=y&&k.length===0,et=a.useCallback(()=>{H(!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(St,{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:()=>ut("list"),title:"List view","aria-label":"List view","aria-pressed":S==="list",children:e.jsx(Wt,{size:16})}),e.jsx("button",{className:`view-toggle-btn${S==="board"?" active":""}`,onClick:()=>ut("board"),title:"Board view","aria-label":"Board view","aria-pressed":S==="board",children:e.jsx(Ze,{size:16})}),e.jsx("button",{className:`view-toggle-btn${S==="org"?" active":""}`,onClick:()=>ut("org"),title:"Org Chart view","aria-label":"Org Chart view","aria-pressed":S==="org",children:e.jsx(Gt,{size:16})})]}),e.jsxs("div",{className:"agents-view-primary-actions",children:[e.jsx("button",{ref:Oe,className:`btn-icon agent-controls-trigger${oe?" agent-controls-trigger--active":""}`,onClick:()=>J(t=>!t),title:"Controls","aria-label":"Controls","aria-haspopup":"dialog","aria-expanded":oe,"aria-controls":Pe,children:e.jsx(us,{size:16})}),e.jsx("button",{className:"btn-icon",onClick:()=>void C(),title:"Refresh","aria-label":"Refresh",children:e.jsx(qe,{size:16,className:y?"spin":void 0})}),!d&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-sm agent-import-trigger",onClick:()=>{I(!0),J(!1)},"aria-label":"Import",title:"Import",children:[e.jsx(At,{size:16}),"Import"]}),e.jsxs("button",{className:"btn btn-task-create btn-sm",onClick:()=>{et(),J(!1)},"aria-label":"New Agent",title:"New Agent",children:[e.jsx(Vt,{size:16}),"New Agent"]})]}),oe&&e.jsxs("div",{ref:we,id:Pe,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(Wa,{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:m,onChange:t=>x(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:()=>{I(!0),J(!1)},"aria-label":"Import",title:"Import",children:[e.jsx(At,{size:16}),"Import"]}),e.jsxs("button",{className:"btn btn-task-create btn-sm",onClick:()=>{et(),J(!1)},"aria-label":"New Agent",title:"New Agent",children:[e.jsx(Vt,{size:16}),"New Agent"]})]}),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:Ve,onChange:t=>{const l=Number(t.target.value);Qe(Number.isFinite(l)&&l>0?l:1)},disabled:Ke}),e.jsxs("span",{className:"heartbeat-multiplier-value",children:["×",Ve.toFixed(1)]}),e.jsx("select",{className:"heartbeat-multiplier-preset",value:String(kt.reduce((t,l)=>Math.abs(l-Ve)<Math.abs(t-Ve)?l:t,kt[0])),onChange:t=>{const l=Number(t.target.value);Qe(Number.isFinite(l)&&l>0?l:1)},disabled:Ke,"aria-label":"Heartbeat speed preset",children:kt.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(xs,{agents:w})]})]})]})]}),e.jsx(Cs,{isOpen:E,onClose:()=>{H(!1),_(null)},onCreated:()=>{H(!1),_(null),C()},projectId:r,prefillDraft:R,agentOnboardingEnabled:u,existingAgents:k,onPrefillDraft:_}),e.jsx(As,{isOpen:b,onClose:()=>I(!1),onImported:()=>void C(),projectId:r}),e.jsx(ks,{stats:A,activeAgents:_e,projectId:r,isOpen:ce,onToggle:()=>pe(t=>!t),onSelectAgent:ga,onOpenTaskLogs:p}),S==="org"?e.jsx("div",{className:"agents-org-full-view",children:e.jsx("div",{className:"agents-view-content agents-view-content--org-full",children:$?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(a.Suspense,{fallback:null,children:e.jsx(ea,{inline:!0,showInlineBackButton:!1,agentId:$,projectId:r,onClose:We,addToast:n,onChildClick:Et,initialTab:ae,initialRunId:F,preferActiveRun:me},$)})]}):Ft?e.jsxs("div",{className:"agents-view-loading",role:"status","aria-live":"polite",children:[e.jsx(qe,{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:[zt(),It()]}):e.jsxs("div",{className:"agent-org-chart-toolbar",children:[zt(),e.jsx("div",{className:"agent-org-chart-controls","data-testid":"agent-org-chart-controls",children:It()})]}),e.jsx("div",{ref:de,className:"agent-org-chart-viewport","data-testid":"agent-org-chart-viewport",tabIndex:0,role:"region","aria-label":"Org chart canvas",onWheel:xa,onPointerDown:ba,onPointerMove:va,onPointerUp:Pt,onPointerCancel:Pt,onKeyDown:fa,"data-panning":Le?"true":"false",children:e.jsxs("div",{ref:xe,className:"agent-org-chart-canvas","data-panning":Le?"true":"false",style:{transform:`translate(${G.x}px, ${G.y}px) scale(${G.scale})`},children:[e.jsx("div",{className:`agent-org-chart${lt==="vertical"?" agent-org-chart--vertical":""}`,"data-testid":"agent-org-chart","data-layout-mode":lt,children:ye?e.jsxs("div",{className:"agent-org-chart__loading",role:"status","aria-live":"polite",children:[e.jsx(qe,{size:18,className:"spin"}),e.jsx("span",{children:"Loading org chart..."})]}):V.length===0?e.jsx(ft,{onCtaClick:et}):(D.current=[],V.map(t=>e.jsx(la,{node:t,onSelect:ua,getHealthStatus:mt,selectedAgentId:Ne,registerNodeElement:pa,linksRef:D},t.agent.id)))}),e.jsx(zs,{links:D.current,nodeElements:Ae.current,canvasRef:xe,viewportRef:de,layoutMode:lt,transform:G})]})})]})})}):e.jsxs("div",{className:"agents-split-layout",children:[e.jsx("div",{className:`agents-split-sidebar${K?" agents-split-sidebar--hidden-mobile":""}`,children:e.jsx("div",{className:"agents-view-content",children:Ft?e.jsxs("div",{className:"agents-view-loading",role:"status","aria-live":"polite",children:[e.jsx(qe,{size:18,className:"spin"}),e.jsx("span",{children:"Loading agents..."})]}):S==="board"?e.jsx("div",{className:"agent-board",children:w.length===0?e.jsx(ft,{onCtaClick:et}):w.map(t=>{const l=mt(t),c=Mt(t,l),g=Rt(t.state),M=Tt("agent-board-card",t.state);return e.jsx("div",{className:`agent-board-card ${M}${$===t.id?" agent-card--selected":""}`,children:e.jsxs("div",{className:"agent-board-clickable",onClick:()=>ue(t.id),role:"button",tabIndex:0,onKeyDown:z=>{(z.key==="Enter"||z.key===" ")&&(z.key===" "&&z.preventDefault(),ue(t.id))},children:[e.jsxs("div",{className:"agent-board-header",children:[e.jsx("span",{className:"agent-board-icon",children:e.jsx(dt,{agent:t,size:20})}),e.jsx("span",{className:"agent-board-badge badge text-secondary",children:$t(t.role)}),e.jsx("span",{className:`agent-board-badge badge ${g}`,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:w.length===0?e.jsx(ft,{onCtaClick:et}):w.map(t=>{const l=mt(t),c=Mt(t,l),g=Rt(t.state),M=Tt("agent-card",t.state),z=wt(t.runtimeConfig?.heartbeatIntervalMs),fe=Ga(z),je=se===t.id;return e.jsxs("div",{className:`agent-card agent-card--clickable ${M}${$===t.id?" agent-card--selected":""}`,onClick:h=>{const W=h.target;if(W===h.currentTarget){ue(t.id);return}const ne=W.closest('button, select, input, [role="button"]');ne&&ne!==h.currentTarget||ue(t.id)},role:"button",tabIndex:0,onKeyDown:h=>{h.target===h.currentTarget&&(h.key==="Enter"||h.key===" ")&&(h.key===" "&&h.preventDefault(),ue(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:[i===t.id?e.jsx("select",{ref:O,className:"select agent-role-select",value:t.role,onChange:h=>void ra(t.id,h.target.value),onKeyDown:h=>oa(h,t.id),onBlur:()=>v(null),autoFocus:!0,children:yt.map(h=>e.jsxs("option",{value:h.value,children:[h.icon," ",h.label]},h.value))}):e.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:h=>{h.stopPropagation(),v(t.id)},title:"Click to change role",role:"button",tabIndex:0,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.stopPropagation(),v(t.id))},children:e.jsx(dt,{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(ta,{size:20,className:"agent-card-chevron"})]}),e.jsxs("div",{className:"agent-badges",children:[e.jsx("span",{className:`badge ${g}`,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:$t(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 h=ja(t);if(h.length===0)return null;const W=h.slice(0,2),ne=h.length-2;return e.jsxs(e.Fragment,{children:[W.map(tt=>e.jsx("span",{className:"badge badge-skill",title:tt,children:ns(tt)},tt)),ne>0&&e.jsxs("span",{className:"badge badge-skill",children:["+",ne]})]})})()]})]}),e.jsxs("div",{className:"agent-card-body",children:[t.state==="error"&&t.lastError?e.jsx(Va,{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:"}),Y===t.id?e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"input agent-heartbeat-custom-input",value:De[t.id]??"",onChange:h=>Te(W=>({...W,[t.id]:h.target.value})),onKeyDown:h=>{h.key==="Enter"?_t(t):h.key==="Escape"&&(Ce(null),Te(W=>{const ne={...W};return delete ne[t.id],ne}))},disabled:je,"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 _t(t),disabled:je,title:"Save custom interval",children:"Save"}),e.jsx("button",{className:"btn btn-sm",onClick:()=>{Ce(null),Te(h=>{const W={...h};return delete W[t.id],W})},disabled:je,title:"Cancel custom interval",children:"Cancel"})]}):e.jsx(e.Fragment,{children:e.jsxs("select",{className:"select agent-heartbeat-select",value:z,onChange:h=>{const W=h.target.value;W==="__custom__"?da(t):ca(t,Number(W))},disabled:je,"aria-label":`Set heartbeat interval for ${t.name}`,children:[fe.map(h=>e.jsx("option",{value:h.value,children:h.label},h.value)),Ka.some(h=>h.value===z)&&e.jsx("option",{value:"__custom__",children:"Custom..."})]})}),je&&e.jsx("span",{className:"agent-heartbeat-saving text-secondary",children:"Saving…"}),t.lastHeartbeatAt&&(()=>{const h=new Date(t.lastHeartbeatAt),W=new Date(h.getTime()+z),ne=t.state==="active"||t.state==="running";return e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"agent-heartbeat-last text-secondary",title:h.toLocaleString(),children:["Last: ",h.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})]}),ne&&e.jsxs("span",{className:"agent-heartbeat-next text-secondary",title:W.toLocaleString(),children:["Next: ",W.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 ve(t.id,"active"),disabled:Me.has(t.id),title:"Activate",children:[e.jsx(bt,{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 ha(t.id,t.name),disabled:Me.has(t.id),title:"Run Now","aria-label":`Run now for ${t.name}`,children:[e.jsx(Ze,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Run Now"})]}),e.jsxs("button",{className:"btn btn-sm",onClick:()=>void ve(t.id,"paused"),disabled:Me.has(t.id),title:"Pause",children:[e.jsx(Kt,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Pause"})]})]}),t.state==="paused"&&e.jsxs("button",{className:"btn btn-sm",onClick:()=>void ve(t.id,"active"),disabled:Me.has(t.id),title:"Resume",children:[e.jsx(bt,{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:()=>ue(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(Ze,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Running"})]}),e.jsxs("button",{className:"btn btn-sm",onClick:()=>void ve(t.id,"paused"),disabled:Me.has(t.id),title:"Pause",children:[e.jsx(Kt,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Pause"})]})]}),t.state==="error"&&e.jsxs("button",{className:"btn btn-sm",onClick:()=>void ve(t.id,"active"),disabled:Me.has(t.id),title:"Retry",children:[e.jsx(bt,{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:()=>ue(t.id),title:`View details for ${t.name}`,"aria-label":`View details for ${t.name}`,children:[e.jsx(rs,{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 ia(t.id,t.name),title:"Delete",children:[e.jsx(Ua,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Delete"})]})]})]})]},t.id)})})})}),e.jsx("div",{className:`agents-split-detail${d&&!$?" agents-split-detail--hidden-mobile":""}`,children:$?e.jsx(a.Suspense,{fallback:null,children:e.jsx(ea,{inline:!0,showInlineBackButton:d,agentId:$,projectId:r,onClose:We,addToast:n,onChildClick:Et,initialTab:ae,initialRunId:F,preferActiveRun:me,onMutationSuccess:ma},$)}):e.jsxs("div",{className:"agents-detail-empty-state",children:[e.jsx(St,{size:48}),e.jsx("h3",{children:"Select an agent"}),e.jsx("p",{children:"Choose an agent from the sidebar to view details"})]})})]})]})}export{Vs as AgentsView};
@@ -0,0 +1 @@
1
+ import{r as n,a as en,j as t,R as tn}from"./vendor-react-K0fH_qHe.js";import{i as yt,b5 as fs,t as Es,b6 as sn,b7 as gs,b8 as nn,w as Kt,b9 as qe,ba as an,bb as rn,bc as on,bd as cn,be as ln,bf as ps,bg as dn,s as Ds,bh as un,bi as mn,bj as _t,bk as hn,bl as fn,bm as gn,bn as pn,k as $s,bo as bn,bp as vn,p as xn,bq as yn,br as wn,u as Sn,bs as Cn,ac as Is,ad as Ps,bt as Nn,bu as kn,S as jn,Y as Ut,P as it,J as at,ap as Mn,bv as bs,bw as vs,bx as xs,B as ot,a as ys,a9 as Rn,aa as An,aW as xt,by as Tn,bz as En,aT as Dn,bA as ws,bB as $n,T as In,bC as Ss,bD as Pn,h as Ln,j as Cs,m as Fn}from"./index-DzSLVOnp.js";import"./vendor-xterm-DzcZoU0P.js";import"./vendor-codemirror-jBKmHyH0.js";const Ot="kb-chat-active-session";function Ns(s){const r=typeof s=="string"?s.trim():"",l=r.indexOf("/");return!r||l<=0||l>=r.length-1?{}:{modelProvider:r.slice(0,l),modelId:r.slice(l+1)}}function zn(s){const r=s?.toolCalls;if(!Array.isArray(r))return;const l=r.map(i=>{if(!i||typeof i!="object")return null;const u=i,x=typeof u.toolName=="string"?u.toolName:"";if(!x)return null;const R=u.args;return{toolName:x,...R&&typeof R=="object"?{args:R}:{},isError:!!u.isError,result:u.result,status:"completed"}}).filter(i=>i!==null);return l.length>0?l:void 0}function _n(s){const r=s?.fallback;if(!r||typeof r!="object")return;const l=r,i=typeof l.primaryModel=="string"?l.primaryModel:"",u=typeof l.fallbackModel=="string"?l.fallbackModel:"",x=l.triggerPoint;if(!(!i||!u||x!=="session-creation"&&x!=="prompt-time"))return{primaryModel:i,fallbackModel:u,triggerPoint:x}}function Un(s){const r=s?.failureInfo;if(!r||typeof r!="object")return;const l=r,i=typeof l.summary=="string"?l.summary.trim():"";if(!i)return;const u=(()=>{const x=l.reference;if(!x||typeof x!="object")return;const R=x,E=typeof R.kind=="string"?R.kind.trim():"",D=typeof R.id=="string"?R.id.trim():"";if(!(!E||!D))return{kind:E,id:D,...typeof R.label=="string"&&R.label.trim()?{label:R.label.trim()}:{}}})();return{summary:i,...typeof l.errorClass=="string"&&l.errorClass.trim()?{errorClass:l.errorClass.trim()}:{},...typeof l.code=="string"&&l.code.trim()?{code:l.code.trim()}:{},...typeof l.detail=="string"&&l.detail.trim()?{detail:l.detail.trim()}:{},...u?{reference:u}:{}}}function ks(s){return typeof s=="string"?{summary:s.trim()||"Failed to get response"}:{summary:typeof s.summary=="string"&&s.summary.trim()?s.summary.trim():"Failed to get response",...typeof s.errorClass=="string"&&s.errorClass.trim()?{errorClass:s.errorClass.trim()}:{},...typeof s.code=="string"&&s.code.trim()?{code:s.code.trim()}:{},...typeof s.detail=="string"&&s.detail.trim()?{detail:s.detail.trim()}:{},...s.reference?{reference:s.reference}:{}}}function Ht(s){return{id:s.id,sessionId:s.sessionId,role:s.role,content:s.content,thinkingOutput:s.thinkingOutput,toolCalls:zn(s.metadata),fallbackInfo:_n(s.metadata),failureInfo:Un(s.metadata),attachments:s.attachments,createdAt:s.createdAt}}function On(s,r){const[l,i]=n.useState([]),[u,x]=n.useState(null),[R,E]=n.useState(!0),[D,C]=n.useState([]),[Q,S]=n.useState(!1),[L,g]=n.useState(!1),[ee,N]=n.useState(""),[_,b]=n.useState(""),[M,A]=n.useState([]),[T,$]=n.useState(""),[J,Y]=n.useState(""),[z,h]=n.useState(!0),[p,o]=n.useState(new Map),c=n.useRef(null),m=n.useRef(!1),y=n.useRef(""),k=n.useRef(null),Z=n.useRef(l),F=n.useRef(u),G=n.useRef(L);Z.current=l,F.current=u,G.current=L,n.useEffect(()=>{y.current=T},[T]);const ke=n.useRef(new Set),ue=n.useRef(0),ve=n.useRef(s);ve.current!==s&&(ve.current=s,ue.current++),n.useEffect(()=>{const f=ue.current;yt(void 0,s).then(v=>{if(ue.current!==f)return;const w=new Map;for(const P of v)w.set(P.id,P);o(w)}).catch(()=>{})},[s]);const ie=n.useCallback(async()=>{E(!0);try{const v=[...(await fs(s)).sessions].sort((w,P)=>new Date(P.updatedAt).getTime()-new Date(w.updatedAt).getTime());i(v)}catch{}finally{E(!1)}},[s]);n.useEffect(()=>{ie()},[ie]);const Ue=n.useRef(()=>{}),Fe=n.useRef(!1);n.useEffect(()=>{Fe.current=!1},[s]),n.useEffect(()=>{if(R||Fe.current||F.current)return;const f=Es(Ot,s);if(!f){Fe.current=!0;return}const v=l.find(w=>w.id===f);if(v){Fe.current=!0,Ue.current(f,v);return}Fe.current=!0},[R,l,s]);const te=n.useCallback(async(f,v)=>{S(!0);try{const w=await sn(f,{limit:50,...v},s),P=w.messages.map(Ht);v?.offset&&v.offset>0?C(se=>[...P,...se]):C(P),h(w.messages.length>=50)}catch{}finally{S(!1)}},[s]),me=n.useCallback(()=>{k.current?.(),k.current=null,y.current="",$(""),N(""),b(""),A([]),g(!1)},[]),wt=n.useCallback(()=>{y.current="",$("")},[]),ne=n.useCallback(()=>{const f=y.current.trim();f&&(y.current="",$(""),ze.current(f))},[]),oe=n.useCallback((f,v,w)=>{if(c.current||!f)return!0;m.current=!1,v&&(N(v.streamingText),b(v.streamingThinking),A(v.toolCalls)),g(!0);const{handlers:P}=gs({sessionId:f,tempUserMessageId:"",setStreamingText:N,setStreamingThinking:b,setStreamingToolCalls:A,cancelStreamingFlushesRef:k,addToast:w?.silent?void 0:r,onFallbackSession:(H,ae)=>{const U=Ns(H.fallbackModel);i(K=>K.map(W=>W.id===ae?{...W,...U}:W)),x(K=>K&&K.id===ae?{...K,...U}:K)},onDone:()=>{N(""),b(""),A([]),g(!1),G.current=!1,c.current=null,te(f),ne()},onError:H=>{N(""),b(""),A([]),g(!1),G.current=!1,c.current=null;const ae=ks(H);w?.silent||r?.(ae.summary,"error"),te(f),ne()}}),se=nn(f,P,s,{...typeof v?.replayFromEventId=="number"?{lastEventId:v.replayFromEventId}:{}});return c.current=se,!0},[r,te,s,ne]),Oe=n.useCallback((f,v)=>{const w=F.current?.id??null;if(f&&w===f&&!v)return;c.current&&(c.current.close(),c.current=null);const P=v??l.find(se=>se.id===f);x(P||null),me(),h(!0),f?te(f):C([]),P?.isGenerating&&oe(P.id,P.inFlightGeneration),f?Kt(Ot,f,s):qe(Ot,s)},[oe,l,te,s,me]);Ue.current=Oe;const ct=n.useCallback(async f=>{const v=await an(f,s);c.current&&(c.current.close(),c.current=null);const w={id:v.session.id,title:v.session.title,agentId:v.session.agentId,status:v.session.status,modelProvider:v.session.modelProvider,modelId:v.session.modelId,createdAt:v.session.createdAt,updatedAt:v.session.updatedAt};return i(P=>P.some(se=>se.id===w.id)?P:[w,...P]),me(),Oe(w.id,w),C([]),w},[s,me,Oe]),je=n.useCallback(async f=>{await rn(f,{status:"archived"},s),i(v=>v.filter(w=>w.id!==f)),u?.id===f&&(x(null),C([]))},[u,s]),Me=n.useCallback(async f=>{u?.id===f&&c.current&&(c.current.close(),c.current=null),await on(f,s),i(v=>v.filter(w=>w.id!==f)),u?.id===f&&(x(null),C([]))},[u,s]),Je=n.useCallback(async()=>{!u||!z||await te(u.id,{offset:D.length})},[u,z,te,D.length]),He=n.useCallback(()=>{u&&(m.current=!0,k.current?.(),k.current=null,c.current?.close(),c.current=null,cn(u.id,s).catch(()=>{}),g(!1),N(""),b(""),A([]))},[u,s]),ze=n.useRef(()=>{}),Re=ln(),xe=n.useCallback(async f=>{try{await ie();const v=await ps(f,s);F.current?.id===f&&x(w=>!w||w.id!==f?w:{...w,...v.session}),v.session.isGenerating?(N(""),b(""),A([]),g(!0),G.current=!0,oe(f,v.session.inFlightGeneration,{silent:!0})):(N(""),b(""),A([]),g(!1),G.current=!1,await te(f))}catch{}},[oe,te,s,ie]),ye=n.useCallback((f,v)=>{if(!u)return;if(G.current){y.current=f,$(f);return}m.current=!1,c.current&&(c.current.close(),c.current=null);const w=`temp-${Date.now()}`,P={id:w,sessionId:u.id,role:"user",content:f,createdAt:new Date().toISOString()};C(H=>[...H,P]),N(""),b(""),A([]),g(!0);const{handlers:se}=gs({sessionId:u.id,tempUserMessageId:w,setStreamingText:N,setStreamingThinking:b,setStreamingToolCalls:A,cancelStreamingFlushesRef:k,addToast:r,onFallbackSession:(H,ae)=>{const U=Ns(H.fallbackModel);i(K=>K.map(W=>W.id===ae?{...W,...U}:W)),x(K=>K&&K.id===ae?{...K,...U}:K)},onDone:({messageId:H,message:ae,accumulated:U})=>{const K=ae?Ht(ae):{id:H||`msg-${Date.now()}`,sessionId:u.id,role:"assistant",content:U.text,thinkingOutput:U.thinking,toolCalls:U.toolCalls.length>0?U.toolCalls:void 0,fallbackInfo:U.fallbackInfo,createdAt:new Date().toISOString()};ke.current.add(K.id),C(W=>[...W,K]),N(""),b(""),A([]),g(!1),G.current=!1,c.current=null,setTimeout(()=>{ke.current.delete(K.id)},1e3),ie(),ne()},onError:(H,ae)=>{const U=ks(H),K=typeof H=="string"?H:U.summary,W=un(K);C(V=>{const O=V.filter(q=>q.id!==ae);return W?O:[...O,{id:`error-${Date.now()}`,sessionId:u.id,role:"assistant",content:U.summary,failureInfo:U,createdAt:new Date().toISOString()}]}),N(""),b(""),A([]),g(!1),G.current=!1,c.current=null,console.error("[useChat] Stream error:",H),W?(console.info("[useChat] Suppressed tab-suspension stream error:",H),u?.id&&(N(""),b(""),A([]),g(!0),G.current=!0,xe(u.id))):(r?.(U.summary,"error"),ie()),m.current||ne()}});c.current=dn(u.id,f,se,v,s)},[u,s,ie,r,oe,xe,ne]);ze.current=ye;const fe=J?l.filter(f=>f.title?.toLowerCase().includes(J.toLowerCase())||f.agentId.toLowerCase().includes(J.toLowerCase())):l;return n.useEffect(()=>{if(!F.current?.isGenerating||(c.current||oe(F.current.id,F.current.inFlightGeneration),!G.current||c.current||!F.current))return;const f=setInterval(async()=>{if(!G.current||c.current||!F.current){clearInterval(f);return}try{(await fs(s)).sessions.find(P=>P.id===F.current?.id)?.isGenerating||(clearInterval(f),await te(F.current.id),N(""),b(""),A([]),g(!1),G.current=!1,ne())}catch{}},3e3);return()=>clearInterval(f)},[oe,te,s,u,ne]),n.useEffect(()=>Re.onBecameVisible(()=>{const v=F.current;if(!v||c.current)return;const w=ue.current;ps(v.id,s).then(P=>{if(!(ue.current!==w||c.current)){if(P.session.isGenerating){N(""),b(""),A([]),g(!0),G.current=!0,oe(v.id,P.session.inFlightGeneration,{silent:!0});return}G.current&&(N(""),b(""),A([]),g(!1),G.current=!1,ne(),te(v.id))}}).catch(()=>{})}),[oe,te,s,Re,ne]),n.useEffect(()=>{const f=ue.current,v=s?`?projectId=${encodeURIComponent(s)}`:"",w=()=>ue.current!==f,P=W=>{if(w())return;const V=JSON.parse(W.data);i(O=>O.some(q=>q.id===V.id)?O:[V,...O])},se=W=>{if(w())return;const V=JSON.parse(W.data);i(O=>[...O.map(re=>re.id===V.id?V:re)]),F.current?.id===V.id&&(x(V),V.isGenerating&&!c.current&&oe(V.id,V.inFlightGeneration))},H=W=>{if(w())return;const{id:V}=JSON.parse(W.data);i(O=>O.filter(q=>q.id!==V)),F.current?.id===V&&(x(null),C([]))},ae=W=>{if(w())return;const V=JSON.parse(W.data),O=Ht(V);if(!ke.current.has(O.id)){if(F.current?.id===O.sessionId&&G.current&&!c.current&&O.role==="assistant"){C(q=>q.some(re=>re.id===O.id)?q:[...q,O]),N(""),b(""),A([]),g(!1),G.current=!1,ne();return}F.current?.id===O.sessionId&&!G.current&&C(q=>{if(q.some(re=>re.id===O.id))return q;if(O.role==="user"){const re=q.findIndex(we=>we.role==="user"&&we.id.startsWith("temp-")&&we.content.trim()===O.content.trim());if(re>=0){const we=[...q];return we[re]=O,we}}return[...q,O]})}},U=W=>{if(w())return;const{id:V}=JSON.parse(W.data);C(O=>O.filter(q=>q.id!==V))};return Ds(`/api/events${v}`,{events:{"chat:session:created":P,"chat:session:updated":se,"chat:session:deleted":H,"chat:message:added":ae,"chat:message:deleted":U}})},[oe,s,ne]),n.useEffect(()=>()=>{c.current&&(c.current.close(),c.current=null)},[]),{sessions:l,activeSession:u,sessionsLoading:R,messages:D,messagesLoading:Q,isStreaming:L,streamingText:ee,streamingThinking:_,streamingToolCalls:M,pendingMessage:T,selectSession:Oe,createSession:ct,archiveSession:je,deleteSession:Me,sendMessage:ye,stopStreaming:He,clearPendingMessage:wt,loadMoreMessages:Je,hasMoreMessages:z,searchQuery:J,setSearchQuery:Y,filteredSessions:fe,refreshSessions:ie,agentsMap:p}}const Pe="fusion:chat-active-room";function Wt(s){return[...s].sort((r,l)=>new Date(l.updatedAt).getTime()-new Date(r.updatedAt).getTime())}function rt(s,r){const l=s.findIndex(u=>u.id===r.id);if(l===-1)return Wt([r,...s]);const i=[...s];return i[l]=r,Wt(i)}function Le(s){try{return JSON.parse(s.data)}catch{return null}}function Hn(s,r){return{id:`temp-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,roomId:s,role:"user",content:r,thinkingOutput:null,metadata:null,senderAgentId:null,mentions:[],createdAt:new Date().toISOString()}}function Bn(s,r){const[l,i]=n.useState([]),[u,x]=n.useState(!0),[R,E]=n.useState(null),[D,C]=n.useState(null),[Q,S]=n.useState([]),[L,g]=n.useState([]),[ee,N]=n.useState(!1),_=n.useRef(l),b=n.useRef(D),M=n.useRef(0),A=n.useRef(s);_.current=l,b.current=D,A.current!==s&&(A.current=s,M.current+=1);const T=n.useCallback(async(p,o=!0)=>{if(!p){S([]),g([]),N(!1);return}o&&g([]),N(!0);try{const[c,m]=await Promise.all([mn(p.id,s),_t(p.id,{limit:100},s)]);S(c.members),g(m.messages)}catch{S([]),g([])}finally{N(!1)}},[s]),$=n.useCallback(async()=>{x(!0);try{const p=await hn({},s),o=Wt(p.rooms);i(o),E(null);const c=Es(Pe,s);if(c){const m=o.find(y=>y.id===c)??null;m?(C(m),T(m,!0)):qe(Pe,s)}}catch(p){const o=p instanceof Error?p.message:"Failed to load chat rooms";E(o),r?.(o,"error")}finally{x(!1)}},[r,T,s]),J=n.useCallback(p=>{if(!p){C(null),qe(Pe,s),T(null,!0);return}const o=_.current.find(c=>c.id===p)??null;C(o),o&&(Kt(Pe,o.id,s),T(o,!0))},[T,s]),Y=n.useCallback(async p=>{const c=(await fn({name:p.name,memberAgentIds:p.memberAgentIds},s)).room;return i(m=>rt(m,c)),C(c),Kt(Pe,c.id,s),await T(c,!0),c},[T,s]),z=n.useCallback(async p=>{await gn(p,s),i(o=>o.filter(c=>c.id!==p)),b.current?.id===p&&(C(null),S([]),g([]),qe(Pe,s))},[s]),h=n.useCallback(async(p,o)=>{const c=b.current,m=c?.id;if(!m)throw new Error("Select a room before sending a message");const y=Hn(m,p);b.current?.id===m&&g(k=>[...k,y]);try{const k=await pn(m,{content:p,...o?.attachments?{attachments:o.attachments}:{}},s);k.message?.createdAt&&c&&i(F=>rt(F,{...c,updatedAt:k.message.createdAt})),b.current?.id===m&&g(F=>F.map(G=>G.id===y.id?k.message:G));const Z=await _t(m,{limit:100},s);if(b.current?.id!==m)return;g(Z.messages)}catch(k){try{const Z=await _t(m,{limit:100},s);b.current?.id===m&&g(Z.messages)}catch{b.current?.id===m&&g(Z=>Z.filter(F=>F.id!==y.id))}throw k}},[s]);return n.useEffect(()=>{$()},[$]),n.useEffect(()=>{const p=M.current,o=s?`/api/events?projectId=${encodeURIComponent(s)}`:"/api/events";return Ds(o,{onReconnect:()=>{$()},events:{"chat:room:created":c=>{if(M.current!==p)return;const m=Le(c);m&&i(y=>rt(y,m))},"chat:room:updated":c=>{if(M.current!==p)return;const m=Le(c);m&&(i(y=>rt(y,m)),b.current?.id===m.id&&C(m))},"chat:room:deleted":c=>{if(M.current!==p)return;const m=Le(c);m?.id&&(i(y=>y.filter(k=>k.id!==m.id)),b.current?.id===m.id&&(C(null),S([]),g([]),qe(Pe,s)))},"chat:room:member:added":c=>{if(M.current!==p)return;const m=Le(c);!m||b.current?.id!==m.roomId||S(y=>y.some(k=>k.agentId===m.agentId)?y:[...y,m])},"chat:room:member:removed":c=>{if(M.current!==p)return;const m=Le(c);!m||b.current?.id!==m.roomId||S(y=>y.filter(k=>k.agentId!==m.agentId))},"chat:room:message:added":c=>{if(M.current!==p)return;const m=Le(c);m&&(i(y=>{const k=y.find(Z=>Z.id===m.roomId);return k?rt(y,{...k,updatedAt:m.createdAt}):y}),b.current?.id===m.roomId&&g(y=>{if(y.some(k=>k.id===m.id))return y;if(m.role==="user"){const k=y.findIndex(Z=>Z.role==="user"&&Z.id.startsWith("temp-")&&Z.content.trim()===m.content.trim());if(k>=0){const Z=[...y];return Z[k]=m,Z}}return[...y,m]}))},"chat:room:message:updated":c=>{if(M.current!==p)return;const m=Le(c);!m||b.current?.id!==m.roomId||g(y=>y.map(k=>k.id===m.id?m:k))},"chat:room:message:deleted":c=>{if(M.current!==p)return;const m=Le(c);m?.id&&g(y=>y.filter(k=>k.id!==m.id))}}})},[s,$]),n.useEffect(()=>{D&&(l.some(p=>p.id===D.id)||(C(null),S([]),g([]),qe(Pe,s)))},[D,s,l]),{rooms:l,roomsLoading:u,roomsError:R,activeRoom:D,activeRoomMembers:Q,messages:L,messagesLoading:ee,selectRoom:J,createRoom:Y,deleteRoom:z,sendRoomMessage:h,refreshRooms:$}}function Gn(s,r=[]){const l=s.trim().replace(/^#/,"");if(!l)return{ok:!1,error:"Room name is required."};if(/[A-Z]/.test(l))return{ok:!1,error:"Use lowercase letters only."};const i=l.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(u=>u.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 Kn({isOpen:s,onClose:r,onCreate:l,projectId:i,existingRoomNames:u=[]}){const[x,R]=n.useState(""),[E,D]=n.useState([]),[C,Q]=n.useState(""),[S,L]=n.useState([]),[g,ee]=n.useState(!1),[N,_]=n.useState(null),[b,M]=n.useState(!1),A=n.useRef(null),T=n.useRef(null);n.useEffect(()=>{s&&(T.current=document.activeElement instanceof HTMLElement?document.activeElement:null,ee(!0),_(null),yt(void 0,i).then(o=>D(o)).catch(()=>{D([]),_("Failed to load agents.")}).finally(()=>ee(!1)))},[s,i]),n.useEffect(()=>{if(!s){R(""),Q(""),L([]),_(null),M(!1);return}const o=window.requestAnimationFrame(()=>A.current?.focus());return()=>window.cancelAnimationFrame(o)},[s]),n.useEffect(()=>{if(!s)return;const o=c=>{c.key==="Escape"&&r()};return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[s,r]),n.useEffect(()=>{s||T.current?.focus()},[s]);const $=n.useMemo(()=>Gn(x,u),[x,u]),J=n.useMemo(()=>{const o=C.trim().toLowerCase();return o?E.filter(c=>c.name.toLowerCase().includes(o)):E},[E,C]),Y=n.useMemo(()=>E.filter(o=>S.includes(o.id)),[E,S]),z=$.ok&&S.length>0&&!b&&!g;if(!s)return null;const h=o=>{b||L(c=>c.includes(o)?c.filter(m=>m!==o):[...c,o])},p=async()=>{if(!$.ok){_($.error);return}if(S.length===0){_("Select at least one member.");return}_(null),M(!0);try{await l({name:$.name,displayName:`#${$.name}`,memberAgentIds:S}),r()}catch(o){_(o instanceof Error?o.message:"Failed to create room.")}finally{M(!1)}};return en.createPortal(t.jsx("div",{className:"modal-overlay open",onClick:o=>o.target===o.currentTarget&&r(),children:t.jsxs("div",{className:"modal modal-lg create-room-modal",role:"dialog","aria-modal":"true","aria-label":"Create room",onClick:o=>o.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:A,id:"create-room-name",className:"input",value:x,disabled:b,onChange:o=>{const c=o.target.value.replace(/^#/,"").replace(/\s+/g,"-").toLowerCase();R(c)}})]}),!$.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:C,disabled:b,onChange:o=>Q(o.target.value)})]}),Y.length>0&&t.jsx("div",{className:"create-room-modal-selected","data-testid":"create-room-selected-chips",children:Y.map(o=>t.jsxs("button",{type:"button",className:"btn btn-sm create-room-modal-chip",onClick:()=>h(o.id),disabled:b,children:[o.name," ×"]},o.id))}),t.jsx("div",{className:"create-room-modal-member-list","data-testid":"create-room-member-list",children:g?t.jsx("div",{className:"create-room-modal-empty",children:"Loading agents..."}):J.length===0?t.jsx("div",{className:"create-room-modal-empty",children:E.length===0?"No agents in this project yet.":"No agents match your search."}):J.map(o=>{const c=S.includes(o.id);return t.jsxs("button",{type:"button",className:`create-room-modal-member-row${c?" create-room-modal-member-row--selected":""}`,onClick:()=>h(o.id),disabled:b,children:[t.jsx($s,{agent:o,size:20}),t.jsx("span",{children:o.name}),t.jsx("span",{className:"create-room-modal-member-role",children:o.role})]},o.id)})}),N&&t.jsx("div",{className:"form-group",children:t.jsx("div",{className:"form-error",children:N})}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:r,disabled:b,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>void p(),disabled:!z,children:b?"Creating...":"Create room"})]})]})}),document.body)}const Wn=320;function Vn(s){return Math.min(s,Wn)}function Ls(s){const r=new Date(s),i=new Date().getTime()-r.getTime(),u=Math.floor(i/1e3),x=Math.floor(u/60),R=Math.floor(x/60),E=Math.floor(R/24);return u<60?"just now":x<60?`${x}m ago`:R<24?`${R}h ago`:E<7?`${E}d ago`:r.toLocaleDateString()}function js(s,r){if(!s||!r)return null;const l=r.toLowerCase();if(l.includes("claude")){let u=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 u=u.replace(/\s+/g," "),u.length>30?u.slice(0,30)+"…":u}if(l.includes("gpt")||l.includes("openai")){const u=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 u.length>30?u.slice(0,30)+"…":u}if(l.includes("gemini")){const u=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 u.length>30?u.slice(0,30)+"…":u}const i=r.replace(/-/g," ").replace(/^\w/,u=>u.toUpperCase()).replace(/\s+/g," ").trim();return i.length>30?i.slice(0,30)+"…":i}function vt(s,r){return s.length<=r?s:`${s.slice(0,r)}…`}function qn(s){if(!s)return null;const r=Object.entries(s);return r.length===0?null:r.map(([l,i])=>{const u=typeof i=="string"?i:(()=>{try{return JSON.stringify(i)}catch{return String(i)}})();return`${l}=${vt(u,50)}`}).join(", ")}function Xn(s){if(s===void 0)return null;if(typeof s=="string")return vt(s,200);try{return vt(JSON.stringify(s),200)}catch{return vt(String(s),200)}}function Jn(s){if(!s)return null;if(s.kind==="mailbox"||s.kind==="mailbox-message"){const r=typeof window>"u"?"/":window.location.pathname||"/",l=new URLSearchParams(typeof window>"u"?"":window.location.search);return l.set("view","mailbox"),l.set("mailbox-message",s.id),`${r}?${l.toString()}#message-${encodeURIComponent(s.id)}`}return null}function Yn(s){if(!s)return null;const r=s.label??`${s.kind} ${s.id}`,l=Jn(s),i=`chat-failure-reference-${s.kind}-${s.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}),l?t.jsx("a",{className:"btn btn-sm chat-message-failure-reference-link",href:l,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:s.kind})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"ID"}),t.jsx("dd",{children:s.id})]}),s.label&&t.jsxs("div",{children:[t.jsx("dt",{children:"Label"}),t.jsx("dd",{children:s.label})]})]})]})]})}function Fs(s){if(!s||s.length===0)return null;const r=(S,L)=>{const g=S.status==="running",ee=S.status==="completed"&&S.isError,N=qn(S.args),_=Xn(S.result),b=g?N:_?`result: ${_}`:N?`args: ${N}`:null,M=g?"running":ee?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${g?" chat-tool-call--running":""}${ee?" chat-tool-call--error":""}`,open:g,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:S.toolName,children:S.toolName}),b&&t.jsx("span",{className:"chat-tool-call-preview",title:b,children:b}),t.jsx("span",{className:"chat-tool-call-status-text",children:M})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[N&&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:N})]}),_&&t.jsxs("div",{className:`chat-tool-call-row${ee?" 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:_})]})]})]},`${S.toolName}-${L}`)},l="chat-tool-calls";if(s.length===1)return t.jsxs("div",{className:l,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(Ss,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:"Tool calls"})]}),r(s[0],0)]});const i=s.filter(S=>S.status==="running").length,u=s.filter(S=>S.status==="completed"&&S.isError).length,x=i>0,R=Array.from(new Set(s.map(S=>S.toolName))),E=R.slice(0,5),D=Math.max(0,R.length-E.length),C=D>0?`${E.join(", ")}, +${D} more`:E.join(", "),Q=x?`(${i} running)`:u>0?`(${u} ${u===1?"error":"errors"})`:null;return t.jsx("div",{className:l,"data-testid":"chat-tool-calls",children:t.jsxs("details",{className:"chat-tool-calls-group","data-testid":"chat-tool-calls-group",open:x,children:[t.jsxs("summary",{className:"chat-tool-calls-group-summary",children:[t.jsx(Ss,{size:12,"aria-hidden":"true"}),t.jsxs("span",{className:"chat-tool-calls-count",children:[s.length," tool calls"]}),t.jsx("span",{className:"chat-tool-calls-names",title:C,children:C}),Q&&t.jsx("span",{className:"chat-tool-calls-group-status",children:Q})]}),s.map((S,L)=>r(S,L))]})})}const zs={p:({children:s,...r})=>t.jsx("p",{...r,children:ws(s)}),li:({children:s,...r})=>t.jsx("li",{...r,children:ws(s)}),pre:({children:s,...r})=>t.jsx("pre",{...r,className:"chat-markdown-pre",children:s}),code:({children:s,...r})=>{const l=typeof s=="string"?s:tn.Children.toArray(s).join(""),i=xt(l);return i.length===1&&typeof i[0]=="string"?t.jsx("code",{...r,children:s}):t.jsx("code",{...r,children:i})},table:({children:s,...r})=>t.jsx("table",{...r,className:"chat-markdown-table",children:s})},Xe="__fn_agent__",Qn=280,pt=180,bt=500,Ms="fusion:chat-sidebar-width",Bt="fusion:chat-scope",Zn="fusion:chat-draft:";function Rs(s,r){return r?`${Zn}${s}:${r}`:null}function As(s){if(!s)return"";try{return localStorage.getItem(s)??""}catch{return""}}const ea=["image/png","image/jpeg","image/gif","image/webp","text/plain","application/json","text/yaml","text/markdown","text/csv","application/xml","text/x-log"];function Ts(s){const r=/(^|[\s])\/([^\s]*)$/.exec(s);if(!r)return null;const l=r[1]??"",i=r[2]??"",u=r.index+l.length;return{filter:i,start:u,end:s.length}}function ta(s,r){const l=s.slice(0,r),i=/(^|[\s\n])@([\w-]*)$/.exec(l);if(!i)return null;const u=i[2]??"",x=l.length-u.length-1;return{filter:u,start:x,end:r}}function sa({projectId:s,onClose:r,onCreate:l}){const[i,u]=n.useState("agent"),[x,R]=n.useState([]),[E,D]=n.useState(!0),[C,Q]=n.useState(""),[S,L]=n.useState([]),[g,ee]=n.useState(!0),[N,_]=n.useState(""),[b,M]=n.useState([]),[A,T]=n.useState([]);n.useEffect(()=>{let h=!1;return D(!0),yt(void 0,s).then(p=>{h||R(p)}).catch(()=>{h||R([])}).finally(()=>{h||D(!1)}),()=>{h=!0}},[s]),n.useEffect(()=>{ee(!0),Ln().then(h=>{L(h.models),M(h.favoriteProviders),T(h.favoriteModels)}).catch(()=>{L([]),M([]),T([])}).finally(()=>{ee(!1)})},[]);const $=n.useCallback(async h=>{const p=b,c=p.includes(h)?p.filter(m=>m!==h):[h,...p];M(c);try{await Cs({favoriteProviders:c,favoriteModels:A})}catch{M(p)}},[b,A]),J=n.useCallback(async h=>{const p=A,c=p.includes(h)?p.filter(m=>m!==h):[h,...p];T(c);try{await Cs({favoriteProviders:b,favoriteModels:c})}catch{T(p)}},[A,b]),Y=h=>{if(h.preventDefault(),i==="agent"){if(!C)return;l({agentId:C});return}if(!N)return;const p=N.indexOf("/");if(p<=0)return;const o=N.slice(0,p),c=N.slice(p+1);l({agentId:Xe,modelProvider:o,modelId:c})},z=i==="agent"?!C:!N;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:h=>h.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:()=>{u("agent"),_("")},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:()=>{u("model"),Q("")},children:"Model"})]}),t.jsxs("form",{onSubmit:Y,children:[i==="agent"&&t.jsxs("label",{className:"chat-new-dialog-model-label",children:["Agent",E?t.jsx("div",{className:"chat-new-dialog-loading",children:"Loading agents..."}):x.length===0?t.jsx("div",{className:"chat-new-dialog-empty",children:"No agents available"}):t.jsx("div",{className:"chat-new-dialog-agent-list",children:x.map(h=>t.jsxs("button",{type:"button",className:`chat-new-dialog-agent-item${C===h.id?" chat-new-dialog-agent-item--selected":""}`,onClick:()=>Q(h.id),"data-testid":`agent-option-${h.id}`,children:[t.jsx(ot,{size:16}),t.jsx("span",{className:"chat-new-dialog-agent-name",children:h.name}),t.jsx("span",{className:"chat-new-dialog-agent-role",children:h.role})]},h.id))})]}),i==="model"&&t.jsx("div",{className:"chat-new-dialog-model-dropdown","data-testid":"chat-new-dialog-model-section",children:g?t.jsx("div",{className:"chat-new-dialog-loading",children:"Loading models..."}):t.jsx(Fn,{models:S,value:N,onChange:_,label:"Model",placeholder:"Select a model",favoriteProviders:b,onToggleFavorite:$,favoriteModels:A,onToggleModelFavorite:J})}),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:z,children:"Create"})]})]})]})})}const Gt=n.memo(function({message:r,forcePlain:l,agentName:i,hideAssistantIdentity:u,showAssistantModelTag:x,activeModelTag:R,activeModelProvider:E,activeSessionId:D,mentionAgentsByName:C,roomContext:Q,copyAction:S}){const L=r.role==="assistant",g=L?r.failureInfo:void 0,ee=L&&(!u||!!g),N=n.useMemo(()=>{if(L)return null;const M=r.content,A=/@([\w-]+)/g,T=[];let $=0,J=A.exec(M);for(;J;){const[Y,z=""]=J,h=J.index;h>$&&T.push(M.slice($,h));const p=z.replace(/_/g," ").toLowerCase(),o=C.get(p);if(o){const c=!!(Q&&!Q.memberIds.has(o.id)),m=c?`Not a member of ${Q?.roomName}`:void 0;T.push(t.jsxs("span",{className:`chat-mention-chip${c?" chat-mention-chip--non-member":""}`,title:m,"aria-label":m,children:["@",o.name.replace(/\s+/g,"_")]},`${o.id}-${h}`))}else T.push(Y);$=h+Y.length,J=A.exec(M)}return $<M.length&&T.push(M.slice($)),T.length===0?M:T},[L,r.content,C,Q]),_=n.useMemo(()=>{const M=r.attachments;if(!M||M.length===0||!D)return null;const A=`/api/chat/sessions/${encodeURIComponent(D)}/attachments/`;return t.jsx("div",{className:"chat-message-attachments",children:M.map(T=>{const $=T.mimeType.startsWith("image/"),J=T.id||T.filename,Y=`${A}${encodeURIComponent(T.filename)}`;return $?t.jsx("a",{className:"chat-message-attachment-link","data-testid":"chat-message-attachment",href:Y,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{className:"chat-message-attachment",src:Y,alt:T.originalName})},J):t.jsxs("a",{className:"chat-message-attachment-file","data-testid":"chat-message-attachment",href:Y,target:"_blank",rel:"noopener noreferrer",children:[t.jsx($n,{size:14}),t.jsx("span",{children:T.originalName})]},J)})})},[r.attachments,D]),b=n.useMemo(()=>L?g?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:g.summary}),(g.errorClass||g.code)&&t.jsxs("div",{className:"chat-message-failure-badges",children:[g.errorClass&&t.jsx("span",{className:"chat-message-failure-badge",children:g.errorClass}),g.code&&t.jsx("span",{className:"chat-message-failure-badge",children:g.code})]}),(g.detail||g.reference)&&t.jsxs("details",{className:"chat-message-failure-details",children:[t.jsxs("summary",{children:[t.jsx(In,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Failure details"})]}),g.detail&&t.jsx("pre",{className:"chat-message-failure-detail",children:xt(g.detail)}),Yn(g.reference)]})]}):l?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(Is,{remarkPlugins:[Ps],components:zs,children:r.content})}):null,[g,l,L,r.content]);return t.jsxs("div",{className:`chat-message chat-message--${r.role}${g?" chat-message--failure":""}`,"data-testid":`chat-message-${r.id}`,children:[ee&&t.jsxs("div",{className:"chat-message-avatar",children:[E?t.jsx(it,{provider:E,size:"sm"}):t.jsx(ot,{size:14}),t.jsx("span",{children:i}),x&&R&&t.jsx("span",{className:"chat-model-tag",children:R})]}),L?b:t.jsx("div",{className:"chat-message-content",children:N}),!g&&S,Fs(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:xt(r.thinkingOutput)})]}),_,t.jsx("div",{className:"chat-message-time",children:Ls(r.createdAt)})]})});function ca({projectId:s,addToast:r,experimentalFeatures:l}){const{activeSession:i,sessionsLoading:u,messages:x,messagesLoading:R,isStreaming:E,streamingText:D,streamingThinking:C,streamingToolCalls:Q,selectSession:S,createSession:L,archiveSession:g,deleteSession:ee,sendMessage:N,stopStreaming:_,pendingMessage:b,clearPendingMessage:M,searchQuery:A,setSearchQuery:T,filteredSessions:$}=On(s,r),[J,Y]=n.useState(!1),z=l?.chatRooms===!0,[h,p]=n.useState(()=>{try{if(localStorage.getItem(Bt)==="rooms"&&z)return"rooms"}catch{}return"direct"}),o=Bn(s,r),[c,m]=n.useState(()=>{const e=Rs(h,h==="rooms"?o.activeRoom?.id:i?.id);return As(e)}),[y,k]=n.useState(null),[Z,F]=n.useState(null),[G,ke]=n.useState(null),[ue,ve]=n.useState(!0),[ie,Ue]=n.useState(Qn),[Fe,te]=n.useState(!1),[me,wt]=n.useState(new Map),[ne,oe]=n.useState([]),[Oe,ct]=n.useState(!0),[je,Me]=n.useState(!1),[Je,He]=n.useState(""),[ze,Re]=n.useState(0),[xe,ye]=n.useState(""),[fe,f]=n.useState(!1),[v,w]=n.useState(0),[P,se]=n.useState(-1),[H,ae]=n.useState(!1),[U,K]=n.useState([]),[W,V]=n.useState(!1),[O,q]=n.useState(!1),[re,we]=n.useState({}),[lt,Be]=n.useState(!1),{pushNav:Vt}=bn(),[,Ye]=n.useState(!1),[_s,Us]=n.useState({top:0,left:0}),B=vn({projectId:s}),St=n.useCallback(e=>{if(!e||!B.mentionActive)return;const a=e.getBoundingClientRect();Us({top:a.top-260,left:a.left+8})},[B.mentionActive]),qt=n.useRef(null),Xt=n.useRef(null),Ae=n.useRef(!1),Ct=n.useRef(null),Jt=n.useRef(null),Te=n.useRef(null),Ee=n.useRef(null),Se=n.useRef(null),ge=n.useRef(null),ce=n.useRef(null),Yt=n.useRef(null),Qt=n.useRef([]),Qe=n.useRef(0),Ze=n.useRef(new Map),I=xn()==="mobile";n.useEffect(()=>{try{const e=localStorage.getItem(Ms);if(!e)return;const a=Number.parseInt(e,10);if(Number.isNaN(a))return;const d=Math.max(pt,Math.min(bt,a));Ue(d)}catch{}},[]),n.useEffect(()=>{try{const e=localStorage.getItem(Bt);if(e==="direct"){p("direct");return}e==="rooms"&&z&&p("rooms")}catch{}},[z]),n.useEffect(()=>{if(!z&&h==="rooms"){p("direct");return}try{localStorage.setItem(Bt,h)}catch{}},[z,h]);const le=Rs(h,h==="rooms"?o.activeRoom?.id:i?.id),Nt=n.useRef(le);n.useEffect(()=>{le!==Nt.current&&(Nt.current=le,m(As(le)))},[le]),n.useEffect(()=>{if(!(!le||Nt.current!==le))try{if(c){localStorage.setItem(le,c);return}localStorage.removeItem(le)}catch{}},[le,c]);const de=z&&h==="rooms"&&!!o.activeRoom,{keyboardOverlap:dt,viewportHeight:Zt,viewportOffsetTop:es,keyboardOpen:et}=yn({enabled:I&&(!!i||de)}),ts=dt>0||es>0,ss=et&&ts?{"--keyboard-overlap":`${dt}px`,"--vv-offset-top":`${es}px`,...Zt!==null?{"--vv-height":`${Zt}px`}:{}}:{},ns=`chat-thread${et&&ts?" chat-thread--keyboard-active":""}`,pe=n.useMemo(()=>{const e=Je.trim().toLowerCase();return(e?ne.filter(d=>d.name.toLowerCase().includes(e)):ne).slice(0,10)},[ne,Je]),Ge=n.useMemo(()=>Array.from(me.values()),[me]),Ce=n.useMemo(()=>!z||h!=="rooms"||!o.activeRoom?null:{roomId:o.activeRoom.id,roomName:o.activeRoom.name,memberIds:new Set(o.activeRoomMembers.map(e=>e.agentId))},[z,h,o.activeRoom,o.activeRoomMembers]),_e=n.useMemo(()=>{const e=Ge.filter(j=>wn(j.name,xe));if(!Ce)return e;const a=e.filter(j=>Ce.memberIds.has(j.id));if(xe.trim().length===0)return a;const d=e.filter(j=>!Ce.memberIds.has(j.id));return[...a,...d]},[Ge,xe,Ce]),kt=n.useMemo(()=>{const e=new Map;for(const a of Ge)e.set(a.name.toLowerCase(),a);return e},[Ge]);n.useEffect(()=>{Re(0)},[pe]),n.useEffect(()=>{w(0)},[xe,fe]),n.useEffect(()=>()=>{Se.current!==null&&window.clearTimeout(Se.current)},[]);const as=n.useCallback(()=>{const e=ge.current;if(!e)return;const d=e.scrollTop+e.clientHeight>=e.scrollHeight-50;q(!d),Ae.current=!d},[]),he=n.useCallback(e=>{if(!e.isConnected)return;let a=0,d=0,j=-1;const X=6,be=()=>{if(e.isConnected){if(e.scrollTop=e.scrollHeight,e.scrollHeight===j?d+=1:(d=0,j=e.scrollHeight),a+=1,a>=X||d>=2){q(!1),Ae.current=!1;return}window.requestAnimationFrame(be)}};be()},[]),tt=n.useCallback(()=>{const e=ge.current;e&&he(e)},[he]);n.useLayoutEffect(()=>{Ee.current!==null&&(window.clearTimeout(Ee.current),Ee.current=null);const e=de?o.activeRoom?.id??null:i?.id??null;if(!e){Ct.current=null;return}const a={threadId:e,loaded:de?!o.messagesLoading:!R,hasMessages:de?o.messages.length>0:x.length>0},d=Ct.current,j=d?.threadId!==e,X=d?.threadId===e&&!d.loaded&&a.loaded,be=d?.threadId===e&&!d.hasMessages&&a.hasMessages;if(!(d===null||j||X||be))return;const Ne=ge.current;if(Ne)return he(Ne),de||(Ee.current=window.setTimeout(()=>{if(Ee.current=null,Ae.current)return;const We=ge.current;We&&he(We)},250)),Ct.current=a,()=>{Ee.current!==null&&(window.clearTimeout(Ee.current),Ee.current=null)}},[de,o.activeRoom?.id,o.messages.length,o.messagesLoading,i?.id,x.length,R,he]);const Os=de?o.messages:x;n.useEffect(()=>{Ae.current||tt()},[Os,D,C,E,tt]),n.useEffect(()=>{dt<=0||!ge.current||tt()},[dt,tt]),Sn(I&&et),n.useEffect(()=>{const e=()=>k(null);if(y)return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[y]),n.useEffect(()=>{if(!I||!et)return;const e=a=>{a.target?.closest(".chat-messages")||a.preventDefault()};return document.addEventListener("touchmove",e,{passive:!1}),()=>{document.removeEventListener("touchmove",e)}},[I,et]),n.useEffect(()=>{if(!I||!i)return;const e=()=>{const a=ce.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)}},[I,i]),n.useEffect(()=>{const e=Jt.current;if(Jt.current=h,h!=="direct"||e!==null&&e!=="rooms")return;const a=ge.current;a&&(he(a),Ae.current=!1,q(!1))},[h,he]),n.useEffect(()=>{if(!i&&!de||de&&!I)return;const e=()=>{const d=ge.current;d&&(he(d),Ae.current=!1,q(!1),Te.current!==null&&(window.clearTimeout(Te.current),Te.current=null),Te.current=window.setTimeout(()=>{if(Te.current=null,Ae.current)return;const j=ge.current;j&&he(j)},250))},a=()=>{document.visibilityState==="visible"&&e()};return document.addEventListener("visibilitychange",a),window.addEventListener("pageshow",e),()=>{document.removeEventListener("visibilitychange",a),window.removeEventListener("pageshow",e),Te.current!==null&&(window.clearTimeout(Te.current),Te.current=null)}},[I,i,de,he]),n.useEffect(()=>{if(de||typeof ResizeObserver>"u")return;const e=ge.current;if(!e)return;const a=new ResizeObserver(()=>{Ae.current||he(e)});return a.observe(e),()=>{a.disconnect()}},[de,he,i?.id,h]),n.useEffect(()=>{let e=!1;const a=s;return yt(void 0,s).then(d=>{if(e||a!==s)return;const j=new Map;for(const X of d)j.set(X.id,X);wt(j)}).catch(()=>{}),()=>{e=!0}},[s]),n.useEffect(()=>{let e=!1;return ct(!0),Cn(s).then(a=>{e||oe(a)}).catch(()=>{e||oe([])}).finally(()=>{e||ct(!1)}),()=>{e=!0}},[s]),n.useEffect(()=>{Qt.current=U},[U]),n.useEffect(()=>()=>{for(const e of Qt.current)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);for(const e of Ze.current.values())window.clearTimeout(e);Ze.current.clear()},[]);const ut=n.useCallback(e=>{if(!e||e.length===0)return;const a=[];for(const d of Array.from(e)){if(!ea.includes(d.type))continue;const j=d.type.startsWith("image/");a.push({file:d,previewUrl:j?URL.createObjectURL(d):""})}a.length>0&&K(d=>[...d,...a])},[]),Hs=n.useCallback(e=>{K(a=>{const d=a[e];return d?.previewUrl&&URL.revokeObjectURL(d.previewUrl),a.filter((j,X)=>X!==e)})},[]),Bs=n.useCallback(e=>{const a=e.clipboardData?.files;if(!a||a.length===0)return;const d=Array.from(a).filter(j=>j.type.startsWith("image/"));d.length!==0&&ut(d)},[ut]),Gs=n.useCallback(async e=>{try{await L(e),Y(!1),I&&ve(!1)}catch{r("Failed to create chat session","error")}},[L,r,I]),De=n.useCallback(e=>{const a=e??ce.current;a&&(a.style.height="auto",a.style.height=`${Vn(a.scrollHeight)}px`)},[]);n.useLayoutEffect(()=>{De()},[c,De]);const st=n.useCallback(()=>{if(m(""),le)try{localStorage.removeItem(le)}catch{}Me(!1),He(""),f(!1),ye(""),se(-1),K(e=>{for(const a of e)a.previewUrl&&URL.revokeObjectURL(a.previewUrl);return[]})},[le]),jt=n.useCallback(()=>{const e=c.trim(),a=U.map(d=>d.file);if(!(!e&&a.length===0||!i)){if(e==="/clear"||e==="/new"){st(),_(),M(),L({agentId:i.agentId,modelProvider:i.modelProvider??void 0,modelId:i.modelId??void 0}).catch(()=>{r("Failed to clear conversation","error")});return}st(),N(e,a)}},[c,U,i,st,_,M,L,r,N]),Mt=n.useCallback(async()=>{const e=c.trim();if(e){if(z&&h==="rooms"){if(!o.activeRoom)return;const a=c;st();try{await o.sendRoomMessage(e)}catch(d){m(a);const j=d instanceof Error&&d.message.trim()?d.message:"Failed to send room message";r(j,"error")}return}jt()}},[c,z,h,o,st,r,jt]),Rt=n.useCallback(e=>{m(a=>{const d=Ts(a);if(!d)return a;const j=`/skill:${e.name} `,X=a.slice(0,d.start)+j+a.slice(d.end);return window.requestAnimationFrame(()=>{ce.current&&(De(ce.current),ce.current.focus())}),X}),Me(!1),He(""),Re(0)},[De]),mt=n.useCallback(e=>{const a=ce.current;if(!a||P<0)return;const d=a.selectionStart??Qe.current,j=a.selectionEnd??d,X=Math.max(d,j),be=Math.min(P,X),Ne=`${`@${e.name.replace(/\s+/g,"_")}`} `,We=c.slice(0,be)+Ne+c.slice(X),Ve=be+Ne.length;m(We),f(!1),ye(""),w(0),se(-1),window.requestAnimationFrame(()=>{ce.current&&(De(ce.current),ce.current.focus(),ce.current.setSelectionRange(Ve,Ve))})},[P,c,De]),rs=n.useCallback(e=>{if(Qe.current=e.currentTarget.selectionStart??Qe.current,B.mentionActive&&B.files.length>0){if(B.handleKeyDown(e,c),e.key==="Enter"||e.key==="Tab"){const a=B.files[B.selectedIndex];if(a){const d=B.selectFile(a,c);m(d),B.dismissMention(),Ye(!1)}}return}if(fe&&e.key==="ArrowDown"){e.preventDefault(),_e.length>0&&w(a=>(a+1)%_e.length);return}if(fe&&e.key==="ArrowUp"){e.preventDefault(),_e.length>0&&w(a=>a===0?_e.length-1:a-1);return}if(fe&&e.key==="Enter"){e.preventDefault();const a=_e[v]??_e[0];a&&mt(a);return}if(fe&&e.key==="Escape"){e.preventDefault(),f(!1),ye(""),se(-1);return}if(je&&e.key==="ArrowDown"){e.preventDefault(),pe.length>0&&Re(a=>(a+1)%pe.length);return}if(je&&e.key==="ArrowUp"){e.preventDefault(),pe.length>0&&Re(a=>a===0?pe.length-1:a-1);return}if(je&&(e.key==="Enter"||e.key==="Tab")&&pe.length>0){e.preventDefault();const a=pe[ze]??pe[0];a&&Rt(a);return}if(je&&e.key==="Escape"){e.preventDefault(),Me(!1);return}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Mt())},[fe,_e,v,mt,je,pe,ze,Rt,Mt,B,c]),ht=n.useCallback((e,a)=>{const d=ta(e,a);if(d){f(!0),ye(d.filter),se(d.start);return}f(!1),ye(""),se(-1)},[]),is=n.useCallback(e=>{const a=e.target,d=a.value,j=a.selectionStart??d.length;Qe.current=j,m(d);const X=Ts(d);X?(Me(!0),He(X.filter)):(Me(!1),He("")),ht(d,j),B.detectMention(d,j),Ye(B.mentionActive),B.mentionActive&&St(a),De(a)},[ht,De]),ft=n.useCallback(e=>{const a=e.currentTarget,d=a.selectionStart??a.value.length;Qe.current=d,ht(a.value,d),B.detectMention(a.value,d),Ye(B.mentionActive),B.mentionActive&&St(a)},[ht,B,St]),os=n.useCallback(e=>{e.key!=="Escape"&&ft(e)},[ft]),cs=n.useCallback(()=>{Se.current!==null&&window.clearTimeout(Se.current),Se.current=window.setTimeout(()=>{Me(!1),f(!1),ye(""),se(-1),Ye(!1),B.dismissMention(),Se.current=null},120)},[B]),ls=n.useCallback(()=>{Se.current!==null&&(window.clearTimeout(Se.current),Se.current=null),typeof window<"u"&&window.innerWidth<=768&&window.setTimeout(()=>{(window.scrollY!==0||window.scrollX!==0)&&window.scrollTo(0,0)},0)},[]),Ks=n.useCallback(async e=>{k(null);try{await g(e),r("Conversation archived","success")}catch{r("Failed to archive conversation","error")}},[g,r]),Ws=n.useCallback(async e=>{F(null),k(null);try{await ee(e),r("Conversation deleted","success")}catch{r("Failed to delete conversation","error")}},[ee,r]),nt=n.useCallback(e=>{try{localStorage.setItem(Ms,String(e))}catch{}},[]),Vs=n.useCallback(e=>{if(I)return;e.preventDefault(),e.stopPropagation();const a=e.currentTarget;typeof a.setPointerCapture=="function"&&a.setPointerCapture(e.pointerId);const d=e.clientX,j=ie;let X=j;document.body.style.userSelect="none";const be=Ne=>{const We=Ne.clientX-d,Ve=Math.max(pt,Math.min(bt,j+We));X=Ve,Ue(Ve),nt(Ve)},Ke=Ne=>{typeof a.releasePointerCapture=="function"&&a.releasePointerCapture(Ne.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",be),document.removeEventListener("pointerup",Ke),nt(X)};document.addEventListener("pointermove",be),document.addEventListener("pointerup",Ke)},[I,nt,ie]),qs=n.useCallback(e=>{if(I||e.key!=="ArrowLeft"&&e.key!=="ArrowRight")return;e.preventDefault();const a=e.shiftKey?50:10,d=e.key==="ArrowLeft"?-a:a,j=Math.max(pt,Math.min(bt,ie+d));Ue(j),nt(j)},[I,nt,ie]),ds=n.useCallback(e=>{S(e),Be(!1),I&&ve(!1)},[S,I]),At=n.useCallback(()=>{S(""),ve(!0),Be(!1)},[S]),Tt=n.useCallback(()=>{o.selectRoom(null),ve(!0),Be(!1)},[o]),Xs=()=>t.jsxs("div",{className:"chat-empty-state",children:[t.jsx(Pn,{size:48,strokeWidth:1.5}),t.jsx("h2",{children:"Start a new conversation"}),t.jsxs("button",{className:"btn btn-primary",onClick:()=>Y(!0),children:[t.jsx(at,{size:16}),"New Chat"]})]}),$e=js(i?.modelProvider,i?.modelId),Ie=i?.modelProvider??null,Et=!!(i||E||x.length>0),gt=h==="rooms"?de:!!i,us=n.useRef(gt);n.useEffect(()=>{const e=us.current;us.current=gt,I&&(e||!gt||Vt({type:"view",revert:h==="rooms"?Tt:At}))},[h,At,Tt,gt,I,Vt]);const Dt=i?.agentId===Xe?$e??"Fusion":i?.title||me.get(i?.agentId??"")?.name||i?.agentId||"Chat",ms=!!($e&&$e!==Dt),Js=I&&h==="direct"&&!!i,$t=me.get(i?.agentId??"")?.name||(i?.agentId===Xe?$e??"Fusion":i?.agentId?.slice(0,30)??"Fusion"),It=!1,Pt=i?.agentId===Xe,Ys=b.length>50?`${b.slice(0,50)}…`:b,Qs=n.useCallback(()=>{ae(e=>!e)},[]);n.useEffect(()=>{if(!lt)return;const e=a=>{Xt.current?.contains(a.target)||Be(!1)};return document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}},[lt]),n.useEffect(()=>{(!I||h!=="direct"||ue)&&Be(!1)},[I,h,ue]);const Lt=n.useCallback((e,a)=>{const d=Ze.current.get(e);d&&window.clearTimeout(d),we(X=>({...X,[e]:a}));const j=window.setTimeout(()=>{we(X=>{const{[e]:be,...Ke}=X;return Ke}),Ze.current.delete(e)},2e3);Ze.current.set(e,j)},[]),hs=n.useCallback(async(e,a)=>{try{if(!navigator.clipboard?.writeText)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(a),Lt(e,"success")}catch{Lt(e,"error")}},[Lt]),Zs=n.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(Is,{remarkPlugins:[Ps],components:zs,children:e})}),[]),Ft=i?.agentId===Xe,zt=n.useCallback((e,a,d)=>t.jsx("button",{type:"button",className:`btn-icon chat-message-copy-action${re[e]==="success"?" chat-message-copy-action--success":""}${re[e]==="error"?" chat-message-copy-action--error":""}`,"data-testid":d??`chat-copy-response-${e}`,"aria-label":re[e]==="success"?"Response copied":re[e]==="error"?"Copy failed":"Copy response",onClick:()=>{hs(e,a)},children:re[e]==="success"?t.jsx(Nn,{size:14}):t.jsx(kn,{size:14})}),[re,hs]);return t.jsxs("div",{className:"chat-view",children:[t.jsxs("div",{className:`chat-sidebar${ue?"":" chat-sidebar--hidden"}`,style:I?void 0:{width:`${ie}px`},children:[z&&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${h==="direct"?" chat-sidebar-scope-btn--active":""}`,"aria-selected":h==="direct","data-testid":"chat-sidebar-scope-direct",onClick:()=>p("direct"),children:"Direct"}),t.jsx("button",{type:"button",role:"tab",className:`chat-sidebar-scope-btn${h==="rooms"?" chat-sidebar-scope-btn--active":""}`,"aria-selected":h==="rooms","data-testid":"chat-sidebar-scope-rooms",onClick:()=>p("rooms"),children:"Rooms"})]}),!z||h==="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(jn,{size:14,className:"chat-sidebar-search-icon"}),t.jsx("input",{type:"text",className:"chat-sidebar-search",placeholder:"Search conversations...",value:A,onChange:e=>T(e.target.value),"data-testid":"chat-search-input"})]})}),t.jsx("div",{className:"chat-session-list chat-sidebar-list",children:u?t.jsx("div",{className:"chat-empty-state chat-empty-state--padded",children:"Loading..."}):$.length===0?t.jsx("div",{className:"chat-empty-state chat-empty-state--padded",children:"No conversations yet"}):$.map(e=>t.jsxs("div",{className:`chat-session-item${i?.id===e.id?" chat-session-item--active":""}`,onClick:()=>ds(e.id),onContextMenu:a=>{a.preventDefault(),k({sessionId:e.id,x:a.clientX,y:a.clientY})},"data-testid":`chat-session-${e.id}`,children:[t.jsx("button",{className:"chat-session-delete-btn",onClick:a=>{a.stopPropagation(),F(e.id)},"data-testid":"chat-session-delete-btn","aria-label":"Delete conversation",children:t.jsx(Ut,{size:14})}),t.jsx("div",{className:"chat-session-title",children:e.title||"Untitled"}),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:[e.modelProvider&&t.jsx(it,{provider:e.modelProvider,size:"sm"}),t.jsx("span",{children:me.get(e.agentId)?.name||(e.agentId===Xe?js(e.modelProvider,e.modelId)??"Fusion":e.agentId.slice(0,30))})]}),t.jsx("span",{children:e.updatedAt?Ls(e.updatedAt):""})]})]},e.id))})]}):t.jsxs("div",{className:"chat-sidebar-rooms","data-testid":"chat-sidebar-rooms",children:[!I&&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:()=>te(!0),children:[t.jsx(at,{size:14}),"Create room"]})}),o.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:o.rooms.map(e=>{const a=o.activeRoom?.id===e.id;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:()=>{o.selectRoom(e.id),I&&ve(!1)},onKeyDown:d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),o.selectRoom(e.id),I&&ve(!1))},children:[t.jsxs("span",{className:"chat-room-item-details",children:[t.jsxs("span",{className:"chat-room-item-name",children:["#",e.name]}),a?t.jsxs("span",{className:"chat-room-item-meta",children:[o.activeRoomMembers.length," ",o.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:d=>{d.stopPropagation(),ke(e.id)},children:t.jsx(Ut,{size:14})})]},e.id)})})]}),h==="rooms"?I?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:()=>te(!0),children:[t.jsx(at,{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:()=>Y(!0),"data-testid":"chat-new-btn",children:[t.jsx(at,{size:14}),"New Chat"]})})]}),!I&&ue&&t.jsx("div",{className:"chat-sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":pt,"aria-valuemax":bt,"aria-valuenow":ie,"aria-label":"Resize chat sidebar",tabIndex:0,onPointerDown:Vs,onKeyDown:qs}),y&&t.jsxs("div",{className:"chat-session-context-menu",style:{top:y.y,left:y.x},onClick:e=>e.stopPropagation(),children:[t.jsxs("button",{onClick:()=>Ks(y.sessionId),"data-testid":"chat-context-archive",children:[t.jsx(Mn,{size:14}),"Archive"]}),t.jsxs("button",{onClick:()=>{k(null),F(y.sessionId)},"data-testid":"chat-context-delete",children:[t.jsx(Ut,{size:14}),"Delete"]})]}),Z&&t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:()=>F(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:()=>F(null),children:"Cancel"}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>void Ws(Z),children:"Delete"})]})]})}),z&&G&&t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:()=>ke(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:()=>ke(null),children:"Cancel"}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>{(async()=>{try{await o.deleteRoom(G),ke(null)}catch{r("Failed to delete room","error")}})()},children:"Delete"})]})]})}),z&&h==="rooms"?t.jsxs("div",{className:ns,style:ss,children:[o.activeRoom?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"chat-room-thread-header",children:[I&&t.jsx("button",{className:"btn-icon",onClick:Tt,"data-testid":"chat-back-btn",children:t.jsx(bs,{size:16})}),t.jsxs("div",{className:"chat-thread-header-title",children:["#",o.activeRoom.name]}),t.jsx("div",{className:"chat-room-thread-members",children:o.activeRoomMembers.map(e=>t.jsx($s,{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:as,children:[o.messagesLoading?t.jsx("div",{className:"chat-empty-state",children:"Loading messages..."}):o.messages.length===0?t.jsx("div",{className:"chat-empty-state",children:"No messages yet. Start the conversation!"}):o.messages.map(e=>{const a=e.senderAgentId?me.get(e.senderAgentId)?.name??e.senderAgentId.slice(0,30):"You",d={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(Gt,{message:d,forcePlain:H,agentName:a,hideAssistantIdentity:!1,showAssistantModelTag:!1,activeModelTag:null,activeModelProvider:null,activeSessionId:o.activeRoom?.id??null,mentionAgentsByName:kt,roomContext:Ce},e.id)}),t.jsx("div",{ref:qt})]})]}):t.jsx("div",{className:"chat-room-empty-pane","data-testid":"chat-rooms-empty-pane",children:"Select a room or create one"}),o.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:ce,className:"chat-input-textarea",placeholder:"Type a message...",value:c,onChange:is,onKeyDown:rs,onKeyUp:os,onClick:ft,onBlur:cs,onFocus:ls,onTouchStart:e=>{typeof window>"u"||window.innerWidth>768||document.activeElement!==e.currentTarget&&(e.preventDefault(),e.currentTarget.focus({preventScroll:!0}))},rows:1,"data-testid":"chat-input"}),t.jsx(vs,{agents:Ge,filter:xe,highlightedIndex:v,visible:fe,onSelect:mt,position:"below",roomMemberIds:Ce?.memberIds,roomName:Ce?.roomName})]}),t.jsx("button",{type:"button",className:"chat-input-send",onPointerDown:e=>{e.pointerType&&e.pointerType!=="mouse"&&e.preventDefault()},onMouseDown:e=>{e.preventDefault()},onClick:()=>{Mt()},disabled:!c.trim(),"data-testid":"chat-send-btn",style:{touchAction:"manipulation"},children:t.jsx(xs,{size:16})})]})})]}):t.jsxs("div",{className:ns,style:ss,children:[(Et||!I)&&t.jsxs("div",{className:"chat-thread-header",children:[I&&Et&&t.jsx("button",{className:"btn-icon",onClick:At,"data-testid":"chat-back-btn",children:t.jsx(bs,{size:16})}),t.jsx("div",{className:"chat-thread-header-identity","data-testid":"chat-thread-header-identity",children:Js?t.jsxs("div",{className:"chat-mobile-session-menu",ref:Xt,children:[t.jsxs("button",{type:"button",className:"btn chat-mobile-session-trigger","data-testid":"chat-mobile-session-trigger","aria-haspopup":"menu","aria-expanded":lt,onClick:()=>Be(e=>!e),children:[Ie?t.jsx(it,{provider:Ie,size:"md"}):t.jsx(ot,{size:16}),t.jsx("span",{className:"chat-thread-header-title",children:Dt}),ms&&t.jsx("span",{className:"chat-model-tag",children:$e}),t.jsx(ys,{size:16,"aria-hidden":"true"})]}),lt&&t.jsx("div",{className:"chat-mobile-session-dropdown",role:"menu","data-testid":"chat-mobile-session-dropdown",children:$.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:()=>ds(e.id),children:t.jsx("span",{className:"chat-mobile-session-option-title",children:e.title||"Untitled"})},e.id))})]}):t.jsxs(t.Fragment,{children:[Ie?t.jsx(it,{provider:Ie,size:"md"}):t.jsx(ot,{size:16}),t.jsx("span",{className:"chat-thread-header-title",children:Dt}),ms&&t.jsx("span",{className:"chat-model-tag",children:$e})]})}),Et&&t.jsx("button",{type:"button",className:`chat-thread-header-render-toggle${H?" chat-thread-header-render-toggle--plain":""}`,"data-testid":"chat-thread-render-toggle","aria-label":H?"Show all messages as rendered Markdown":"Show all messages as plain text",onClick:Qs,children:H?t.jsx(Rn,{size:14}):t.jsx(An,{size:14})}),!I&&t.jsxs("button",{className:"btn btn-sm btn-primary chat-thread-header-new-chat",onClick:()=>Y(!0),"data-testid":"chat-thread-new-chat-btn",children:[t.jsx(at,{size:14}),"New Chat"]})]}),t.jsxs("div",{className:"chat-messages",ref:ge,onScroll:as,children:[E?t.jsxs(t.Fragment,{children:[x.map(e=>t.jsx(Gt,{message:e,forcePlain:H,agentName:$t,hideAssistantIdentity:Pt,showAssistantModelTag:It,activeModelTag:$e,activeModelProvider:Ie,activeSessionId:i?.id??null,mentionAgentsByName:kt,roomContext:null,copyAction:Ft&&e.role==="assistant"?zt(e.id,e.content):void 0},e.id)),t.jsxs("div",{className:"chat-message chat-message--assistant chat-message--streaming",children:[!Pt&&t.jsxs("div",{className:"chat-message-avatar",children:[Ie?t.jsx(it,{provider:Ie,size:"sm"}):t.jsx(ot,{size:14}),t.jsx("span",{children:$t}),It]}),D?Zs(D,H):t.jsx("div",{className:"chat-message-content chat-message-content--waiting",children:C?"Thinking…":"Connecting…"}),Ft&&D&&zt("__streaming__",D,"chat-copy-response-streaming"),Fs(Q),C&&t.jsxs("details",{className:"chat-message-thinking",children:[t.jsx("summary",{children:"Thinking"}),t.jsx("pre",{className:"chat-message-thinking-content",children:xt(C)})]}),t.jsxs("div",{className:"chat-typing-indicator",children:[t.jsx("span",{}),t.jsx("span",{}),t.jsx("span",{})]})]})]}):R?t.jsx("div",{className:"chat-empty-state",children:"Loading messages..."}):x.length===0&&!i?Xs():x.length===0&&i?t.jsx("div",{className:"chat-empty-state",children:"No messages yet. Start the conversation!"}):t.jsx(t.Fragment,{children:x.map(e=>t.jsx(Gt,{message:e,forcePlain:H,agentName:$t,hideAssistantIdentity:Pt,showAssistantModelTag:It,activeModelTag:$e,activeModelProvider:Ie,activeSessionId:i?.id??null,mentionAgentsByName:kt,roomContext:null,copyAction:Ft&&e.role==="assistant"?zt(e.id,e.content):void 0},e.id))}),t.jsx("div",{ref:qt})]}),O&&t.jsxs("button",{type:"button",className:"btn btn-sm chat-jump-to-latest","data-testid":"chat-jump-to-latest",onClick:tt,children:[t.jsx(ys,{size:14}),"Latest"]}),i&&t.jsxs("div",{className:"chat-input-area",children:[t.jsx("input",{ref:Yt,type:"file",accept:"image/*,.txt,.json,.yaml,.yml,.log,.csv,.xml,.md",multiple:!0,style:{display:"none"},onChange:e=>{ut(e.target.files),e.target.value=""}}),je&&t.jsx("div",{className:"chat-skill-menu","data-testid":"chat-skill-menu",role:"listbox","aria-label":"Skill suggestions",children:Oe?t.jsx("div",{className:"chat-skill-menu-empty",children:"Loading skills…"}):pe.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:Je?"No skills found":"No skills available"}):pe.map((e,a)=>t.jsxs("button",{type:"button",role:"option","aria-selected":a===ze,className:`chat-skill-menu-item${a===ze?" chat-skill-menu-item--highlighted":""}`,onMouseDown:d=>d.preventDefault(),onMouseEnter:()=>Re(a),onClick:()=>Rt(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))}),U.length>0&&t.jsx("div",{className:"chat-attachment-previews","data-testid":"chat-attachment-previews",children:U.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:()=>Hs(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:()=>Yt.current?.click(),children:t.jsx(Tn,{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),ut(e.dataTransfer.files)},children:[t.jsx("textarea",{ref:ce,className:"chat-input-textarea",placeholder:"Type a message...",value:c,onChange:is,onKeyDown:rs,onKeyUp:os,onClick:ft,onBlur:cs,onFocus:ls,onPaste:Bs,onTouchStart:e=>{typeof window>"u"||window.innerWidth>768||document.activeElement!==e.currentTarget&&(e.preventDefault(),e.currentTarget.focus({preventScroll:!0}))},rows:1,"data-testid":"chat-input"}),t.jsx(vs,{agents:Ge,filter:xe,highlightedIndex:v,visible:fe,onSelect:mt,position:"below",roomMemberIds:Ce?.memberIds,roomName:Ce?.roomName}),t.jsx(En,{visible:B.mentionActive&&!fe,position:_s,files:B.files,selectedIndex:B.selectedIndex,onSelect:e=>{const a=B.selectFile(e,c);m(a),B.dismissMention(),Ye(!1),ce.current?.focus()},loading:B.loading}),b&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${Ys}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:M,children:"×"})]})]}),E?t.jsx("button",{className:"chat-input-stop",onClick:_,"aria-label":"Stop generation","data-testid":"chat-stop-btn",children:t.jsx(Dn,{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:()=>{jt()},disabled:!c.trim()&&U.length===0,"data-testid":"chat-send-btn",style:{touchAction:"manipulation"},children:t.jsx(xs,{size:16})})]})]})]}),z&&t.jsx(Kn,{isOpen:Fe,onClose:()=>te(!1),projectId:s,existingRoomNames:o.rooms.map(e=>e.name),onCreate:async e=>{await o.createRoom({name:e.name,memberAgentIds:e.memberAgentIds}),h!=="rooms"&&p("rooms"),te(!1),I&&ve(!1)}}),J&&t.jsx(sa,{projectId:s,onClose:()=>Y(!1),onCreate:Gs})]})}export{ca as ChatView,Vn as clampChatInputHeight};
@@ -0,0 +1 @@
1
+ import{r,j as t}from"./vendor-react-K0fH_qHe.js";import{bW as De,bX as de,bY as Ze,bZ as ue,s as Ue,b_ as be,b$ as we,c0 as xe,c1 as ye,c2 as et,c3 as ae,c4 as tt,c5 as rt,c6 as st,c7 as nt,c8 as at,c9 as ie,L as ee,S as it,M as lt,ca as ct,bA as ot,a as dt,cb as Me,T as Ae,cc as ut,V as vt,aT as mt,aU as ft,aa as pt,au as ht,R as gt}from"./index-DzSLVOnp.js";import"./vendor-xterm-DzcZoU0P.js";import"./vendor-codemirror-jBKmHyH0.js";const ve=500,bt=3e3;function B(e){return e instanceof Error?e.message:String(e)}function Te(e){return e.length<=ve?e:e.slice(-ve)}function le(e,i){return Te([...e,i])}function G(e){try{return JSON.parse(e)}catch{return null}}function Q(e){const i=e.text??"";return e.stream==="stderr"?`[stderr] ${i}`:i}function wt(e){return e?.previewUrl??null}async function Se(e){return tt(e)}async function Ne(e,i){return rt(e,i)}async function xt(e){return st(e)}async function yt(e){return nt(e)}async function je(e){return at(e)}function V(e){try{return e()}catch{return null}}function ce(){return typeof V(()=>de)=="function"&&typeof V(()=>De)=="function"}function X(e){return{config:{id:e.id??"default",name:e.name??"Dev Server",command:e.command??"",cwd:e.cwd??"."},status:e.status,runtime:e.pid?{pid:e.pid,startedAt:e.startedAt??new Date().toISOString(),exitCode:e.exitCode??void 0,previewUrl:e.previewUrl}:void 0,previewUrl:e.previewUrl??e.detectedUrl??e.manualUrl??void 0,logHistory:(e.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}function St(e){const[i,o]=r.useState(null),[g,y]=r.useState([]),[w,f]=r.useState([]),[k,U]=r.useState([]),[C,T]=r.useState(!0),[S,u]=r.useState(null),n=r.useRef(0),[d,M]=r.useState(null),R=r.useCallback(a=>{if(o(a),a?.logHistory){const s=a.logHistory.slice(-ve).map(Q);f(s)}},[]),A=r.useCallback(async()=>{const a=n.current;try{if(ce())if(d){const s=await De(d,e);if(n.current!==a)return;R(s)}else{const s=await de(e);if(n.current!==a)return;y(s),s.length>0&&(M(s[0].config.id),R(s[0]))}else{const s=await Se(e);if(n.current!==a)return;const c=X(s);y([c]),R(c)}u(null)}catch(s){if(n.current!==a)return;u(B(s))}},[R,e,d]);r.useEffect(()=>{n.current+=1;const a=n.current;o(null),y([]),f([]),U([]),T(!0),u(null),M(null),(async()=>{try{const[c,l]=await Promise.allSettled([ce()?de(e):Se(e).then(N=>[X(N)]),typeof V(()=>ae)=="function"?ae(e):je(e).then(N=>N.map(b=>({name:b.name,command:b.command,cwd:b.cwd,scriptName:b.scriptName,packagePath:b.packagePath})))]);if(n.current!==a)return;let v=null;if(c.status==="fulfilled"){const N=c.value;if(y(N),N.length>0){const b=N[0];ce()&&M(b.config.id),R(b)}}else v=B(c.reason);l.status==="fulfilled"&&U(l.value),v&&u(v)}catch(c){if(n.current!==a)return;u(B(c))}finally{n.current===a&&T(!1)}})()},[R,e]),r.useEffect(()=>{const a=d?Ze(d,e):typeof V(()=>ue)=="function"?ue(e):null;if(!a)return;const s=n.current,c=Ue(a,{events:{history:l=>{if(n.current!==s)return;const v=G(l.data);if(v?.lines){const N=v.lines.map(Q);f(Te(N))}},log:l=>{if(n.current!==s)return;const v=G(l.data);if(v){const N=typeof v.line=="string"?v.line:Q(v);f(b=>le(b,N))}},"dev-server:log":l=>{if(n.current!==s)return;const v=G(l.data);if(v){const N=typeof v.line=="string"?v.line:Q(v);f(b=>le(b,N))}},"dev-server:output":l=>{if(n.current!==s)return;const v=G(l.data);v?.line&&f(N=>le(N,v.line))},status:l=>{if(n.current!==s)return;const v=G(l.data),N=v?.status;N&&o(b=>b&&{...b,status:N,runtime:v.pid?{...b.runtime??{startedAt:new Date().toISOString()},pid:v.pid}:b.runtime})},"dev-server:status":l=>{if(n.current!==s)return;const v=G(l.data);if(v?.status){const N=X(v);o(N),y([N])}},stopped:()=>{n.current},failed:()=>{n.current}},onReconnect:()=>{n.current===s&&A()},onError:()=>{n.current===s&&u(l=>l??"Lost log stream connection.")}});return()=>{c()}},[e,A,d]),r.useEffect(()=>{if(i?.status!=="running"&&i?.status!=="starting")return;const a=setInterval(()=>{A()},bt);return()=>{clearInterval(a)}},[A,i?.status]);const _=r.useCallback(async(a,s)=>{n.current+=1;const c=n.current;try{let l;if(d&&typeof V(()=>be)=="function")l=await be(d,e);else{const v=await Ne({command:a,cwd:s},e);l=X(v)}if(n.current!==c)return;o(l),u(null)}catch(l){if(n.current!==c)return;throw u(B(l)),l}},[e,d]),D=r.useCallback(async()=>{n.current+=1;const a=n.current;try{let s;if(d&&typeof V(()=>we)=="function")s=await we(d,e);else{const c=await xt(e);s=X(c)}if(n.current!==a)return;o(s),u(null)}catch(s){if(n.current!==a)return;throw u(B(s)),s}},[e,d]),j=r.useCallback(async()=>{n.current+=1;const a=n.current;try{let s;if(d&&typeof V(()=>xe)=="function")s=await xe(d,e);else{const c=await yt(e);s=X(c)}if(n.current!==a)return;o(s),u(null)}catch(s){if(n.current!==a)return;throw u(B(s)),s}},[e,d]),P=r.useCallback(async a=>{n.current+=1;const s=n.current;try{let c;if(d&&typeof V(()=>ye)=="function")c=await ye(d,a,e);else{const l=await et({url:a},e);c={url:l.manualUrl??l.previewUrl??l.detectedUrl??null,source:l.manualUrl?"manual":"auto"}}if(n.current!==s)return;o(l=>l?{...l,previewUrl:c.url??void 0}:null),u(null)}catch(c){if(n.current!==s)return;throw u(B(c)),c}},[e,d]),h=r.useCallback(async()=>{n.current+=1;const a=n.current;try{let s;try{s=await ae(e)}catch{s=(await je(e)).map(l=>({name:l.name,command:l.command,cwd:l.cwd,scriptName:l.scriptName,packagePath:l.packagePath}))}if(n.current!==a)return;U(s),u(null)}catch(s){if(n.current!==a)return;throw u(B(s)),s}},[e]),p=r.useCallback(async(a,s)=>{if(typeof a!="string"&&!d)try{const v=a,N=await Ne({command:v.command,cwd:v.cwd,scriptName:v.scriptName,packagePath:v.packagePath??v.cwd},e),b=X(N);o(b),y([b]),u(null);return}catch(v){throw u(B(v)),v}const c=typeof a=="string"?a:a.command,l=typeof a=="string"?s:a.cwd;await _(c,l)},[e,_,d]),E=r.useCallback(async()=>{await D()},[D]),L=r.useCallback(async()=>{await j()},[j]),z=r.useCallback(async a=>{await P(a)},[P]),F=r.useCallback(async()=>{await h()},[h]),O=r.useCallback(async()=>{await A()},[A]),H=wt(i),x=i?{...i,pid:i.runtime?.pid}:null;return{session:i,sessions:g,logs:w,detectedCommands:k,previewUrl:H,isLoading:C,error:S,startServer:_,stopServer:D,restartServer:j,setPreviewUrl:P,detectCommands:h,refresh:A,candidates:k,serverState:x,loading:C,start:p,stop:E,restart:L,setManualUrl:z,detect:F,refreshStatus:O}}const ke=500,Ce=100;function Pe(e){return e.length>ke?e.slice(-ke):e}function ze(e){return e==="stderr"?"stderr":"stdout"}function K(e){try{return JSON.parse(e.data)}catch{return null}}function Z(e,i){return{id:typeof e.id=="number"&&Number.isFinite(e.id)?e.id:i,text:typeof e.text=="string"?e.text:"",stream:ze(e.stream),timestamp:typeof e.timestamp=="string"?e.timestamp:""}}function Nt(e,i){return{id:i,text:e,stream:"stdout",timestamp:""}}function oe(e,i){if(i.length===0)return e;const o=[...e],g=new Set(e.map(y=>y.id));for(const y of i)g.has(y.id)||(g.add(y.id),o.push(y));return o.sort((y,w)=>y.id-w.id),Pe(o)}function jt(e,i){const[o,g]=r.useState([]),[y,w]=r.useState(!1),[f,k]=r.useState(!1),[U,C]=r.useState(!1),[T,S]=r.useState(null),u=r.useRef(null),n=r.useRef(!1),d=r.useRef(0),M=r.useRef(0),R=r.useRef(e),A=r.useRef(i),_=r.useRef(0),D=r.useRef(1);(R.current!==e||A.current!==i)&&(R.current=e,A.current=i,d.current++,n.current=!0,_.current=0,D.current=1,g([]),w(!1),k(!1),C(!1),S(null),u.current&&(u.current(),u.current=null)),r.useEffect(()=>{if(!i){u.current&&(u.current(),u.current=null);return}const E=d.current,L=++M.current;n.current=!1,w(!0);const z=(x,a)=>{const s=Pe(x);g(s),S(a),C(a!==null?a>s.length:!1);const c=s.length>0?s[s.length-1].id:0;_.current=c,D.current=c+1},F=x=>{if(n.current||d.current!==E||!x||typeof x!="object")return;const a=x.lines;if(!Array.isArray(a))return;if(a.length>0&&typeof a[0]=="string"){const c=a.filter(l=>typeof l=="string").map((l,v)=>Nt(l,v+1));z(c,c.length);return}const s=a.filter(c=>!!c&&typeof c=="object").map((c,l)=>Z(c,l+1));z(s,s.length)},O=x=>{if(n.current||d.current!==E)return;const a=typeof x.text=="string"?x.text:typeof x.line=="string"?x.line:null;if(!a)return;const s=D.current,c=typeof x.id=="number"&&Number.isFinite(x.id)?x.id:s,l={id:c,text:a,stream:ze(x.stream),timestamp:typeof x.timestamp=="string"?x.timestamp:""};_.current=Math.max(_.current,c),D.current=Math.max(D.current,c+1),g(v=>oe(v,[l])),S(v=>v===null?v:Math.max(v+1,l.id))};async function H(){try{const a=await ie({maxLines:Ce},e);if(n.current||d.current!==E||M.current!==L)return;const s=a.lines.map((c,l)=>Z(c,l+1));z(s,a.totalLines)}catch{if(n.current||d.current!==E||M.current!==L)return;z([],null)}finally{!n.current&&d.current===E&&M.current===L&&w(!1)}const x=ue(e);u.current=Ue(x,{events:{"dev-server:log":a=>{const s=K(a);s&&O(s)},log:a=>{const s=K(a);s&&O(s)},history:a=>{const s=K(a);F(s)},"dev-server:history":a=>{const s=K(a);F(s)}},onReconnect:()=>{n.current||d.current!==E||ie({lastEventId:_.current,maxLines:50},e).then(a=>{if(n.current||d.current!==E)return;const s=a.lines.map((c,l)=>Z(c,D.current+l));if(s.length>0){const c=s[s.length-1].id;_.current=Math.max(_.current,c),D.current=Math.max(D.current,c+1)}g(c=>oe(c,s)),S(a.totalLines)}).catch(()=>{})}})}return H(),()=>{n.current=!0,u.current&&(u.current(),u.current=null)}},[i,e]);const P=r.useCallback(async()=>{if(!i||f)return;const E=d.current,L=o.length;k(!0);try{const z=await ie({maxLines:Ce,offset:L},e);if(n.current||d.current!==E)return;const F=z.lines.map((O,H)=>Z(O,H+1));g(O=>oe(F,O)),C(z.totalLines>L+F.length),S(z.totalLines)}catch{}finally{k(!1)}},[i,o.length,f,e]),h=r.useCallback(()=>{g([])},[]),p=u.current!==null&&!y&&!n.current;return{entries:o,loading:y,loadingMore:f,hasMore:U,total:T,loadMore:P,clear:h,logs:o,isStreaming:p,clearLogs:h}}const kt="This preview appears to block iframe embedding. Open it in a new tab instead.",Ct="The preview URL could not be loaded. Verify the server is running and the URL is correct.",Et="Preview is taking longer than expected and may block iframe embedding.";function Lt(e){return e==="blocked"?kt:e==="error"?Ct:null}function Rt(e,i={}){const{loadTimeoutMs:o=1e4,detectionMethod:g=null}=i,y=r.useRef(null),w=r.useRef(null),[f,k]=r.useState("unknown"),[U,C]=r.useState(null),[T]=r.useState(g),S=r.useCallback(()=>{w.current!==null&&(window.clearTimeout(w.current),w.current=null)},[]),u=r.useCallback(j=>{k(j),C(Lt(j))},[]),n=r.useCallback(()=>{k("blocked"),C(Et)},[]);r.useEffect(()=>{if(S(),!e){k("unknown"),C(null);return}k("unknown"),C(null);let j=!1;return queueMicrotask(()=>{j||(k("loading"),C(null))}),()=>{j=!0,S()}},[S,e]),r.useEffect(()=>{if(f!=="loading"){S();return}const j=setTimeout(()=>{w.current=null,n()},o);return w.current=j,()=>{clearTimeout(j),w.current===j&&(w.current=null)}},[S,f,o,n]);const d=r.useCallback(()=>{const j=y.current;if(!j){u("embedded");return}try{if(j.contentWindow?.location?.href==="about:blank"&&j.src!=="about:blank"){u("blocked");return}}catch{}u("embedded")},[u]),M=r.useCallback(()=>{u("error")},[u]);r.useEffect(()=>{if(S(),!e){k("unknown"),C(null);return}k("unknown"),C(null)},[S]);const R=r.useCallback(()=>{S(),k("unknown"),C(null)},[S]),A=R,_=r.useMemo(()=>f==="embedded",[f]),D=r.useMemo(()=>f==="blocked"||f==="error",[f]);return{embedStatus:f,isEmbedded:_,isBlocked:D,blockReason:U,detectionMethod:T,iframeRef:y,resetEmbedStatus:R,setEmbedStatus:u,retry:A,embedContext:U,handleIframeLoad:d,handleIframeError:M}}const _t=/\x1b\[[0-9;]*m/g;function me(e){return e.replace(_t,"")}function Dt(e){if(!e)return"";const i=new Date(e);return Number.isNaN(i.getTime())?"":i.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}function Ut(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Mt(e){if(e.stream==="stderr")return"error";const i=me(e.text).toLowerCase();return/\b(warn|warning)\b/.test(i)?"warn":/\b(error|fatal)\b/.test(i)?"error":"info"}function At(e,i){if(!i)return e;const o=new RegExp(`(${Ut(i)})`,"ig"),g=e.split(o),y=i.toLowerCase();return t.jsx(t.Fragment,{children:g.map((w,f)=>w.toLowerCase()===y?t.jsx("mark",{children:w},`${w}-${f}`):t.jsx("span",{children:w},`${w}-${f}`))})}function Tt({entries:e,loading:i,loadingMore:o,hasMore:g,total:y,onLoadMore:w,isRunning:f}){const k=r.useRef(null),U=r.useRef(e.length),C=r.useRef(f),[T,S]=r.useState(!1),[u,n]=r.useState(!1),[d,M]=r.useState(""),[R,A]=r.useState("all"),_=r.useMemo(()=>R==="all"?e:e.filter(p=>Mt(p)===R),[e,R]),D=r.useMemo(()=>{const p=d.trim().toLowerCase();return p?_.filter(E=>me(E.text).toLowerCase().includes(p)):_},[_,d]),j=D.length,P=r.useCallback(()=>{const p=k.current;p&&(p.scrollTop=p.scrollHeight,n(!1))},[]);r.useEffect(()=>{const p=C.current,E=U.current,L=e.length>E;f&&(!p||!u&&L)&&P(),C.current=f,U.current=e.length},[e.length,f,u,P]);const h=r.useCallback(()=>{const p=k.current;if(!p)return;const L=p.scrollTop+p.clientHeight>=p.scrollHeight-50;n(!L)},[]);return r.useEffect(()=>{i||e.length===0||!u&&f&&P()},[e,f,u,i,P]),i&&e.length===0?t.jsx("section",{className:"devserver-log-viewer","data-testid":"devserver-log-viewer",children:t.jsxs("div",{className:"devserver-log-viewer__loading","data-testid":"devserver-log-loading",children:[t.jsx(ee,{size:16,className:"devserver-log-viewer__spinner"}),t.jsx("span",{children:"Loading logs…"})]})}):t.jsxs("section",{className:`devserver-log-viewer${T?" devserver-log-viewer--fullscreen":""}`,"data-testid":"devserver-log-viewer",children:[t.jsxs("header",{className:"devserver-log-viewer__toolbar",children:[t.jsxs("div",{className:"devserver-log-viewer__toolbar-meta",children:[t.jsx("span",{className:"devserver-log-viewer__title",children:"Logs"}),t.jsxs("span",{className:"devserver-log-viewer__count","data-testid":"devserver-log-count",children:[y!==null?`${e.length}/${y}`:`${e.length}`," lines"]})]}),t.jsxs("div",{className:"devserver-log-viewer__toolbar-actions",children:[t.jsxs("label",{className:"devserver-log-viewer__severity",htmlFor:"devserver-log-severity-filter",children:[t.jsx("span",{className:"visually-hidden",children:"Filter logs by severity"}),t.jsxs("select",{id:"devserver-log-severity-filter",className:"select devserver-log-viewer__severity-select",value:R,onChange:p=>A(p.target.value),"data-testid":"devserver-log-severity-filter","aria-label":"Filter logs by severity",children:[t.jsx("option",{value:"all",children:"All severities"}),t.jsx("option",{value:"info",children:"Info"}),t.jsx("option",{value:"warn",children:"Warn"}),t.jsx("option",{value:"error",children:"Error"})]})]}),t.jsxs("label",{className:"devserver-log-viewer__search",htmlFor:"devserver-log-search",children:[t.jsx("span",{className:"visually-hidden",children:"Search logs"}),t.jsx(it,{size:14}),t.jsx("input",{id:"devserver-log-search",className:"input devserver-log-viewer__search-input",type:"text",value:d,onChange:p=>M(p.target.value),placeholder:"Search logs","data-testid":"devserver-log-search-input","aria-label":"Search logs"})]}),d.trim().length>0&&t.jsxs("span",{className:"devserver-log-viewer__matches","data-testid":"devserver-log-match-count",children:[j," match",j===1?"":"es"]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon",onClick:()=>S(p=>!p),"data-testid":"devserver-log-fullscreen-toggle","aria-label":T?"Exit fullscreen logs":"Enter fullscreen logs",children:T?t.jsx(lt,{size:14}):t.jsx(ct,{size:14})})]})]}),t.jsxs("div",{className:"devserver-log-viewer__body",children:[g&&t.jsx("div",{className:"devserver-log-viewer__load-more","data-testid":"devserver-log-load-more",children:t.jsx("button",{type:"button",className:"btn btn-sm touch-target",onClick:w,disabled:o,"data-testid":"devserver-log-load-more-button",children:o?t.jsxs(t.Fragment,{children:[t.jsx(ee,{size:14,className:"devserver-log-viewer__spinner"}),"Loading older logs…"]}):"Load older logs"})}),t.jsxs("div",{ref:k,className:"devserver-log-viewer__content",onScroll:h,"data-testid":"devserver-log-content",children:[!i&&D.length===0&&t.jsx("p",{className:"devserver-log-viewer__empty","data-testid":"devserver-log-empty",children:e.length===0?"No logs yet. Start the dev server to see output.":_.length===0?"No log lines match the selected severity.":"No log lines match your search."}),D.map(p=>{const E=me(p.text),L=Dt(p.timestamp);return t.jsxs("div",{className:"devserver-log-line",children:[L&&t.jsx("span",{className:"devserver-log-timestamp","data-testid":"devserver-log-timestamp",children:L}),p.stream==="stderr"&&t.jsx("span",{className:"devserver-log-stream-badge","data-testid":"devserver-log-stderr-badge",children:"ERR"}),t.jsx("span",{className:"devserver-log-text",children:ot(At(E,d.trim()))})]},p.id)})]}),u&&f&&t.jsxs("button",{type:"button",className:"btn btn-sm devserver-log-viewer__new-logs-button",onClick:P,"data-testid":"devserver-log-jump-button",children:[t.jsx(dt,{size:14}),"New logs"]})]})]})}const Pt="devserver-preview-iframe";function zt({url:e,embedStatus:i,onEmbedStatusChange:o,iframeRef:g,blockReason:y,onRetry:w,className:f=Pt,embedContext:k}){const U=y??k??null,[C,T]=r.useState(0);r.useEffect(()=>{!e||i!=="unknown"||(T(d=>d+1),o("loading"))},[i,o,e]);const S=r.useCallback(()=>{const d=g.current;if(!d){o("embedded");return}try{if(d.contentWindow?.location?.href==="about:blank"&&d.src!=="about:blank"){o("blocked");return}}catch{}o("embedded")},[g,o]),u=r.useCallback(d=>{d.stopPropagation(),o("error")},[o]),n=r.useCallback(()=>{e&&window.open(e,"_blank","noopener,noreferrer")},[e]);return e?t.jsxs("div",{className:"devserver-preview-iframe-shell",children:[t.jsx("iframe",{src:e,ref:g,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",className:f,title:"Dev server preview",onLoad:S,onError:u,onErrorCapture:u,"data-testid":"devserver-preview-iframe"},`${e}-${C}`),i==="loading"&&t.jsxs("div",{className:"devserver-preview-overlay","data-testid":"devserver-preview-loading",children:[t.jsx(ee,{size:16,className:"dev-server-spin"}),t.jsx("span",{children:"Loading preview..."})]}),i==="blocked"&&t.jsxs("div",{className:"devserver-preview-blocked-panel",role:"alert","data-testid":"devserver-preview-blocked-panel",children:[t.jsx(Me,{className:"devserver-preview-blocked-icon","aria-hidden":"true"}),t.jsxs("div",{children:[t.jsx("p",{className:"devserver-preview-blocked-title",children:"Preview cannot be embedded"}),U&&t.jsx("p",{className:"devserver-preview-blocked-context",children:U})]}),t.jsx("p",{className:"devserver-preview-blocked-description",children:"You can view the preview in a separate browser tab."}),t.jsxs("div",{className:"devserver-preview-blocked-actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",onClick:n,children:"Open in new tab"}),w&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:w,children:"Retry"})]})]}),i==="error"&&t.jsxs("div",{className:"devserver-preview-error-panel",role:"alert","data-testid":"devserver-preview-error-panel",children:[t.jsx(Ae,{className:"devserver-preview-blocked-icon","aria-hidden":"true"}),t.jsxs("div",{children:[t.jsx("p",{className:"devserver-preview-blocked-title",children:"Unable to load preview"}),U&&t.jsx("p",{className:"devserver-preview-blocked-context",children:U})]}),t.jsx("p",{className:"devserver-preview-blocked-description",children:"You can view the preview in a separate browser tab."}),t.jsxs("div",{className:"devserver-preview-blocked-actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",onClick:n,children:"Open in new tab"}),w&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:w,children:"Retry"})]})]})]}):null}const Ee={stopped:{className:"dev-server-status-badge--stopped",label:"Stopped"},starting:{className:"dev-server-status-badge--starting",label:"Starting..."},running:{className:"dev-server-status-badge--running",label:"Running"},stopping:{className:"dev-server-status-badge--starting",label:"Stopping..."},failed:{className:"dev-server-status-badge--failed",label:"Failed"}};function Le(e){return e instanceof Error?e.message:String(e)}function $e(e){return e==="."?"root":e}function Re(e){return e?e==="root"?".":e:null}function _e(e,i,o){return!i||e.scriptName!==i?!1:o?$e(e.cwd)===o:!0}function $t(e){return e.cwd==="."?"root":e.cwd}function Ft(e){return e.length<=60?e:`${e.slice(0,60)}…`}function Wt({addToast:e,projectId:i}){const{session:o,detectedCommands:g,previewUrl:y,isLoading:w,error:f,startServer:k,stopServer:U,restartServer:C,setPreviewUrl:T,detectCommands:S,refresh:u}=St(i),n=o?.status??"stopped",d=n==="running"||n==="starting",M=Ee[n]??Ee.stopped,{entries:R,loading:A,loadingMore:_,hasMore:D,total:j,loadMore:P}=jt(i,!!i),h=y,p=o?.config?.cwd??null,[E,L]=r.useState(!0),[z,F]=r.useState(""),[O,H]=r.useState(""),[x,a]=r.useState(null),[s,c]=r.useState(null),[l,v]=r.useState("embedded"),N=l==="embedded"?h:null,{embedStatus:b,setEmbedStatus:Fe,resetEmbedStatus:I,iframeRef:q,isEmbedded:Oe,isBlocked:te,blockReason:re,retry:fe}=Rt(N),[pe,W]=r.useState(!1),he=r.useRef(b);r.useEffect(()=>{const m=he.current!==b;te&&m&&W(!0),b==="embedded"&&W(!1),he.current=b},[b,te]),r.useEffect(()=>{W(!1)},[h]);const J=r.useMemo(()=>{if(!x)return null;const m=Re(p);return g.find($=>!($.scriptName!==x||m&&$.cwd!==m||o?.config?.command&&$.command!==o.config.command))??g.find($=>_e($,x,p))??null},[g,o?.config?.command,x,p]);r.useEffect(()=>{typeof S=="function"&&S().catch(m=>{e(Le(m),"error")})},[e,S]),r.useEffect(()=>{if(x){L(!1);return}L(!0)},[x]),r.useEffect(()=>{if(o?.status==="running"||o?.status==="starting"){o.config?.command?.trim().length>0&&F(o.config.command);return}if(J){F(J.command);return}g.length>0&&F(m=>m.trim().length>0?m:g[0]?.command??"")},[g,J,o?.config?.command,o?.status]),r.useEffect(()=>{H(h??"")},[h]);const se=r.useCallback(()=>{h&&window.open(h,"_blank","noopener,noreferrer")},[h]),ge=r.useCallback(()=>{W(!1),fe()},[fe]),Be=r.useCallback(()=>{try{const m=q.current;if(m?.contentWindow){m.contentWindow.location.reload(),W(!1),I();return}}catch{}if(!(!h||!q.current))try{const m=new URL(h);m.searchParams.set("_t",Date.now().toString()),q.current.src=m.toString(),W(!1),I()}catch{q.current.src=h,W(!1),I()}},[h,q,I]),Y=r.useCallback(async(m,$,ne)=>{c(m);try{await $(),e(ne,"success")}catch(Ke){e(Le(Ke),"error")}finally{c(null)}},[e]),He=r.useCallback(m=>{a(m.scriptName),L(!1),F(m.command),e(`Selected ${m.scriptName} script.`,"success")},[e]),Ve=r.useCallback(()=>{a(null),L(!0),e("Cleared selected dev server script.","success")},[e]),We=()=>{const m=z.trim();if(m.length===0){e("Enter a command before starting the dev server.","warning");return}const $=Re(p)??".",ne=J?.cwd??$;Y("start",()=>k(m,ne),"Dev server started.")},Xe=()=>{Y("stop",U,"Dev server stopped.")},qe=()=>{Y("restart",C,"Dev server restarted.")},Ge=()=>{const m=O.trim(),$=m.length>0?m:null;Y("preview",()=>T($),$?"Preview URL updated.":"Preview URL override cleared.")},Ie=r.useCallback(()=>{f&&u()},[f,u]),Je=n==="starting"||n==="running"||s!==null,Ye=n==="stopped"||s!==null,Qe=n==="stopped"||n==="starting"||s!==null;return t.jsxs("div",{className:"dev-server-view","data-testid":"dev-server-view",children:[t.jsxs("section",{className:"dev-server-header","aria-label":"Dev server controls header",children:[t.jsxs("div",{className:"dev-server-header-title",children:[t.jsx(ut,{size:16}),t.jsx("h2",{children:"Dev Server"}),t.jsx("span",{className:`dev-server-status-badge ${M.className}`,"data-testid":"dev-server-status-badge",children:M.label})]}),t.jsxs("div",{className:"dev-server-header-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-primary btn-sm",onClick:We,disabled:Je,"data-testid":"dev-server-start-button",children:[t.jsx(vt,{size:14}),t.jsx("span",{children:s==="start"?"Starting...":"Start"})]}),t.jsxs("button",{type:"button",className:"btn btn-danger btn-sm",onClick:Xe,disabled:Ye,"data-testid":"dev-server-stop-button",children:[t.jsx(mt,{size:14}),t.jsx("span",{children:s==="stop"?"Stopping...":"Stop"})]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:qe,disabled:Qe,"data-testid":"dev-server-restart-button",children:[t.jsx(ft,{size:14}),t.jsx("span",{children:s==="restart"?"Restarting...":"Restart"})]})]})]}),t.jsxs("section",{className:"dev-server-panel dev-server-config","aria-label":"Dev server configuration",children:[t.jsxs("div",{className:"dev-server-section-header",children:[t.jsx("h3",{children:"Configuration"}),w&&t.jsx("span",{className:"dev-server-muted",children:"Loading..."})]}),w&&!o&&g.length===0&&t.jsxs("div",{className:"dev-server-loading-state","data-testid":"dev-server-loading-state",children:[t.jsx(ee,{size:16,className:"dev-server-spin"}),t.jsx("span",{children:"Loading dev server configuration..."})]}),f&&t.jsxs("div",{className:"dev-server-error-box",role:"alert","data-testid":"dev-server-error-box",children:[t.jsx("p",{children:f}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:Ie,children:"Retry"})]}),t.jsxs("div",{className:"dev-server-section",children:[t.jsx("h3",{children:"Script Selection"}),x&&t.jsxs("div",{className:"dev-server-selected","data-testid":"dev-server-selected-summary",children:[t.jsx("span",{className:"dev-server-candidate-name",children:x}),t.jsx("span",{className:"dev-server-candidate-source",children:p??"root"}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>L(!0),"data-testid":"dev-server-change-selection",children:"Change"}),t.jsx("button",{type:"button",className:"btn btn-danger btn-sm",onClick:Ve,"data-testid":"dev-server-clear-selection",children:"Clear"})]}),E&&g.length===0&&t.jsxs("p",{className:"dev-server-empty-state","data-testid":"dev-server-empty-candidates",children:["No dev server scripts detected. Check that your project has a ",t.jsx("code",{children:"package.json"})," with a ",t.jsx("code",{children:"dev"}),", ",t.jsx("code",{children:"start"}),", or similar script."]}),E&&g.length>0&&t.jsx("div",{className:"dev-server-candidates","data-testid":"dev-server-candidates",children:g.map(m=>{const $=_e(m,x,p);return t.jsxs("button",{type:"button",className:`dev-server-candidate ${$?"dev-server-candidate--selected":""}`,onClick:()=>He(m),"data-testid":`dev-server-candidate-${m.scriptName}-${$e(m.cwd)}`,children:[t.jsx("span",{className:"dev-server-candidate-name",children:m.scriptName}),t.jsx("span",{className:"dev-server-candidate-command",children:Ft(m.command)}),t.jsx("span",{className:"dev-server-candidate-source",children:$t(m)})]},`${m.cwd}::${m.scriptName}::${m.command}`)})})]}),t.jsxs("div",{className:"dev-server-field-group",children:[t.jsx("label",{htmlFor:"dev-server-command",className:"dev-server-label",children:"Command"}),t.jsx("input",{id:"dev-server-command",className:"input",value:z,onChange:m=>F(m.target.value),placeholder:"pnpm dev","data-testid":"dev-server-command-input",readOnly:n==="running"||n==="starting"})]}),(n==="running"||n==="starting")&&o&&t.jsxs("div",{className:"dev-server-current-command","data-testid":"dev-server-current-command",children:[t.jsx("span",{className:"dev-server-label",children:"Running command"}),t.jsx("code",{children:o.config?.command??z})]}),t.jsxs("div",{className:"dev-server-preview-override",children:[t.jsx("label",{htmlFor:"dev-server-preview-input",className:"dev-server-label",children:"Preview URL Override"}),t.jsx("input",{id:"dev-server-preview-input",className:"input",type:"url",value:O,onChange:m=>H(m.target.value),placeholder:"http://localhost:3000","data-testid":"dev-server-preview-input"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:Ge,disabled:s==="preview","data-testid":"dev-server-set-preview",children:"Save"})]}),h&&t.jsxs("p",{className:"dev-server-preview-hint",children:["Auto-detected: ",h]})]}),t.jsx("div",{className:"dev-server-content",children:t.jsxs("section",{className:"dev-server-panel dev-server-logs-panel","data-testid":"dev-server-logs-panel","aria-label":"Dev server logs",children:[t.jsxs("div",{className:"dev-server-section-header",children:[t.jsx("h3",{children:"Logs"}),t.jsxs("span",{className:"dev-server-muted",children:[j??R.length," lines"]})]}),t.jsx("div",{className:"dev-server-logs-viewer","data-testid":"dev-server-log-viewer",children:t.jsx(Tt,{entries:R,loading:A,loadingMore:_,hasMore:D,total:j,onLoadMore:P,isRunning:d})})]})}),t.jsxs("section",{className:"dev-server-panel devserver-preview-panel","data-testid":"devserver-preview-panel","aria-label":"Dev server preview",children:[t.jsxs("div",{className:"devserver-preview-header",children:[t.jsxs("div",{className:"devserver-preview-title",children:[t.jsx(pt,{size:14}),t.jsx("span",{children:"Preview"})]}),t.jsxs("span",{className:"devserver-preview-url-badge devserver-preview-url-badge--auto",title:h??"No preview URL","data-testid":"devserver-preview-url-badge",children:["Auto",h?` · ${h}`:" · Not available"]}),t.jsxs("div",{className:"devserver-preview-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>v(m=>m==="embedded"?"external":"embedded"),"data-testid":"devserver-preview-mode-toggle",children:l==="embedded"?"External only":"Embedded"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon",title:"Open in new tab",onClick:se,disabled:!h,"data-testid":"devserver-preview-open-tab",children:t.jsx(ht,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon",title:"Refresh preview",onClick:Be,disabled:!h,"data-testid":"devserver-preview-refresh",children:t.jsx(gt,{})})]})]}),t.jsxs("div",{className:"devserver-preview-container","data-embed-status":b,"data-embedded":Oe?"true":"false",children:[!h&&!d&&t.jsx("p",{className:"devserver-preview-empty",children:"Start a dev server to see a live preview here."}),!h&&d&&t.jsx("p",{className:"devserver-preview-empty",children:"No preview URL detected. Start the dev server or set a manual URL to preview your app."}),h&&l==="external"&&t.jsxs("div",{className:"devserver-preview-external-only","data-testid":"devserver-preview-external-only",children:[t.jsx("p",{children:"Embedded preview is disabled. Open your app in a separate browser tab."}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm touch-target",onClick:se,"data-testid":"devserver-preview-external-open-tab",children:"Open in new tab"})]}),h&&l==="embedded"&&pe&&te&&t.jsxs("div",{className:b==="error"?"devserver-preview-error-panel":"devserver-preview-blocked-panel","data-testid":"devserver-preview-fallback",role:"alert",children:[b==="error"?t.jsx(Ae,{className:"devserver-preview-blocked-icon","aria-hidden":"true"}):t.jsx(Me,{className:"devserver-preview-blocked-icon","aria-hidden":"true"}),t.jsxs("div",{children:[t.jsx("p",{className:"devserver-preview-blocked-title",children:b==="error"?"Preview failed":"Preview blocked"}),re&&t.jsx("p",{className:"devserver-preview-blocked-context",children:re})]}),t.jsx("p",{className:"devserver-preview-blocked-description",children:"Open the preview in a new tab, or retry embedded mode after checking your server settings."}),t.jsxs("div",{className:"devserver-preview-blocked-actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",onClick:se,"data-testid":"devserver-preview-fallback-open-tab",children:"Open preview in new tab"}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:ge,"data-testid":"devserver-preview-fallback-retry",children:"Retry embedded preview"})]})]}),h&&l==="embedded"&&!pe&&t.jsx(zt,{url:h,embedStatus:b,onEmbedStatusChange:Fe,iframeRef:q,blockReason:re,onRetry:ge})]})]})]})}export{Wt as DevServerView};
@@ -1 +1 @@
1
- import{r as i,j as r}from"./vendor-react-K0fH_qHe.js";import{ew as f,ex as g,dg as b,b as y,ad as P,a8 as H,a9 as C,L as O,aq as v}from"./index-u6AOHWO5.js";import{F as z}from"./folder-open-D8Qfxakh.js";function D({value:o,onChange:d,placeholder:m,onInputKeyDown:x,nodeId:l,localNodeId:h}){const[e,n]=i.useState({isOpen:!1,loading:!1,error:null,currentPath:"",parentPath:null,entries:[],showHidden:!1}),a=i.useCallback(async(s,c=!1)=>{n(t=>({...t,loading:!0,error:null}));try{const t=await f(s,c,l,h);n(u=>({...u,loading:!1,currentPath:t.currentPath,parentPath:t.parentPath,entries:t.entries}))}catch(t){n(u=>({...u,loading:!1,error:t instanceof Error?t.message:"Failed to browse directory"}))}},[l,h]),j=i.useCallback(()=>{n(s=>s.isOpen?{...s,isOpen:!1}:{...s,isOpen:!0})},[]);i.useEffect(()=>{e.isOpen&&!e.loading&&e.entries.length===0&&!e.error&&a(o||void 0,e.showHidden)},[e.isOpen,e.loading,e.entries.length,e.error,o,e.showHidden,a,l,h]);const p=i.useCallback(s=>{a(s,e.showHidden)},[a,e.showHidden]),k=i.useCallback(()=>{d(e.currentPath),n(s=>({...s,isOpen:!1}))},[e.currentPath,d]),w=i.useCallback(()=>{n(s=>{const c=!s.showHidden;return{...s,showHidden:c}})},[]);i.useEffect(()=>{e.isOpen&&e.currentPath&&a(e.currentPath,e.showHidden)},[e.showHidden]);const N=e.currentPath?g(e.currentPath):[];return r.jsxs("div",{className:"directory-picker",children:[r.jsxs("div",{className:"directory-picker-input-row",children:[r.jsx("input",{type:"text",className:"input directory-picker-input",value:o,onChange:s=>d(s.target.value),onKeyDown:x,placeholder:m||"/path/to/your/project"}),r.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm directory-picker-browse-btn",onClick:j,"aria-label":e.isOpen?"Close directory browser":"Browse directories",children:[e.isOpen?r.jsx(z,{size:16}):r.jsx(b,{size:16}),r.jsx("span",{children:"Browse"})]})]}),e.isOpen&&r.jsxs("div",{className:"directory-picker-browser",role:"tree","aria-label":"Directory browser",children:[r.jsx("div",{className:"directory-picker-breadcrumbs",children:N.map((s,c)=>r.jsxs("span",{className:"directory-picker-breadcrumb-item",children:[c>0&&r.jsx(y,{size:12,className:"directory-picker-breadcrumb-sep"}),r.jsx("button",{type:"button",className:"directory-picker-breadcrumb",onClick:()=>p(s.path),title:s.path,children:s.label})]},s.path))}),r.jsxs("div",{className:"directory-picker-toolbar",children:[e.parentPath&&r.jsxs("button",{type:"button",className:"btn btn-sm btn-secondary directory-picker-up-btn",onClick:()=>p(e.parentPath),"aria-label":"Go to parent directory",title:"Parent directory",children:[r.jsx(P,{size:14}),r.jsx("span",{children:"Up"})]}),r.jsxs("button",{type:"button",className:"btn btn-sm btn-secondary directory-picker-hidden-toggle",onClick:w,"aria-label":e.showHidden?"Hide hidden directories":"Show hidden directories",title:e.showHidden?"Hide hidden":"Show hidden",children:[e.showHidden?r.jsx(H,{size:14}):r.jsx(C,{size:14}),r.jsx("span",{children:e.showHidden?"Hide hidden":"Show hidden"})]})]}),e.loading?r.jsxs("div",{className:"directory-picker-loading",children:[r.jsx(O,{size:20,className:"animate-spin"}),r.jsx("span",{children:"Loading…"})]}):e.error?r.jsxs("div",{className:"directory-picker-error",children:[r.jsx(v,{size:16}),r.jsx("span",{children:e.error})]}):r.jsx("div",{className:"directory-picker-entries",children:e.entries.length===0?r.jsx("div",{className:"directory-picker-empty",children:"No subdirectories"}):e.entries.map(s=>r.jsxs("button",{type:"button",className:"directory-picker-entry",onClick:()=>p(s.path),role:"treeitem",title:s.path,children:[r.jsx(b,{size:16,className:"directory-picker-entry-icon"}),r.jsx("span",{className:"directory-picker-entry-name",children:s.name}),s.hasChildren&&r.jsx(y,{size:14,className:"directory-picker-entry-arrow"})]},s.path))}),r.jsxs("div",{className:"directory-picker-actions",children:[r.jsx("span",{className:"directory-picker-selected-path",title:e.currentPath,children:e.currentPath}),r.jsx("button",{type:"button",className:"btn btn-primary directory-picker-select-btn",onClick:k,children:"Select"})]})]})]})}export{D};
1
+ import{r as i,j as r}from"./vendor-react-K0fH_qHe.js";import{eC as f,eD as g,dj as b,b as y,ae as P,a9 as C,aa as H,L as O,ar as v}from"./index-DzSLVOnp.js";import{F as z}from"./folder-open-BTN2_Wuv.js";function B({value:o,onChange:d,placeholder:m,onInputKeyDown:x,nodeId:l,localNodeId:h}){const[e,n]=i.useState({isOpen:!1,loading:!1,error:null,currentPath:"",parentPath:null,entries:[],showHidden:!1}),a=i.useCallback(async(s,c=!1)=>{n(t=>({...t,loading:!0,error:null}));try{const t=await f(s,c,l,h);n(u=>({...u,loading:!1,currentPath:t.currentPath,parentPath:t.parentPath,entries:t.entries}))}catch(t){n(u=>({...u,loading:!1,error:t instanceof Error?t.message:"Failed to browse directory"}))}},[l,h]),j=i.useCallback(()=>{n(s=>s.isOpen?{...s,isOpen:!1}:{...s,isOpen:!0})},[]);i.useEffect(()=>{e.isOpen&&!e.loading&&e.entries.length===0&&!e.error&&a(o||void 0,e.showHidden)},[e.isOpen,e.loading,e.entries.length,e.error,o,e.showHidden,a,l,h]);const p=i.useCallback(s=>{a(s,e.showHidden)},[a,e.showHidden]),k=i.useCallback(()=>{d(e.currentPath),n(s=>({...s,isOpen:!1}))},[e.currentPath,d]),w=i.useCallback(()=>{n(s=>{const c=!s.showHidden;return{...s,showHidden:c}})},[]);i.useEffect(()=>{e.isOpen&&e.currentPath&&a(e.currentPath,e.showHidden)},[e.showHidden]);const N=e.currentPath?g(e.currentPath):[];return r.jsxs("div",{className:"directory-picker",children:[r.jsxs("div",{className:"directory-picker-input-row",children:[r.jsx("input",{type:"text",className:"input directory-picker-input",value:o,onChange:s=>d(s.target.value),onKeyDown:x,placeholder:m||"/path/to/your/project"}),r.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm directory-picker-browse-btn",onClick:j,"aria-label":e.isOpen?"Close directory browser":"Browse directories",children:[e.isOpen?r.jsx(z,{size:16}):r.jsx(b,{size:16}),r.jsx("span",{children:"Browse"})]})]}),e.isOpen&&r.jsxs("div",{className:"directory-picker-browser",role:"tree","aria-label":"Directory browser",children:[r.jsx("div",{className:"directory-picker-breadcrumbs",children:N.map((s,c)=>r.jsxs("span",{className:"directory-picker-breadcrumb-item",children:[c>0&&r.jsx(y,{size:12,className:"directory-picker-breadcrumb-sep"}),r.jsx("button",{type:"button",className:"directory-picker-breadcrumb",onClick:()=>p(s.path),title:s.path,children:s.label})]},s.path))}),r.jsxs("div",{className:"directory-picker-toolbar",children:[e.parentPath&&r.jsxs("button",{type:"button",className:"btn btn-sm btn-secondary directory-picker-up-btn",onClick:()=>p(e.parentPath),"aria-label":"Go to parent directory",title:"Parent directory",children:[r.jsx(P,{size:14}),r.jsx("span",{children:"Up"})]}),r.jsxs("button",{type:"button",className:"btn btn-sm btn-secondary directory-picker-hidden-toggle",onClick:w,"aria-label":e.showHidden?"Hide hidden directories":"Show hidden directories",title:e.showHidden?"Hide hidden":"Show hidden",children:[e.showHidden?r.jsx(C,{size:14}):r.jsx(H,{size:14}),r.jsx("span",{children:e.showHidden?"Hide hidden":"Show hidden"})]})]}),e.loading?r.jsxs("div",{className:"directory-picker-loading",children:[r.jsx(O,{size:20,className:"animate-spin"}),r.jsx("span",{children:"Loading…"})]}):e.error?r.jsxs("div",{className:"directory-picker-error",children:[r.jsx(v,{size:16}),r.jsx("span",{children:e.error})]}):r.jsx("div",{className:"directory-picker-entries",children:e.entries.length===0?r.jsx("div",{className:"directory-picker-empty",children:"No subdirectories"}):e.entries.map(s=>r.jsxs("button",{type:"button",className:"directory-picker-entry",onClick:()=>p(s.path),role:"treeitem",title:s.path,children:[r.jsx(b,{size:16,className:"directory-picker-entry-icon"}),r.jsx("span",{className:"directory-picker-entry-name",children:s.name}),s.hasChildren&&r.jsx(y,{size:14,className:"directory-picker-entry-arrow"})]},s.path))}),r.jsxs("div",{className:"directory-picker-actions",children:[r.jsx("span",{className:"directory-picker-selected-path",title:e.currentPath,children:e.currentPath}),r.jsx("button",{type:"button",className:"btn btn-primary directory-picker-select-btn",onClick:k,children:"Select"})]})]})]})}export{B as D};